Browse topics

GROUP BY and HAVING

Version
19
Review
Draft

Summary#

GROUP BY combines rows that share values into one row per group, and aggregate functions summarize each group. HAVING keeps groups that satisfy a condition.

Syntax#

sql
SELECT group_column,
       aggregate(value) FILTER (WHERE row_condition)
FROM table_name
WHERE row_condition
GROUP BY group_column
HAVING aggregate_condition;

SELECT group_column, GROUPING(group_column), aggregate(value)
FROM table_name
GROUP BY ROLLUP (group_column);

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE sales (
    sale_id integer PRIMARY KEY,
    region  text NOT NULL,
    channel text NOT NULL,
    amount  integer NOT NULL
);

INSERT INTO sales VALUES
    (1, 'north', 'web', 120), (2, 'north', 'store', 80),
    (3, 'south', 'web', 200), (4, 'south', 'web', 50),
    (5, 'west', 'store', 40);

-- WHERE filters rows before grouping; HAVING filters the groups.
SELECT region,
       count(*) AS orders,
       sum(amount) AS total,
       sum(amount) FILTER (WHERE channel = 'web') AS web_total
FROM sales
WHERE amount >= 50
GROUP BY region
HAVING sum(amount) >= 200
ORDER BY region;

-- ROLLUP adds a grand total; GROUPING() identifies that row.
SELECT CASE WHEN GROUPING(region) = 1 THEN '(all)' ELSE region END AS region,
       sum(amount) AS total
FROM sales
GROUP BY ROLLUP (region)
ORDER BY GROUPING(region), region;

ROLLBACK;

Expected output#

Text
region|orders|total|web_total
north|2|200|120
south|2|250|250
(2 rows)
region|total
north|200
south|250
west|40
(all)|490
(4 rows)

Common mistakes#

An aggregate such as sum(amount) >= 200 is not allowed in WHERE; put it in HAVING. In a ROLLUP result, a null in a grouping column can be a subtotal or a real null value. Use GROUPING(column) to tell them apart.

Version applicability#

FILTER was added in PostgreSQL 9.4. GROUPING SETS, CUBE and ROLLUP arrived in PostgreSQL 9.5. Basic grouping also works on earlier versions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0