sqlcmd.net validated sql reference
intermediate grouping MySQL MariaDB SQL Server PostgreSQL SQLite

Filter Grouped Results With HAVING

Use `HAVING` to filter aggregate results after `GROUP BY`, the same way `WHERE` filters individual rows before grouping.

Docker-validated Not currently validation-green

Find departments with more than 3 employees

Finance has 2 employees and is excluded by HAVING COUNT(*) > 3. Only Engineering, with 4 employees, passes the filter.

Rows loaded before the example query runs.
Setup
CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(50));

INSERT INTO
  employees (id, name, department)
VALUES
  (1, 'Ada', 'Engineering'),
  (2, 'Grace', 'Engineering'),
  (3, 'Linus', 'Engineering'),
  (4, 'Alan', 'Engineering'),
  (5, 'Karen', 'Finance'),
  (6, 'Steve', 'Finance');
Shared across supported engines.
SQL
SELECT
  department,
  COUNT(*) AS headcount
FROM
  employees
GROUP BY
  department
HAVING
  COUNT(*) > 3
ORDER BY
  department;
Returned rows for the shared example.
departmentheadcount
Engineering4

Output is identical across all engines.

Where this command helps.

  • keeping only groups above a threshold
  • filtering summary results after aggregate calculations

What the command is doing.

HAVING is the filter clause for grouped rows. Because WHERE runs before grouping, it cannot reference aggregate functions like COUNT(*). HAVING runs after grouping and can, making it the right tool for questions like "which categories have more than N items."