Sub topic 3
Sorting and limiting combined results
This chapter assumes you can write SELECT with WHERE, use DISTINCT and ORDER BY, and combine two queries with UNION, INTERSECT, or EXCEPT. Examples use PostgreSQL or MySQL syntax unless noted.
Sorting and limiting combined results
Place one ORDER BY at the end of the statement. It sorts the combined result, and it must name columns from the first query.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
ORDER BY email
LIMIT 10;To sort or limit each side before combining, wrap each query in parentheses:
(SELECT email FROM customers ORDER BY email LIMIT 5)
UNION ALL
(SELECT email FROM newsletter_subscribers ORDER BY email LIMIT 5);Precedence and parentheses with several operators
The SQL standard and PostgreSQL make INTERSECT bind more tightly than UNION and EXCEPT. Some other databases treat all three as equal and evaluate left to right. Parentheses remove the guesswork:
(SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers)
EXCEPT
SELECT email FROM unsubscribed;Equivalent queries with joins and EXISTS
The EXCEPT example above can be written with NOT EXISTS:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);The two forms differ for NULL values. The = comparison never matches NULL, so a NULL subscriber email is kept by NOT EXISTS. EXCEPT treats two NULLs as equal and removes that row.
INTERSECT ALL and EXCEPT ALL
Plain INTERSECT and EXCEPT return distinct rows. The ALL versions count duplicates. If an email appears twice in one query and once in the other, INTERSECT ALL returns it once. Check your database before using them, because SQL Server and Oracle do not support these variants.
SELECT email FROM customers
INTERSECT ALL
SELECT email FROM newsletter_subscribers;Performance considerations
UNION, INTERSECT, and EXCEPT without ALL must remove duplicates, usually with a sort or a hash step. UNION ALL skips that step, so it is usually faster.
Differences between database systems
- Row limiting: PostgreSQL and MySQL use LIMIT. SQL Server uses TOP. Oracle and standard SQL use FETCH FIRST n ROWS ONLY.
- Minus operator: Oracle uses MINUS where other systems use EXCEPT.
- ALL variants: Some systems do not support INTERSECT ALL or EXCEPT ALL.
Exercise
Write a query that returns up to 3 distinct emails from customers or newsletter_subscribers, sorted alphabetically.
Show answer
SELECT email FROM customers UNION SELECT email FROM newsletter_subscribers ORDER BY email LIMIT 3;