Sub topic 8
Sorting and limiting combined results
This chapter covers how ORDER BY and row limiting work when a query uses UNION, INTERSECT, or EXCEPT. It assumes you can write basic SELECT queries with WHERE, you know DISTINCT and ORDER BY on a single query, and you know that a NULL represents a missing value. You should also know the set operators from the earlier chapters: the two queries must have the same number of columns with compatible types.
One ORDER BY for the whole result
A set operator produces a single combined result. That result has no guaranteed order. The databases may produce rows in any order, and the order you see on a small test table can change when the data grows or the plan changes.
To sort the combined result, put one ORDER BY after the last query:
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
ORDER BY email;This ORDER BY belongs to the whole statement. It does not sort only the last SELECT. The sort happens after the two queries are combined and duplicates are removed.
A plain ORDER BY inside one of the member queries, without parentheses, is a syntax error in most databases:
-- Fails in PostgreSQL, MySQL, SQL Server, and Oracle
SELECT email FROM customers ORDER BY email
UNION
SELECT email FROM newsletter_subscribers;The parser reads the first ORDER BY as the end of the statement and then does not expect UNION.
What the ORDER BY can refer to
The final ORDER BY sorts the combined result, so it can only use what that result exposes. The result takes its column names from the first query. This leads to several rules.
- Use the column names or aliases of the first
SELECT. - Use column positions, such as
ORDER BY 1. - In most databases you cannot sort by a column that is not in the select list, because the combined rows no longer have a source table row.
- In most databases you cannot sort by an expression built from source columns, such as
ORDER BY LOWER(email), unless that expression is part of the output.
The following example shows why names must come from the first query. The two tables use different column names:
SELECT email AS contact FROM customers
UNION
SELECT address FROM newsletter_subscribers
ORDER BY contact;The output column is called contact. Sorting by address would fail in most databases, because address is a name from the second query only.
Sorting by position avoids this problem and works when the names differ:
SELECT email FROM customers
UNION
SELECT address FROM newsletter_subscribers
ORDER BY 1 DESC;Positions are short, but they break silently if someone adds a column to the select lists. A named alias is easier to maintain.
If you need to sort by a computed value, put it in the select list of the first query, or wrap the set operation in a subquery:
SELECT email
FROM (
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
) AS combined
ORDER BY LOWER(email);Once the union is a derived table, the outer query is an ordinary query and any expression over its columns is allowed.
Sorting with a source column
A common pattern is to label each row with where it came from and then sort on the label. With UNION ALL, the label also stops rows from different sources being treated as duplicates.
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers
ORDER BY source, email;All customers appear first, sorted by email, followed by all subscribers. The sort keys source and email are both output columns, so this works everywhere.
If you want a custom order that is not alphabetical, add a numeric column and sort by it:
SELECT email, 1 AS priority FROM customers
UNION ALL
SELECT email, 2 AS priority FROM newsletter_subscribers
ORDER BY priority, email;Sorting inside a member query
Sometimes you really do need to sort or limit one member query before combining. The usual case is "take the top three from each group, then merge them." To do that, wrap the member query in parentheses. Most databases then accept ORDER BY and a row limit inside:
(SELECT email, created_at FROM customers
ORDER BY created_at DESC
LIMIT 3)
UNION ALL
(SELECT email, created_at FROM newsletter_subscribers
ORDER BY created_at DESC
LIMIT 3)
ORDER BY created_at DESC;This is PostgreSQL and MySQL syntax. Each parenthesized query picks its own three newest rows. Then the final ORDER BY sorts the six rows together.
Two points about this pattern:
- The inner
ORDER BYonly decides which rows pass theLIMIT. It does not promise that the rows stay in that order after they are combined. If the final order matters, repeat the sort in the outerORDER BY. - Without a
LIMIT(or an equivalent), an innerORDER BYhas no effect on the final result. Some databases reject it, and others accept it and ignore it.
SQL Server does not allow parentheses around a member query with ORDER BY. Instead, use a derived table:
SELECT email, created_at
FROM (SELECT TOP 3 email, created_at
FROM customers
ORDER BY created_at DESC) AS c
UNION ALL
SELECT email, created_at
FROM (SELECT TOP 3 email, created_at
FROM newsletter_subscribers
ORDER BY created_at DESC) AS s
ORDER BY created_at DESC;Limiting the combined result
To limit the whole combined result, put the limit clause after the final ORDER BY. The limit then applies to the sorted, combined rows.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
ORDER BY email
LIMIT 10;This returns the first ten emails of the merged and deduplicated list, in alphabetical order.
The limit syntax depends on the database:
| Database | Row limiting after the final ORDER BY |
|---|---|
| PostgreSQL | `LIMIT n` or `FETCH FIRST n ROWS ONLY` |
| MySQL, MariaDB, SQLite | `LIMIT n` |
| SQL Server | `OFFSET 0 ROWS FETCH NEXT n ROWS ONLY` (requires `ORDER BY`) |
| Oracle (12c and later) | `FETCH FIRST n ROWS ONLY` |
| Standard SQL | `FETCH FIRST n ROWS ONLY` |
In SQL Server, TOP cannot be applied to the whole combined result directly. Use OFFSET ... FETCH after the final ORDER BY, or wrap the union in a derived table and use TOP in the outer query.
Limit without ORDER BY gives arbitrary rows
A limit without an ORDER BY returns some rows, but which ones is not defined. With a set operator this is even less predictable, because the database may combine the inputs by hashing, sorting, or appending. The following query is valid but the ten rows are arbitrary:
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
LIMIT 10;Use a limit without a sort only when you need a sample and any rows will do. When you want "the first ten," state the order.
Ties and paging
If the sort key has duplicate values, the rows within a tie can come back in a different order on each run, so a limit can cut through a tie differently each time. This causes pages to overlap or skip rows when you use OFFSET for paging. Add a tiebreaker column so the sort is total:
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers
ORDER BY email, source
LIMIT 20 OFFSET 40;Here email plus source identifies every row, so each page is stable, as long as the data does not change between requests.
How the pieces fit together
The diagram shows the order in which the clauses take effect for a statement with a union, a final sort, and a limit.
Because the sort and limit come last, a limit never reduces the work of the earlier steps in a way you can count on. The database must still know the full combined result before it can pick the first rows in sorted order. Some databases can optimize this by reading only the top rows from each sorted input, but you should not rely on that.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Syntax error near `UNION` | `ORDER BY` placed in the first member query without parentheses | Move it to the end, or wrap the member in parentheses |
| "Column not found" in `ORDER BY` | Sorting by a name that exists only in the second query | Use the first query's name, an alias, or a position |
| "ORDER BY items must appear in the select list" | Sorting by a column or expression that is not an output column | Add it to the select list, or sort in an outer query |
| Rows come back in a different order each run | No `ORDER BY`, or ties in the sort key | Add the `ORDER BY`, and add a tiebreaker |
| Inner `LIMIT` seems ignored in the final order | Order inside a member query is not kept after combining | Repeat the `ORDER BY` after the last member |
| Wrong row count after `LIMIT` | The limit applied to the combined result, not to each member | Parenthesize each member to limit it separately |
Putting it together
Suppose you want the five most recently active unique email addresses across two tables, with the newest first. Each table has an email and a last_seen timestamp, and the same person may appear in both.
SELECT email, MAX(last_seen) AS last_seen
FROM (
SELECT email, last_seen FROM customers
UNION ALL
SELECT email, last_seen FROM newsletter_subscribers
) AS all_contacts
GROUP BY email
ORDER BY last_seen DESC, email
LIMIT 5;A plain UNION would not work here. It would keep an address twice if its last_seen differed between the tables, because UNION removes duplicates of whole rows, not of single columns. The UNION ALL plus GROUP BY pattern deduplicates on email alone and keeps the latest timestamp. The email tiebreaker in the ORDER BY makes the five rows deterministic.
Exercise
A query ends with SELECT email FROM customers ORDER BY email UNION SELECT address FROM newsletter_subscribers; and fails with a syntax error. Rewrite it so it returns every distinct address from both tables sorted alphabetically, and explain which name the final ORDER BY should use.
Show answer
Move the ORDER BY to the end of the statement: SELECT email FROM customers UNION SELECT address FROM newsletter_subscribers ORDER BY email;. The final ORDER BY applies to the whole combined result, and the output column takes its name from the first query, so it must use email (or the position 1), not address.
Exercise
You want the three newest rows from customers and the three newest rows from newsletter_subscribers, merged into one list sorted newest first, using PostgreSQL. Both tables have email and created_at. Write the query.
Show answer
Parenthesize each member so it can have its own ORDER BY and LIMIT, then sort the result again: (SELECT email, created_at FROM customers ORDER BY created_at DESC LIMIT 3) UNION ALL (SELECT email, created_at FROM newsletter_subscribers ORDER BY created_at DESC LIMIT 3) ORDER BY created_at DESC;. The final ORDER BY is needed because the order inside the members is not kept after combining.