
UNION ALL로 두 쿼리 합친 후에 전체를 정렬하고 싶은데, 어떻게 해?
SELECT mother.name, MAX(child.birth_year) AS birth_year
FROM people mother
JOIN people child ON mother.id = child.mother_id
GROUP BY mother.id, mother.name
UNION ALL
SELECT father.name, MAX(child.birth_year) AS birth_year
FROM people father
JOIN people child ON father.id = child.father_id
GROUP BY father.id, father.name
ORDER BY name -- ← 맨 마지막에 한 번만!
괄호 없어도 돼! 맨 끝에 붙이면 전체 결과에 적용됨!
| 위치 | 동작 |
|---|---|
| 각 SELECT 안에 ORDER BY | ❌ UNION에서 무시됨! |
| 맨 마지막에 ORDER BY | ✅ 전체 결과에 적용! |
-- 각각 ORDER BY 넣으면?
SELECT name, birth_year FROM ... ORDER BY name -- ← 무시됨!
UNION ALL
SELECT name, birth_year FROM ... ORDER BY name -- ← 무시됨!
UNION이 합치면서 개별 ORDER BY는 무시해버려!
SELECT name, birth_year FROM ...
UNION ALL
SELECT name, birth_year FROM ...
ORDER BY name -- ← 여기서 한 번만!
UNION ALL 결과 (정렬 전):
| name | birth_year |
|------|------------|
| 영숙 | 1990 |
| 철수 | 1990 |
| 미영 | 1992 |
| 동수 | 1992 |
ORDER BY name 적용 후:
| name | birth_year |
|------|------------|
| 동수 | 1992 |
| 미영 | 1992 |
| 영숙 | 1990 |
| 철수 | 1990 |
→ 전체가 name 기준으로 정렬됨!
UNION / UNION ALL 쓸 때:
ORDER BY는 맨 마지막에 한 번만!
그러면 합쳐진 전체 결과를 정렬해줘! 🔥
