Sub topic 7
How NULLs and duplicates are treated
This chapter assumes you can write basic SELECT queries, use DISTINCT, and know that NULL means "unknown or missing value". You should also know how UNION, UNION ALL, INTERSECT, and EXCEPT combine two queries. Here the focus is on the rules the database uses to decide whether two rows are the same, because those rules produce most surprises.
Two questions every set operator answers
Every set operator has to answer two questions.
- When are two rows considered equal?
- What happens when the same row appears more than once?
The answers are different from what you may expect from WHERE and JOIN.
Rows are compared as whole rows, with NULLs equal
In a WHERE clause, NULL = NULL is not true. It evaluates to unknown, and the row is filtered out. Set operators do not use that rule. They use a comparison the SQL standard calls "not distinct". Two values are not distinct if they are equal, or if both are NULL.
The same rule applies in DISTINCT and GROUP BY, so set operators follow the logic you already know from those features.
Comparison also covers the entire row. A row with columns (city, phone) matches another row only if every column matches. ('Oslo', NULL) matches ('Oslo', NULL). It does not match ('Oslo', '555-0100').
| Comparison | `NULL` vs `NULL` | Result |
|---|---|---|
| `WHERE a = b` | unknown | Row filtered out |
| `JOIN ... ON a = b` | unknown | No match |
| `a IS NOT DISTINCT FROM b` | true | Match |
| `UNION`, `INTERSECT`, `EXCEPT` | not distinct | Match |
| `DISTINCT`, `GROUP BY` | not distinct | Same group |
A dataset to experiment with
The examples below use three small tables. They contain repeated values and NULLs on purpose. The statements use plain SQL that works in PostgreSQL, SQLite, and recent MySQL and SQL Server versions.
CREATE TABLE customers (email VARCHAR(50));
CREATE TABLE newsletter_subscribers (email VARCHAR(50));
CREATE TABLE unsubscribed (email VARCHAR(50));
INSERT INTO customers (email) VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
(NULL),
(NULL);
INSERT INTO newsletter_subscribers (email) VALUES
('[email protected]'),
('[email protected]'),
(NULL);
INSERT INTO unsubscribed (email) VALUES
('[email protected]'),
(NULL);The customers table has five rows. It contains [email protected] twice and NULL twice. The newsletter_subscribers table has three rows, and unsubscribed has two.
Duplicates in each operator
The operators differ in how they handle duplicate rows. The rule for the plain forms is simple: UNION, INTERSECT, and EXCEPT return distinct rows. They remove duplicates even when the duplicates come from a single input query.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;This returns four rows: [email protected], [email protected], [email protected], and one NULL. Bob appeared three times across the inputs, and the two NULLs from customers and the one from the subscribers table collapsed into a single NULL. The order of the rows is not guaranteed.
UNION ALL skips the duplicate removal step.
SELECT email FROM customers
UNION ALL
SELECT email FROM newsletter_subscribers;This returns all eight rows, because 5 + 3 = 8. NULLs are not merged, because nothing is being compared.
For INTERSECT, the plain form returns each matching row once.
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;The result is [email protected] and NULL. Bob is listed once even though customers holds two Bob rows. The NULL is returned because NULL is treated as equal to NULL.
For EXCEPT, the database removes duplicates from the first result and then drops every row that also appears in the second.
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;The subscribers are Bob, Cy, and NULL. The unsubscribed list contains Cy and NULL. Removing those leaves only [email protected]. The NULL subscriber is removed because the NULL in unsubscribed counts as a match.
Summary of behavior
| Operator | Duplicates in output | NULLs match each other? | Result on the sample data |
|---|---|---|---|
| `UNION` | Removed | Yes | 4 rows |
| `UNION ALL` | Kept | Not compared | 8 rows |
| `INTERSECT` | Removed | Yes | 2 rows (Bob, NULL) |
| `EXCEPT` | Removed | Yes | 1 row (Bob) |
The distinct forms have one more property. Because they remove duplicates from each side, EXCEPT and INTERSECT ignore how many times a row occurs. A row that appears once in the first query and ten times in the second is still removed by EXCEPT. A later chapter covers INTERSECT ALL and EXCEPT ALL, which do count occurrences.
How the database decides
A single mismatch in any column makes the rows different. This is why adding a column such as 'customer' AS source to a UNION query can change the number of rows returned. Rows that used to merge now differ in the new column.
SELECT email, 'customer' AS source FROM customers
UNION
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;With the sample data, this returns six rows instead of four. Bob appears once as a customer and once as a subscriber, and NULL appears once for each source.
Where the NULL rule differs from other tools
Because set operators treat NULLs as equal and joins treat them as unequal, the two approaches can return different answers for the same question. The EXCEPT example earlier is one case. Here is the NOT EXISTS form of the same question.
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);This returns [email protected] and NULL. For the NULL subscriber, the condition u.email = s.email is never true. NOT EXISTS therefore finds no matching row and keeps the subscriber. The EXCEPT query returned only Bob.
NOT IN behaves worse.
SELECT DISTINCT email
FROM newsletter_subscribers
WHERE email NOT IN (SELECT email FROM unsubscribed);This returns no rows at all. The unsubscribed table contains a NULL, so for Bob the test NOT IN expands to email <> '[email protected]' AND email <> NULL. The second comparison is unknown, so the whole condition is never true. One NULL in the subquery makes NOT IN return nothing.
Duplicates inside a single query
Removing duplicates is not limited to rows that appear in both inputs. If one side already contains repeats, UNION collapses them.
SELECT email FROM customers
UNION
SELECT email FROM customers WHERE 1 = 0;The second query returns no rows, yet the result has only three rows (Ann, Bob, NULL). The five-row customers table was reduced because UNION applies distinct removal to the combined output. If you needed all five rows, you would use UNION ALL.
What counts as "equal" for text
For character columns, equality follows the collation of the column. In a case-insensitive collation, '[email protected]' and '[email protected]' are equal, and UNION keeps only one of them. In a case-sensitive collation they stay separate. Trailing spaces can also matter, depending on the database. If you see unexpected duplicates or unexpected merges, compare the column collations before suspecting the query.
When the two inputs have different collations, some databases raise an error and others pick one by precedence rules. Setting the collation explicitly with a COLLATE clause removes the ambiguity.
Common mistakes
- Using
UNIONwhen the inputs cannot overlap. The duplicate removal costs a sort or hash and changes nothing. UseUNION ALL. - Using
UNION ALLand expecting distinct rows. Row counts will be too high, which often shows up as inflated totals. - Assuming NULL rows will be dropped by an
INTERSECT. They are kept when both sides contain a NULL. - Rewriting
EXCEPTasNOT INwithout checking whether the subquery column can contain NULL. - Adding an extra column to a
UNIONand not noticing that rows no longer merge.
Exercise
Given the sample tables above, how many rows does SELECT email FROM customers EXCEPT SELECT email FROM unsubscribed return, and which are they?
Show answer
Two rows: [email protected] and [email protected]. The customers table holds Ann, Bob, Bob, NULL, NULL. EXCEPT removes duplicates, leaving Ann, Bob, and NULL. The unsubscribed table contains NULL and Cy. NULL matches NULL under the set-operator rule, so the NULL row is removed. Cy is not in the first result, so it has no effect.
Exercise
A teammate rewrites SELECT email FROM newsletter_subscribers EXCEPT SELECT email FROM unsubscribed as SELECT email FROM newsletter_subscribers WHERE email NOT IN (SELECT email FROM unsubscribed). The new query returns zero rows on the sample data. Explain why, and suggest a fix.
Show answer
The unsubscribed table contains a NULL. For each subscriber, NOT IN expands into a chain of <> comparisons, and the comparison with NULL is unknown, so the condition is never true and every row is filtered out. A fix is to use NOT EXISTS with a correlated subquery, or to add WHERE email IS NOT NULL inside the subquery. Neither version removes a NULL subscriber, so the result will still differ from EXCEPT. To match EXCEPT exactly, keep EXCEPT or compare with IS NOT DISTINCT FROM.