09 / 17 · Combining Rows
Set operations
Combine whole query results by adding, matching or subtracting occurrences of the same output row.
On this page 4
The shop collects product lines from its website and its counter. A list of all sold products needs both sources. A list of products sold in both places needs only the overlap. A reconciliation can go further and cancel one website line against each matching counter line. Each question combines two results with the same row shape.
Add occurrences or collapse them#
Each source below yields one product label per line. A missing label is stored as NULL. The three website lines labelled tea are three observations, even though their projected values are equal.
CREATE TEMP TABLE online_products (product text);
CREATE TEMP TABLE store_products (product text);
INSERT INTO online_products VALUES
('tea'), ('tea'), ('tea'), ('coffee'), (NULL);
INSERT INTO store_products VALUES
('tea'), ('tea'), ('cocoa'), (NULL);
SELECT product FROM online_products
UNION ALL
SELECT product FROM store_products
ORDER BY product NULLS LAST;
UNION ALL returns nine rows. There are five occurrences of tea, one each of coffee and cocoa, and two occurrences of NULL. For a report of distinct labels, drop ALL. UNION then returns four rows, one per distinct output value, including one NULL. The duplicate test covers the whole output row. Two NULL markers in the same column count as matching for this test. An equality predicate in WHERE follows the separate rules of three-valued logic. (PostgreSQL 18, SELECT, SQLite, §3)
Match or cancel copies#
INTERSECT returns distinct rows found on both sides. It gives one tea and one NULL here. Its ALL form preserves as many copies as can be paired across the two inputs.
SELECT product FROM online_products
INTERSECT ALL
SELECT product FROM store_products
ORDER BY product NULLS LAST;
The three website copies of tea can be matched against only two counter copies, so the result has two tea rows. Each side has one missing label, so the result also has one NULL. With EXCEPT ALL, each right-hand copy cancels one left-hand copy of the same row.
SELECT product FROM online_products
EXCEPT ALL
SELECT product FROM store_products
ORDER BY product NULLS LAST;
The result is one coffee and one tea. The two counter copies of tea cancel two of the three website copies. The counter’s cocoa cancels nothing. Plain EXCEPT returns only coffee, because it keeps distinct left-hand rows that are absent from the right-hand result. Reversing the operands changes the question. (PostgreSQL 18, SELECT)
Let and be the number of occurrences of a particular output row on the left and right. The rules with ALL follow directly from collecting copies, pairing them or cancelling those pairs.
| Operation | Output copies | For tea with , |
|---|---|---|
UNION ALL | 5 | |
INTERSECT ALL | 2 | |
EXCEPT ALL | 1 |
How many tea rows remain
The same rules apply after projection over several columns. Including a line identifier alongside product would make the operator match the pair. Joining on product answers a different question about pairs of observations. An inner join of the three website tea lines with the two counter tea lines creates pairs. Intersection with ALL gives two copies.
Which columns are compared?#
Each side must return the same number of columns. The operator pairs columns by position and resolves a common output type for each position. Aliases on the second branch do not move its values. The first branch supplies the result column names. (PostgreSQL 18, §§7.4 and 10.5, DuckDB 1.4, Set Operations)
SELECT 101 AS order_id, 2 AS line_no
UNION ALL
SELECT 1 AS line_no, 104 AS order_id;
The right-hand row contributes (1, 104) under the output columns order_id, line_no. Both fields are integers, so the database accepts a semantically swapped pair. Write the columns in the same order on each branch. DuckDB 1.4 has a dialect-specific UNION BY NAME form for inputs with named columns. The PostgreSQL examples use positional matching. (DuckDB 1.4, Set Operations)
Which operation runs first?#
In PostgreSQL, INTERSECT binds more tightly than UNION and EXCEPT. The latter two associate from left to right. SQLite’s compound selects group from left to right. If a calculation relies on a particular grouping, give the intermediate result a name or group it explicitly in the target dialect. (PostgreSQL 18, §7.4, SQLite, §3)
An outer ORDER BY requests a row order for the combined result. UNION ALL alone makes no promise to display the left-hand rows first. In a compound PostgreSQL query, the final ORDER BY refers to an output name or position. To sort by a new expression, first put the combined query inside another SELECT. (PostgreSQL 18, SELECT)
Next#
A report with several intermediate results becomes hard to read when every stage is nested. Common table expressions and views give those stages names and distinguish a name that lives for one statement from a reusable database object.
References#
- PostgreSQL Global Development Group. PostgreSQL 18 documentation. Combining Queries, SELECT and Type Resolution define the operators, multiplicities, binding and output types.
- SQLite Project. SELECT, §3. Describes compound selects, duplicate detection and left-to-right grouping.
- DuckDB Foundation. Set Operations, DuckDB 1.4. Distinguishes positional matching from the dialect-specific matching by name.