Skip to content

Instantly share code, notes, and snippets.

@MatheusR42
Created June 19, 2018 04:23
Show Gist options
  • Save MatheusR42/5b436f33c4e2956870b39fdab173d592 to your computer and use it in GitHub Desktop.
Save MatheusR42/5b436f33c4e2956870b39fdab173d592 to your computer and use it in GitHub Desktop.
Include NULL values in aggregate function COUNT() in MySQL
CREATE TABLE example_table (
hour INT
);
INSERT INTO example_table (hour)
VALUES (1),(2),(2),(NULL),(NULL),(NULL);
COMMIT;
SELECT
COUNT(DISTINCT hour) + (CASE
WHEN COUNT(hour) <> COUNT(*) THEN 1
ELSE 0
END) AS 'distinct hours'
FROM
example_table;
SELECT
hour, COUNT(*) AS 'count'
FROM
example_table
GROUP BY hour;
@MatheusR42
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment