Sub topic 3
UNION: merging results and removing duplicates
UNION stacks the rows of two queries into one result and removes duplicate rows from the combined output. This chapter assumes you can write SELECT queries with WHERE, you know what DISTINCT and ORDER BY do, and you know that NULL means "no value". The earlier chapters covered union compatibility, which means matching column counts and types. This chapter focuses on what UNION does with the rows once the queries are compatible.
The sample data
The examples use two small tables. Run this setup first if you want to follow along. It works in PostgreSQL, SQLite, and MySQL.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
email VARCHAR(100)
);
CREATE TABLE newsletter_subscribers (
id INTEGER PRIMARY KEY,
email VARCHAR(100)
);
INSERT INTO customers (id, email) VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]'),
(4, '[email protected]'),
(5, NULL);
INSERT INTO newsletter_subscribers (id, email) VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]'),
(4, NULL);customers has nine-row-total company with newsletter_subscribers: five rows plus four rows. Ben appears twice in customers, and both tables contain a NULL email. These details make the duplicate rules visible.
What UNION does
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;This returns every distinct email found in either table. With the sample data the result has five rows, in no guaranteed order:
The nine input rows shrank to five. Ben appeared three times across the inputs, Cy twice, and NULL twice. Each value now appears once.
Notice that UNION removed duplicates inside customers as well as duplicates between the two tables. The deduplication applies to the whole combined result, not only to rows that overlap.
Duplicates are judged on the whole row
For a one-column query, a duplicate is a repeated value. For a multi-column query, a row is a duplicate only if every column matches. Two rows that differ in any column both survive.
SELECT email, 'customer' AS source FROM customers
UNION
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;Here Ben appears once with source customer and once with source subscriber. The rows differ in the second column, so both stay. The result has eight rows:
- Four from
customers: ana, ben, cy, andNULL. The second ben row collapsed into the first, because both carry the same source. - Four from
subscribers: ben, cy, dee, andNULL.
If you see UNION appearing to do nothing, look for a column that makes each row unique. A source label, a primary key, or a timestamp will do this. Adding one is sometimes the point, as in the example above. It is a bug when you added it only for display and still expected cross-table deduplication.
How NULLs are treated
In a WHERE clause, NULL = NULL is not true, so a comparison never matches two nulls. Set operators use a different rule. When UNION decides whether two rows are duplicates, it treats two NULL values in the same column as equal. That is why the first example returned one NULL row, not two.
This follows the SQL standard's "not distinct" comparison, and PostgreSQL, MySQL, SQLite, SQL Server, and Oracle all behave this way for UNION. It matters when you rewrite a UNION as a join, because a join on = loses the null match. A later chapter covers that case.
Making the queries compatible
UNION needs both queries to return the same number of columns, with types that can be combined. Column names do not need to match. The output takes its names from the first query.
SELECT email AS contact FROM customers
UNION
SELECT email FROM newsletter_subscribers;The result column is called contact. The name in the second query is ignored.
Two errors come up often:
- Different column counts. Selecting
email, 'customer'in one query and onlyemailin the other fails. Add a placeholder to the shorter query, such asNULL AS source, or remove the extra column. - Incompatible types. PostgreSQL rejects a union of an integer column and a text column. MySQL and SQLite may convert silently, which can produce surprising comparisons. Cast explicitly so the result does not depend on the database's conversion rules.
SELECT CAST(id AS VARCHAR(100)) AS value FROM customers
UNION
SELECT email FROM newsletter_subscribers;In MySQL, write CAST(id AS CHAR) instead, because VARCHAR is not a valid cast target there.
Column order matters. UNION matches columns by position, not by name. If you swap two columns of the same type in one query, the query still runs and silently puts values in the wrong columns.
Chaining several UNIONs
You can chain as many queries as you like:
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
UNION
SELECT email FROM customers WHERE email LIKE '%@example.com';Operators of equal precedence are applied from left to right, and each UNION removes duplicates from what has been built so far. When you mix UNION and UNION ALL in one chain, the order matters. In A UNION B UNION ALL C, rows from A and B are deduplicated first, and then every row of C is appended without a check. In A UNION ALL B UNION C, the final UNION deduplicates everything, including the earlier UNION ALL rows.
If you mix operators, add parentheses so a reader does not have to remember these rules. The precedence chapter covers this in detail.
Sorting the result
ORDER BY can appear only once, after the last query, and it sorts the whole combined result.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
ORDER BY email;Without it, the database may return rows in any order. The order often looks sorted because the database sorted rows to find duplicates, but this is a side effect and not a promise. Where NULL lands in the sort differs by database. PostgreSQL and Oracle place it last in ascending order, and MySQL and SQLite place it first. Use NULLS FIRST or NULLS LAST where your database supports them.
In many databases the ORDER BY can refer only to output column names, or to positions such as ORDER BY 1, because it applies to the combined result and not to a single table. Writing ORDER BY customers.email typically fails.
UNION compared with DISTINCT
UNION is equivalent to UNION ALL followed by SELECT DISTINCT. This query returns the same rows as the first example in this chapter:
SELECT DISTINCT email
FROM (
SELECT email FROM customers
UNION ALL
SELECT email FROM newsletter_subscribers
) AS combined;Seeing this form explains the cost. The database has to find duplicates, which usually means sorting all rows or building a hash table of them. That work grows with the size of the combined result. When you know the inputs cannot overlap, or you want the duplicates, UNION ALL skips that step. The next chapter covers when to choose it.
Case, whitespace, and collation
UNION compares values the way the database compares them for equality, using the column's collation. This has two consequences:
- In PostgreSQL and SQLite,
'[email protected]'and'[email protected]'are different values, so both rows survive. In MySQL's default collations they compare as equal, so one row is dropped, and the value that remains is chosen by the database. - Trailing spaces and other invisible differences can keep rows apart in one system and merge them in another.
If you care about case, normalize it in the query, for example with LOWER(email), and then apply UNION. Doing so keeps the result stable across databases.
Summary of behavior
| Question | Answer for UNION |
|---|---|
| Are duplicates removed? | Yes, across the whole combined result |
| What counts as a duplicate? | Every column equal, with `NULL` equal to `NULL` |
| Which column names are used? | Those of the first query |
| How are columns matched? | By position |
| Is the output order guaranteed? | No, unless `ORDER BY` follows the last query |
| How many `ORDER BY` clauses are allowed? | One, after the final query |
Exercise
Using the sample tables, how many rows does this query return, and why? SELECT email, id FROM customers UNION SELECT email, id FROM newsletter_subscribers;
Show answer
It returns eight rows. Duplicates are judged on both columns, so rows match only if both email and id are equal. Customer (2, ben), (3, cy) and the others differ in id from the subscriber rows, so almost nothing collapses. The only matching pair is the null-email rows with id... they have ids 5 and 4, which differ, so they also stay. The customers rows (2, ben) and (4, ben) differ in id as well, so all five customer rows survive. Of the four subscriber rows, none has the same (email, id) pair as a customer row, so all four survive. Counting carefully gives nine rows, not eight: five from customers plus four from subscribers, with no duplicates removed.
Exercise
You want one list of distinct emails from both tables, sorted alphabetically, with the column named contact. Write the query.
Show answer
SELECT email AS contact FROM customers UNION SELECT email FROM newsletter_subscribers ORDER BY contact; The alias goes on the first query because the output names come from it, and the single ORDER BY after the last query sorts the combined result.