Skip to content

Instantly share code, notes, and snippets.

@YanhaoYang
Last active February 21, 2018 15:02
Show Gist options
  • Save YanhaoYang/0ebfbf85a0de0e01b58c83d085d8baa5 to your computer and use it in GitHub Desktop.
Save YanhaoYang/0ebfbf85a0de0e01b58c83d085d8baa5 to your computer and use it in GitHub Desktop.
SQL `count(1)` vs `count(*)` vs `count(id)`: only `count(id)` does not count `NULL` rows
CREATE TABLE categories ( id integer );
CREATE TABLE products ( id integer, cat_id integer );
INSERT INTO categories(id) VALUES(1);
INSERT INTO categories(id) VALUES(2);
INSERT INTO products(id, cat_id) VALUES(1, 1);
SELECT c.id, count(1) FROM categories c
LEFT JOIN products p
ON c.id = p.cat_id
GROUP BY c.id;
-- id count
-- 1 1
-- 2 1
SELECT c.id, count(*) FROM categories c
LEFT JOIN products p
ON c.id = p.cat_id
GROUP BY c.id;
-- id count
-- 1 1
-- 2 1
SELECT c.id, count(p.id) FROM categories c
LEFT JOIN products p
ON c.id = p.cat_id
GROUP BY c.id;
-- id count
-- 1 1
-- 2 0
-- See http://sqlfiddle.com/#!9/c10c25/5/0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment