Sub topic 8
Sorting and Limiting Combined Results
Assume you can write SELECT queries with WHERE, understand DISTINCT, and know that NULL represents a missing or unknown value. This chapter focuses on applying ORDER BY and row limits to results created with set operators.
Sort the combined result
A set operation combines the rows produced by two or more SELECT statements. To sort the complete combined result, put one ORDER BY clause after the final SELECT.
SELECT email
FROM customers
UNION
SELECT email
FROM newsletter_subscribers
ORDER BY email;The ORDER BY clause applies to the result of UNION, not only to newsletter_subscribers. The output column name usually comes from the first SELECT, so email is valid if the first query names its column email.
You can also sort by the column's position:
SELECT email, created_at
FROM customers
UNION ALL
SELECT email, created_at
FROM newsletter_subscribers
ORDER BY 2 DESC, 1;Here, column 2 is created_at, and column 1 is email. Prefer column names when possible because they are easier to understand and less likely to break when the select list changes.
Limit the combined result
A row-limiting clause placed after the final query limits the complete set-operation result.
SELECT email
FROM customers
UNION
SELECT email
FROM newsletter_subscribers
ORDER BY email
LIMIT 10;This returns the first 10 distinct emails after sorting. The order matters: without ORDER BY, the database is generally free to return any 10 rows.
To skip rows before taking a page, use OFFSET:
SELECT email
FROM customers
UNION
SELECT email
FROM newsletter_subscribers
ORDER BY email
LIMIT 10 OFFSET 20;This skips the first 20 sorted rows and returns the next 10. That is a common form of page 3 when each page contains 10 rows.
| Goal | Typical clause |
|---|---|
| Return the first 10 rows | `LIMIT 10` |
| Skip 20 rows, then return 10 | `LIMIT 10 OFFSET 20` |
| Return rows 21 through 30 | `OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY` |
The exact syntax depends on the database system. PostgreSQL, MySQL, and SQLite commonly support LIMIT. SQL Server commonly uses OFFSET ... FETCH, and Oracle supports FETCH FIRST and OFFSET. Check your database's syntax before moving a query between systems.
Limit one branch or the whole result
This query limits the combined result:
SELECT email
FROM customers
UNION ALL
SELECT email
FROM newsletter_subscribers
ORDER BY email
LIMIT 5;Sometimes you need to limit each input before combining it. Use subqueries, and give each subquery its own ORDER BY and limit. The exact parenthesis rules vary by database, but the intent is clear:
SELECT email
FROM (
SELECT email
FROM customers
ORDER BY created_at DESC
LIMIT 5
) AS recent_customers
UNION ALL
SELECT email
FROM (
SELECT email
FROM newsletter_subscribers
ORDER BY subscribed_at DESC
LIMIT 5
) AS recent_subscribers
ORDER BY email;This selects five recent rows from each table, then combines those rows and sorts the combined output. It does not select the five most recent rows overall.
Common errors
- Putting
ORDER BYbetween the two branches usually causes a syntax error or does not sort the final result. - Expecting a branch-level limit to limit the whole result produces the wrong number of rows.
- Omitting
ORDER BYmakes pagination unreliable. - Referring to a column name that exists only in the second query can fail because the final output names usually come from the first query.
- Using
UNIONwhen you need every row can remove duplicates before the limit is applied.
Exercise
You need the alphabetically first 20 distinct emails from customers and subscribers, skipping the first 40 emails. Where should ORDER BY, LIMIT, and OFFSET go?
Show answer
Put them after the final SELECT: SELECT email FROM customers UNION SELECT email FROM newsletter_subscribers ORDER BY email LIMIT 20 OFFSET 40;