Set rules
- SQL course
- Intermediate
- Lesson 63/115
- 4 min
Learn column count and type rules for set queries.
Set operation rules
In set operations each SELECT must have the same column count and compatible types. Ordering is only on the last query.
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers
ORDER BY name;This query sorts the combined list by name.
name, city is selected from customers. The result is sorted by name in ascending order.
Set operation rules — details
ORDER BY is written only after the last SELECT. It cannot appear in intermediate queries.
That ORDER BY sorts the whole combined result; you refer to columns by their names in the first SELECT or by position.
Practice Set operation rules
Combine customers and suppliers with UNION and sort with ORDER BY name.
Starter code
-- ordered union
SELECT name, city FROM customers
UNIONSample solution
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers
ORDER BY name;Expected output
name city ACME İstanbul Ayşe Ankara
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add ORDER BY
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers
____ name;
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers
ORDER BY name;
Explanation: ORDER BY is the right answer.
2 Set rules: match the terms
| Term | Meaning |
|---|---|
same columns |
required |
compatible types |
needed |
ORDER BY |
at end |
UNION |
union |
3 Where does ORDER BY go?
- After every query
- At the very end Correct answer
- After the first query
- Nowhere
Explanation: ORDER BY goes only at the very end.