← Back to SQL, page 16

sql-0302 · Easy fresher

What does SELECT COUNT(*) FROM employees WHERE salary > 200000 return: zero rows, one row with 0, or NULL?

One row containing 0. An aggregate query without GROUP BY always returns exactly one row, even when no input rows match, and COUNT of nothing is 0. With GROUP BY, the same filter would return no rows at all.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT COUNT(*) AS n FROM employees WHERE salary > 200000;
n
0

No employee earns that much, yet the query still returns a row, because aggregates without GROUP BY summarize the whole (empty) set into one row. SUM, AVG, MIN and MAX in the same position would return NULL, not 0.

Add GROUP BY dept_id and the result has no rows, since there are no groups to report. Code that reads "the first row" must handle both shapes.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT COUNT(*) AS n FROM employees WHERE salary > 200000;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Aggregates without GROUP BY return exactly one row
  • COUNT of an empty set is 0
  • SUM, AVG, MIN and MAX of an empty set are NULL
  • With GROUP BY, an empty input gives no rows

Common mistakes

  • Expecting an empty result from an ungrouped COUNT
  • Expecting 0 from SUM over no rows

Follow-ups

  • What does SUM return in the same query?
  • How would you return 0 from SUM?

Tips

  • Contrast grouped and ungrouped results