05 / 17 · Combining Rows
Grouping and aggregation
Group order lines by product, compute totals and filter summaries. Distinguish empty input from rows with missing amounts.
On this page 4
A sales report needs a line for each product, with the number of units and the amount sold. The order table has three tea lines. DISTINCT product can turn them into one name, but the quantities and prices no longer reach the report. We need to combine the information from the three lines before emitting one result.
One result row per group#
An aggregate computes one value from a collection of input rows. In the query below, GROUP BY product places all rows for the same product in one group. The three calls in SELECT then summarize each group. Run the order-line setup in the same session first. (PostgreSQL 18, §§2.7 and 7.2.3)
SELECT product,
COUNT(*) AS lines,
SUM(quantity) AS units,
SUM(quantity * unit_price_cents) AS revenue_cents
FROM order_lines
GROUP BY product
ORDER BY product;
| product | lines | units | revenue_cents |
|---|---|---|---|
| cocoa | 1 | 3 | 1200 |
| coffee | 2 | 3 | 1800 |
| tea | 3 | 4 | 1400 |
The tea group contains quantities 2, 1 and 1. We count three rows and sum four units. The amount expression gives 700, 350 and 350 cents before SUM combines those amounts into 1400. The result grain is one row per product. Adding order_id to GROUP BY would change it to one row per observed product and order pair. In that result, tea would occupy three rows.
Three lines form one group
The input is a collection with repetitions. Each sale contributes separately, even when the quantities and prices are identical. SUM(DISTINCT quantity) would sum only the distinct values 1 and 2 for tea. It would give 3 units instead of 4. COUNT(DISTINCT order_id) answers a different question. It gives the number of distinct orders for a product, skipping missing identifiers. For tea that count is 3. The same value as COUNT(*) here follows from the data. One order could contain two lines for the same product. (PostgreSQL 18, §§4.2.7 and 9.21; DuckDB 1.4, DISTINCT clause in aggregate functions)
Filter input rows or filter groups#
Suppose the report should show products whose revenue reached 1500 cents. Coffee qualifies because its two lines sum to 1800. Neither coffee line reaches 1500 by itself. Filtering individual lines by that threshold would discard both before the total was available.
SELECT product,
SUM(quantity * unit_price_cents) AS revenue_cents
FROM order_lines
GROUP BY product
HAVING SUM(quantity * unit_price_cents) >= 1500
ORDER BY product;
HAVING sees one total per group, so the result is one row, (coffee, 1800). WHERE still belongs in the query if we need to restrict which lines contribute to the total. For example, adding WHERE order_id >= 103 before GROUP BY leaves coffee with only the 1200-cent line. No group then satisfies HAVING. Think of WHERE as selecting the input and HAVING as selecting the summaries. This is a logical description of the result. The DBMS can choose a physical plan that computes the same answer. (PostgreSQL 18, §§2.7 and 7.2.3)
Which values can the group return?#
Consider adding order_id to the output of the first query, while still grouping only by product. Tea has orders 101, 102 and 103. The request gives PostgreSQL no rule for choosing one. It rejects this query. We can request one row per product and order, or ask an aggregate such as MIN(order_id) for one defined value per product. A minimum identifier is meaningful only if the report actually needs the lowest identifier. It need not identify the earliest order.
PostgreSQL can allow an ungrouped column from a table when the grouped columns include that table’s primary key. The key determines the column, so there is only one possible value. SQLite accepts a wider class of queries with ungrouped columns and can return a value from an arbitrary row. Explicitly grouping or aggregating the output expressions keeps the intended rule visible across engines. (PostgreSQL 18, §7.2.3; SQLite, §2.5)
Missing values and empty input#
A separate import contains two tea lines. One has a known amount of 700 cents and the other has an amount still missing. We want to distinguish the amount reported so far from the completeness of the import.
SELECT COUNT(*) AS input_rows,
COUNT(amount_cents) AS known_amounts,
SUM(amount_cents) AS known_total_cents,
AVG(amount_cents) AS mean_known_cents
FROM (VALUES (700), (NULL::integer)) AS batch(amount_cents);
The result is 2 input rows, 1 known amount, a sum of 700 and an average of 700. COUNT(*) counts rows. COUNT(amount_cents) counts the non-null values of the expression. SUM and AVG also use only the known values here. The average divides the known total by the count of known amounts. A genuinely recorded zero would count as a known value and change the average to 350. (PostgreSQL 18, §9.21; DuckDB 1.4, Handling NULL values)
If a WHERE filter removes every row, an aggregate query without GROUP BY still returns one summary row. Both counts are zero and the sum and average are NULL. With GROUP BY product there would be no observed groups and no output rows. A group can also contain rows whose amounts are all NULL. Then COUNT(*) is positive, while COUNT(amount_cents) is zero and SUM(amount_cents) is NULL. Using COALESCE(SUM(amount_cents), 0) intentionally makes an absent total display as zero. Keep a count of known values if that distinction matters to the report.
Next#
The totals currently use the product code recorded on each line. To display the catalogue name or category, the report needs fields from another table. In Inner joins we decide which pairs of rows belong together and check whether the resulting row count still supports a correct sum.
References#
- PostgreSQL Global Development Group. PostgreSQL 18 documentation, 2025. §2.7 and §7.2.3 specify grouping and filtering. §4.2.7 and §9.21 cover aggregate syntax, counts and empty inputs.
- SQLite Project. SELECT, §2.5. Documents how SQLite chooses values for ungrouped columns in aggregate queries.
- DuckDB Foundation. Aggregate Functions. DuckDB 1.4 documentation, sections on
DISTINCT, missing values and empty input.