A subquery is a SELECT in parentheses inside another query, and it can go in WHERE, HAVING, SELECT and FROM. A scalar subquery returns one value, a list subquery for IN or ANY one column, EXISTS only whether a row exists, and a subquery in FROM acts as a temporary table. A scalar with several rows raises an error, with zero rows it gives NULL.
SQL · Subqueries, CTE, sets
A "greater than average" threshold was typed into the query as a number. The data changed and the report lied. How to avoid the number?
In a query that finds large transactions someone typed the threshold 188.33: they once counted the average by hand. The test was green until a test row was added. Now the average is different and the threshold stayed the same. A subquery cures this class of bug: the query itself computes the threshold at run time. This lesson covers where a subquery can go, how its kinds differ and where it breaks.
How it works and why. A subquery is a SELECT in parentheses inside another query. The database runs it as part of the outer one, so its result is always fresh. The kind of subquery decides what shape it must return, and that is where almost all mistakes come from. The data used below (table transactions):
id
account_id
amount
status
1
10
100
completed
2
10
300
completed
3
11
50
failed
4
12
200
completed
5
12
400
completed
6
13
80
completed
Where a subquery can go
Figure 1. The place of a subquery decides which shape of result it must return.
A scalar subquery returns one row with one column and stands where a value is expected: in a comparison or in SELECT. With zero rows it yields NULL, and a comparison with it selects nothing. With more than one row the database raises an error. A list subquery (IN, ANY) returns one column and any number of rows. EXISTS only checks whether at least one row exists, the columns do not matter. A subquery in FROM works as a temporary table, so WHERE or JOIN can be applied to it. MySQL and PostgreSQL before version 16 require an alias for it, so people always write one. A correlated subquery refers to columns of the outer query, so logically it runs once per outer row.
Example: from a hard-coded number to a subquery. The starting query:
-- the threshold is typed in as a number, counted by hand onceSELECT id, amount
FROM transactions
WHERE amount > 188.33;
The average of six amounts is 1130 / 6 ≈ 188.33, and the query returns transactions 2, 4, 5 (amounts 300, 200, 400). Add a seventh row with 20, the average drops, and the query still cuts by the old threshold. The correct form:
-- the query computes the threshold itself: ids 2, 4, 5SELECT id, amount
FROM transactions
WHERE amount > (SELECTAVG(amount) FROM transactions);
A correlated subquery is useful for "the largest within a group":
-- correlated: the largest transaction of each account-- result: ids 2, 3, 5, 6SELECT t.id, t.account_id, t.amount
FROM transactions t
WHERE t.amount = (SELECTMAX(t2.amount)
FROM transactions t2
WHERE t2.account_id = t.account_id);
If an account has two transactions with the same maximum amount, both come back. The typical case for a subquery in FROM: aggregate first, then filter on the aggregate:
-- a subquery in FROM: the per-account total first, then the filterSELECT s.account_id, s.total
FROM (
SELECT account_id, SUM(amount) AS total
FROM transactions
WHERE status = 'completed'GROUPBY account_id
) AS s
WHERE s.total > 250;
-- accounts 10 (400) and 12 (600); 13 has only 80
If a scalar subquery returns several rows, the database stops the query with an error:
SELECT id FROM transactions
WHERE amount = (SELECT amount FROM transactions WHERE status = 'completed');
-- ERROR: more than one row returned by a subquery used as an expression
The same threshold written two ways
Wrong
WHERE amount > 188.33
The number goes stale as soon as the data changes. The test passes while old and new values happen to match.
Right
WHERE amount > (SELECT AVG…)
The threshold is computed at run time and always matches the data in the table.
Figure 2. A computed value beats a typed-in one.
Limits and alternatives. The PostgreSQL planner often runs a correlated scalar subquery with an aggregate once per outer row (the plan shows SubPlan), so on large tables it can be slow. Then it is replaced with a JOIN to a grouped table or with a window function. IN and EXISTS are usually turned into a join (a semi-join) by the planner. Deep nesting reads badly, and CTEs exist for that. Decide by EXPLAIN, not by a guess.
Typical mistakes.
A scalar subquery that returns several rows: the error more than one row returned by a subquery used as an expression. Add an aggregate, LIMIT 1 with ORDER BY, or switch = to IN.
A scalar subquery with no rows yields NULL, and the condition selects nothing with no message.
A subquery in FROM without an alias: an error in MySQL and in PostgreSQL before 16.
A correlated subquery without table aliases: the inner account_id is compared with itself and the condition is always true.
A typed-in number instead of a subquery: the test depends on the state of the data.
Check yourself
The query SELECT id FROM transactions WHERE amount = (SELECT amount FROM transactions WHERE status = 'completed') fails. Why, if the sample table has five completed transactions?
Answer
A scalar subquery must return at most one row, and here it returns five. The database answers with a more-than-one-row error. The fix depends on the intent: IN for any match, MAX or AVG for a single value.
How does a subquery in FROM differ from a subquery in WHERE in the shape of its result?
Answer
In FROM a subquery returns a table with any number of columns and rows, and it needs an alias. In WHERE it must return a value (scalar), a one-column list (IN) or only the fact that a row exists (EXISTS).
Related lessons: “How does IN differ from EXISTS?”, “What is a CTE (WITH) and why is it needed?”, “How do you find records that have no match in another table?”.
In an interview.Junior: A subquery is a query in parentheses inside another one. It can return one value for a comparison, a list for IN or a table in FROM. For example, I find transactions above the average with a scalar subquery instead of typing a number. Middle/Senior: I talk about the shape of the result: a scalar must return at most one row or it is an error, and zero rows gives NULL and a silently empty result. A correlated subquery logically runs per row, so on large tables I read EXPLAIN and, if needed, rewrite it as a JOIN with grouping or a window function. I split complex queries into CTEs.
How does IN differ from EXISTS?
IN looks for a value in a subquery's list, while EXISTS checks whether the subquery returns any row for the current row. Unlike a JOIN, neither duplicates rows. In the positive form the planner usually builds the same semi-join, so EXPLAIN decides. The real difference is negation: NOT IN breaks on a NULL in the subquery, NOT EXISTS does not.
SQL · Subqueries, CTE, sets
A query for "users with a failed transaction" returns Anna twice. How to keep one row each?
A QA engineer looks for users who had at least one failed transaction. A query with JOIN returns Anna twice because she has two failed ones. Someone adds DISTINCT, someone writes IN, someone EXISTS. All three give an answer, but they behave differently with duplicates, with NULL and on big data. This lesson covers what exactly IN and EXISTS compare and when the choice matters.
How it works and why.IN takes the value on the left and looks for it in the list the subquery returns: "is this id among these user_ids?". EXISTS compares nothing with a list: it runs the subquery for the current row and asks whether there is at least one row: "is there a failed transaction of exactly this user?". So in EXISTS the subquery is almost always correlated and its columns do not matter, people write SELECT 1. The outer row is taken once, no duplicates appear and execution may stop at the first match.
-- users with at least one failed transaction: annaSELECT u.email
FROM users u
WHERE u.id IN (
SELECT a.user_id
FROM accounts a
JOIN transactions t ON t.account_id = a.id
WHERE t.status = 'failed'
);
SELECT u.email
FROM users u
WHEREEXISTS (
SELECT1FROM accounts a
JOIN transactions t ON t.account_id = a.id
WHERE a.user_id = u.id AND t.status = 'failed'
);
On the sample data (failed transaction 3 belongs to account 11 of user 1) both queries return Anna once. For positive IN and EXISTS the PostgreSQL planner usually builds the same plan (a semi-join), so speed makes no difference. The difference shows up in two places.
What each of the two does
IN
Compares with a list
The subquery returns a list of values and the outer value is looked up in it. A NULL in the list never matches.
EXISTS
Asks about presence
For each row it checks whether the subquery has at least one row. NULL does not affect the result.
Figure 1. Both fit a semi-join: an outer row is taken once.
First place: duplicates compared with JOIN. If the same requirement were written with JOIN, a user with two failed transactions would appear twice. IN and EXISTS do not do that because they only filter rows and never multiply them:
-- a JOIN duplicates the user when there are several failuresSELECT u.email
FROM users u
JOIN accounts a ON a.user_id = u.id
JOIN transactions t ON t.account_id = a.id
WHERE t.status = 'failed';
-- with two failures for anna: two rows of anna
Second place: negation.NOT IN and NOT EXISTS are not equivalent. If the subquery has even one NULL, NOT IN returns an empty result while NOT EXISTS works correctly. This is a separate lesson, and it is the main reason to prefer EXISTS in negations.
Limits and alternatives. If you need columns from the subquery (the sum of failures, the date of the last one), EXISTS does not fit because it returns only true or false. Then use a JOIN with an aggregate or a window function. IN is handy with a short explicit list (status IN ('failed', 'cancelled')). EXISTS is handy when the condition depends on several columns of the outer row. Old rules such as "EXISTS is always faster" or "IN is always slower" are outdated: decide by EXPLAIN on a realistic volume.
Typical mistakes.
JOIN instead of EXISTS where only the fact is needed: duplicates and inflated counts.
In an EXISTS subquery the link to the outer row is forgotten (a.user_id = u.id): the condition becomes independent and the query returns either everyone or nobody.
SELECT * in EXISTS is believed to be slow. That is a myth: the columns are not evaluated, but SELECT 1 reads clearer.
NOT IN over a column that may hold NULL: an empty result with no error.
Check yourself
A user has two failed transactions. How many rows of this user do the IN, EXISTS and JOIN queries return?
Answer
IN and EXISTS return one row: they only check presence. JOIN returns two, one per failed transaction. If you need a list of users rather than transactions, JOIN needs DISTINCT and EXISTS does not.
When do you need a JOIN instead of EXISTS?
Answer
When you need values from the second table: the sum of failures, the date of the last one. EXISTS returns only yes or no, you never see the rows of the subquery.
Related lessons: “Why can NOT IN return zero rows?”, “What is a subquery and where can it be used?”, “What is EXPLAIN and how do you use it?”.
In an interview.Junior: IN compares a value with a list from the subquery, and EXISTS only checks whether at least one row exists. For "has at least one such record" I take EXISTS because a JOIN would give duplicates. Middle/Senior: In the positive form the planner usually builds the same semi-join, so speed is not an argument and I decide by EXPLAIN. The difference is fundamental in negation: NOT IN breaks on a NULL in the subquery and NOT EXISTS does not. If I need values from the second table, EXISTS does not fit and I take a JOIN with an aggregate.
Why can NOT IN return zero rows?
If the subquery in NOT IN returns even one NULL, the query returns zero rows without an error. A comparison with NULL gives UNKNOWN, so NOT IN, which expands into a chain of "not equal" conditions joined by AND, never becomes true, and WHERE keeps only true rows. Safe alternatives are NOT EXISTS or a LEFT JOIN with an IS NULL check on the right table's key.
SQL · Subqueries, CTE, sets
The query "users without accounts" returned two yesterday and nobody today. No data disappeared. What changed?
A report "users with no account" returned two people, and after a new data load it became empty. The users went nowhere: the accounts table got one row with no user_id. The query with NOT IN raised no error, it just returned zero rows. This is one of the quietest bugs in SQL and it is often asked in interviews.
How it works and why. SQL logic has three values: a condition can be true, false or unknown (UNKNOWN). A comparison with NULL always gives UNKNOWN. WHERE keeps only rows where the condition is true, so UNKNOWN is dropped just like false. x NOT IN (a, b, c) means x <> a AND x <> b AND x <> c. If one of the values is NULL, the matching factor is UNKNOWN. An AND with UNKNOWN is either false or unknown, never true. So for any x that is not in the list the answer is UNKNOWN and the row is dropped.
The sample data: users 1 anna, 2 bohdan, 3 clara, 4 dmytro; accounts 10 and 11 belong to user 1, 12 to user 2, and account 13 has user_id = NULL.
-- accounts.user_id contains NULL (account 13): the result is 0 rowsSELECT id, email
FROM users
WHERE id NOTIN (SELECT user_id FROM accounts);
-- for user 3 (clara) NOT IN expands like this3 <> 1AND3 <> 1AND3 <> 2AND3 <> NULL-- TRUE AND TRUE AND TRUE AND UNKNOWN => UNKNOWN => row dropped
The input data and the correct answer
accounts
id
user_id
10
1
11
1
12
2
13
NULL
NOT EXISTS: result
id
email
3
clara
4
dmytro
Figure 1. One NULL in accounts.user_id is enough for NOT IN to return 0 rows, while NOT EXISTS returns two.
Note that even for a user who definitely has no accounts the condition does not become true. For user 1, who is in the list, the condition is false, and that surprises nobody. What surprises is that the NULL "poisons" those who are not in the list too.
Example: three ways to fix it.
-- 1) NOT EXISTS: clara and dmytroSELECT u.id, u.email
FROM users u
WHERENOTEXISTS (SELECT1FROM accounts a WHERE a.user_id = u.id);
-- 2) LEFT JOIN + IS NULL: the same resultSELECT u.id, u.email
FROM users u
LEFTJOIN accounts a ON a.user_id = u.id
WHERE a.id ISNULL;
-- 3) NOT IN, but with NULL filtered outSELECT id, email
FROM users
WHERE id NOTIN (SELECT user_id FROM accounts WHERE user_id ISNOTNULL);
NOT EXISTS compares through a.user_id = u.id. For the account with NULL the comparison is UNKNOWN, so that row simply matches nobody and does not touch the other users. The LEFT JOIN with IS NULL is safe too. The third variant treats the symptom: it works, but it is easy to forget the filter in another query. A separate finding for the tester: an account without an owner. If user_id is mandatory by requirement it is a defect, and the answer to it is a NOT NULL constraint.
The same search for missing records written two ways
Wrong
NOT IN (SELECT user_id …)
One NULL in the list and the result is empty. There is no error, so the bug is easy to miss.
Right
NOT EXISTS (…)
A comparison with NULL matches nobody and does not touch other rows. The result is stable.
Figure 2. For "has no match", use NOT EXISTS.
Limits and alternatives. If NULL is impossible in the subquery (a NOT NULL column or an explicit list of literals without NULL), NOT IN works correctly. But the guarantee lasts only until the schema changes: someone adds a column that allows NULL and the query silently breaks. So NOT EXISTS is safer by default. One more detail: if NULL is on the left (NULL NOT IN (1, 2)) the result is UNKNOWN too. A test for this: add one row with NULL in the link column to the test data and see whether the query turned empty.
Typical mistakes.
NOT IN over a subquery on a column that allows NULL.
An empty result is read as "all fine" although the data did not change: an empty result must be checked for its cause too.
WHERE user_id <> NULL instead of IS NOT NULL: the condition is never true.
A LEFT JOIN where the absence check is written not on the key of the right table but on an ordinary column that can itself be NULL.
Check yourself
What does SELECT 5 WHERE 5 NOT IN (1, 2, NULL) return? And SELECT 5 WHERE 5 NOT IN (1, 2)?
Answer
The first returns zero rows: 5 <> NULL is unknown, so the whole condition is UNKNOWN. The second returns a row with the value 5 because both comparisons are true.
What does the NOT EXISTS query return on the sample data and why does the NULL in accounts.user_id not hurt it?
Answer
Two users, 3 and 4. For each user the subquery looks for an account with a.user_id = u.id. For the account with NULL the comparison is unknown, so that row matches nobody and does not affect the result.
Related lessons: “How does IN differ from EXISTS?”, “How do you find records that have no match in another table?”, “What is the difference between a condition in ON and in WHERE with a LEFT JOIN?”.
In an interview.Junior: If the subquery in NOT IN returns even one NULL, the query returns zero rows with no error because a comparison with NULL gives unknown. To find missing records I use NOT EXISTS or a LEFT JOIN with a NULL check. Middle/Senior: I explain the mechanism: NOT IN expands into a chain of <> joined with AND, and one UNKNOWN makes the whole condition not true. NOT IN is safe only if the column is NOT NULL, but a schema can change, so by default I use NOT EXISTS. In test data I keep a row with NULL in the link column so that such queries fail in a test, not in production. An account without an owner is a bug candidate by itself.
What is a CTE (WITH) and why is it needed?
A CTE (WITH) names an intermediate result for the duration of one query, so the query reads top to bottom. A CTE can be referenced several times. WITH RECURSIVE, a starting query plus a recursive one joined by UNION ALL, walks hierarchies. A CTE is mainly about readability, not speed; in PostgreSQL 12+ MATERIALIZED and NOT MATERIALIZED control whether it is inlined into the query.
SQL · Subqueries, CTE, sets
A 40-line query with three levels of subqueries. How to split it into steps that read well?
A report "users whose completed payments exceed 500" starts with one subquery and within a month grows two more. It has to be read from the inside out, and even the author gets lost a week later. A CTE (Common Table Expression, WITH) gives each step a name and lays the query out top to bottom. It is the simplest way to make SQL understandable for a colleague who will review it.
How it works and why. A CTE names an intermediate result for the duration of one query. After WITH name AS (…) the name is used in the main query like an ordinary table. Several CTEs can be declared separated by commas, and each next one sees the previous ones. The name lives only within this query. For a reader they are "variables" for results, and for the database a tool too: one CTE can be referenced several times without repeating a complex subquery.
Take the sample data: transactions 100 and 300 belong to account 10 (user 1), 50 is failed (account 11), 200 and 400 belong to account 12 (user 2), 80 to account 13 with no owner. First the query with a nested subquery:
-- nested subqueries: read from the inside outSELECT u.email, s.total
FROM users u
JOIN (
SELECT a.user_id, SUM(t.amount) AS total
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'completed'GROUPBY a.user_id
) s ON s.user_id = u.id
WHERE s.total > 500;
The completed sums: user 1 has 100 + 300 = 400, user 2 has 200 + 400 = 600, the account without an owner makes a group with NULL and the sum 80, which the JOIN with users drops. Only bohdan meets "more than 500". The same query, but with a CTE:
-- the same query as a CTE: reads top to bottom; result bohdan, 600WITH totals AS (
SELECT a.user_id, SUM(t.amount) AS total
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'completed'GROUPBY a.user_id
)
SELECT u.email, s.total
FROM totals s
JOIN users u ON u.id = s.user_id
WHERE s.total > 500;
The difference is not speed but that the step "compute the totals" is now named and lies apart from the step "join the users". Adding a check to it or moving it to a separate query for debugging is easy: just run the content of the CTE alone.
A recursive CTE walks a tree
categories
id
parent_id
name
1
NULL
Electronics
2
1
Phones
3
1
Laptops
4
2
Android
tree result
name
depth
Electronics
0
Phones
1
Laptops
1
Android
2
Figure 1. The starting row sets the root, and each pass adds the children of the previous level while new rows appear.
The recursive form WITH RECURSIVE has two parts joined by UNION ALL: a starting query (the root) and a recursive one that refers to the CTE itself. The database repeats the second part while it produces new rows. This is how hierarchies are walked: a category tree, a reporting line, nested comments.
-- all subcategories of category 1 with depthWITH RECURSIVE tree AS (
SELECT id, name, 0AS depth
FROM categories
WHERE id = 1UNIONALLSELECT c.id, c.name, tree.depth + 1FROM categories c
JOIN tree ON c.parent_id = tree.id
)
SELECT name, depth FROM tree ORDERBY depth, id;
In PostgreSQL a CTE can even be combined with data changes: DELETE … RETURNING inside WITH deletes and returns what was deleted at once. This is handy for cleaning up test data with a count:
-- PostgreSQL: delete and see at once what was deletedWITH gone AS (
DELETEFROM transactions
WHERE status = 'failed'RETURNING id, account_id
)
SELECTcount(*) AS deleted FROM gone;
Limits and alternatives. In PostgreSQL before version 12 a CTE was always materialised, so it acted as a wall for the optimiser. Since version 12 an ordinary CTE without side effects and with a single reference is inlined into the main query, and if there are several references it is computed once. This can be changed with the keywords MATERIALIZED and NOT MATERIALIZED:
WITH totals AS MATERIALIZED (
SELECT account_id, SUM(amount) AS total
FROM transactions
GROUPBY account_id
)
SELECT * FROM totals;
In other databases the behaviour depends on the version and the engine (MySQL supports CTEs from 8.0). So a CTE should be considered neither "faster" nor "slower" than a subquery: compare plans with EXPLAIN. A temporary table is better when the intermediate result is large and is read several times by different queries, because it can be indexed. For simple one-step queries a CTE is unnecessary.
Typical mistakes.
Expecting a CTE to always run once and "cache" the result: in PostgreSQL 12+ it depends on the number of references and the keywords.
Forgetting the stop condition in the recursive part: on data with a cycle (a category refers to its ancestor) the query never ends. A depth field with a limit or a check of visited ids helps.
Using UNION instead of UNION ALL in recursion without need: needless duplicate removal on every step.
Assuming the CTE name is visible in the next separate query: it lives only within one.
Check yourself
How does a CTE differ from a subquery in FROM and from a temporary table?
Answer
A CTE is a named subquery for the duration of one query: it can be referenced several times and reads top to bottom. A temporary table physically exists for the session, can be indexed and used in many queries. A subquery in FROM has no name and is used once.
Why does a recursive CTE need UNION ALL and what does each of the two parts do?
Answer
The first part gives the starting rows (the root of the tree), the second takes rows from the previous step and adds their children. The database repeats the second part while it returns new rows. UNION ALL joins the results of the steps without removing duplicates.
Related lessons: “What is a subquery and where can it be used?”, “How does UNION differ from UNION ALL? What are INTERSECT and EXCEPT?”, “How do you find the top N records in each group?”.
In an interview.Junior: A CTE is a named intermediate result declared with WITH. I split a complex query into steps, each with a name, and can reference a step several times. There is also a recursive variant for hierarchies, for example a category tree. Middle/Senior: I understand that a CTE is first of all about readability. In PostgreSQL 12+ an ordinary CTE with one reference is inlined into the query, and with several it is materialised, and this is controlled with the keywords MATERIALIZED and NOT MATERIALIZED. For recursion I take care of stopping on data with cycles. In PostgreSQL I use a CTE with DELETE … RETURNING to clean up test data with a count.
How does UNION differ from UNION ALL? What are INTERSECT and EXCEPT?
UNION combines the results of two queries and removes duplicates, while UNION ALL keeps all rows and is therefore faster. INTERSECT returns rows present in both queries, and EXCEPT the rows of the first that are absent from the second; it is not symmetric, so verifying a migration needs both directions. Columns are matched by position, not by name, and two NULLs count as equal.
SQL · Subqueries, CTE, sets
After a migration the user count is the same. How to find who was not moved with one query?
A team is asked to verify a migration: the old system has three users, the new one has three too, but are they the same ones? Comparing by eye is dull, and JOIN and NOT IN give scattered results. Set operations compare whole results of queries: what exists only in one, what in both, what in total. This is the shortest way to answer "do two data sets match".
How it works and why. The operations combine the results of two queries by column position. The condition: the same number of columns and compatible types. Column names come from the first query. Rows are compared as a whole, and in this comparison two NULLs count as equal, unlike the ordinary =.
Operation
What it returns
Duplicates
UNION
everything from both queries
removes
UNION ALL
everything from both queries
keeps
INTERSECT
what is in both
removes
EXCEPT
what is in the first and not in the second
removes
The variants INTERSECT ALL and EXCEPT ALL in PostgreSQL compare taking the number of repeats into account. In Oracle EXCEPT is called MINUS, and MySQL supports INTERSECT and EXCEPT since 8.0.31. The example data: legacy_users has emails a, b, c, and users has emails a, c, d.
-- legacy_users: a, b, c; users: a, c, d (emails shortened to letters)SELECT email FROM legacy_users
EXCEPT
SELECT email FROM users; -- b (did not migrate)SELECT email FROM users
EXCEPT
SELECT email FROM legacy_users; -- d (appeared new)SELECT email FROM legacy_users
INTERSECT
SELECT email FROM users; -- a, cSELECT email FROM legacy_users
UNIONSELECT email FROM users; -- a, b, c, d (4)SELECT email FROM legacy_users
UNIONALLSELECT email FROM users; -- a, b, c, a, c, d (6)
What is being compared
legacy_users
email
a
b
c
users
email
a
c
d
Figure 1. a and c match. Only the old system has b, only the new one has d.
The direction matters: EXCEPT is not symmetric. The first query tells who was lost (b), the second what extra appeared (d). A full migration check needs both. A coarser check is to compare row counts (COUNT(*)) and the sum of a control column. But only EXCEPT shows which records differ.
UNION against UNION ALL
UNION
Unique rows
A result without duplicates. For that the database sorts or hashes everything, so it is slower. a, b, c, d: 4 rows.
UNION ALL
Everything as is
Duplicates stay, no extra work. a, b, c, a, c, d: 6 rows.
Figure 2. Choose by intent: unique values or the full set.
Limits and alternatives. Columns match by position, not by name. If the types are compatible there is no error, and the data is silently swapped:
-- the types are compatible, so there is no error, but the columns are swappedSELECT first_name, last_name FROM staff
UNIONALLSELECT last_name, first_name FROM contractors;
The precedence of the operations is surprising too: INTERSECT binds tighter than UNION and EXCEPT, and those run left to right. Parentheses make the intent explicit:
-- INTERSECT binds tighter: first B INTERSECT C, then A UNION the resultSELECT id FROM a
UNIONSELECT id FROM b
INTERSECT
SELECT id FROM c;
-- parentheses make the intent explicit
(SELECT id FROM a UNIONSELECT id FROM b)
INTERSECT
SELECT id FROM c;
Two NULLs count as the same in set operations:
-- in set operations two NULLs count as the sameSELECTNULLUNIONSELECTNULL; -- 1 row
Instead of EXCEPT people often write NOT EXISTS or LEFT JOIN … IS NULL. They compare by the key you name (for example only by id), while EXCEPT compares all selected columns at once. So EXCEPT suits a quick check of several columns and NOT EXISTS a check by key. UNION ALL is faster than UNION and fits when duplicates cannot occur or are wanted: for example when merging logs from several tables.
Typical mistakes.
UNION where the count of all rows is needed: duplicates vanish and the count is understated.
A different column order in the two queries: the types match, there is no error, the data is swapped.
One EXCEPT in one direction and the conclusion "no differences": extra rows are not seen, both directions must be checked.
Mixing UNION with INTERSECT without parentheses.
ORDER BY before UNION: only the result of the whole operation is sorted, and it is written at the end.
Check yourself
legacy_users has emails a, b, c and users has a, c, d. What does SELECT email FROM users EXCEPT SELECT email FROM legacy_users return, and why is the reverse query needed?
Answer
One row, d: a record that appeared in the new system and did not exist in the old one. The reverse query (legacy EXCEPT users) shows b, the one who was not moved. A migration check needs both directions.
Why can UNION give fewer rows than the sum of the rows of both queries, and what to do if you need all of them?
Answer
UNION removes fully identical rows, so the result can be shorter. If you need all rows from both queries, write UNION ALL: it removes nothing and is faster.
Related lessons: “What is a CTE (WITH) and why is it needed?”, “How do you find records that have no match in another table?”, “How do you test database migrations?”.
In an interview.Junior: UNION combines results and removes duplicates, UNION ALL keeps them and is therefore faster. INTERSECT gives common rows, EXCEPT gives rows of the first query that are not in the second. To check a migration I run EXCEPT both ways. Middle/Senior: I remember that columns match by position, not by name, so a swapped order with compatible types gives silently wrong data. INTERSECT has higher precedence than UNION, so I write parentheses. In set operations two NULLs are equal, unlike =. If I need a comparison by key rather than by all columns, I take NOT EXISTS.