Set operators in SQL
UNION, UNION ALL, INTERSECT and EXCEPT: combining the results of two queries, column compatibility, duplicate removal and where ORDER BY goes.
- 23 cards
- 6 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- The numbers
- Scenarios
- Understand
A few cards from the deck
UNION: what is it?
Show the answer
The operator that merges the rows of two queries into one result and removes duplicates.
A row present in both results appears only once. To do so the engine must compare rows, which has a cost.
The client cities are Lyon, Paris, Lyon, Nantes; the magasin cities are Lyon, Paris, Lille. What does this query return?
```sql
SELECT ville FROM client
INTERSECT
SELECT ville FROM magasin;`LyonandParis, once eachLyon,ParisandLyonNantesLyon,Paris,NantesandLille
Show the answer
LyonandParis, once eachOnly Lyon and Paris appear on both sides.
INTERSECTdeduplicates: the clients' Lyon, present twice, comes out once. Four cities would be the result of aUNION.Only one
ORDER BYis allowed, written … of the compound query: it sorts ….Show the answer
Only one
ORDER BYis allowed, written at the end of the compound query: it sorts the whole result.SELECT … UNION SELECT … ORDER BY villesorts the union. Written in the middle without parentheses, the sort makes no sense: the database refuses it.UNION ALL: what is it?
Show the answer
The operator that merges the rows of two queries without removing anything: duplicates are kept.
It returns as many rows as both queries put together. Faster, because the engine does not deduplicate: prefer it when duplicates are impossible or wanted.