Cả hai nối kết quả của nhiều SELECT thành một, khác nhau ở chỗ khử trùng lặp:
- UNION: loại dòng trùng (phải sort + so sánh cả tập → tốn O(n log n)).
- UNION ALL: giữ mọi dòng, không sort → luôn nhanh hơn. Chỉ dùng
UNIONkhi thực sự cần khử trùng.
Điều kiện: cùng số cột và kiểu tương thích; tên cột lấy từ SELECT đầu tiên. ORDER BY chỉ đặt ở cuối toàn bộ UNION, không nhét vào từng SELECT con.
Hai phép họ hàng:
- INTERSECT: dòng có ở CẢ HAI query — SELECT user_id FROM premium INTERSECT SELECT user_id FROM active.
- EXCEPT (MINUS trong Oracle): dòng có ở query đầu nhưng không ở query sau.
Ví dụ dùng thực tế — gộp hai bảng thành báo cáo chung:
SELECT 'income' AS type, amount FROM income
UNION ALL
SELECT 'expense', -amount FROM expenses
ORDER BY type;Both stack the results of several SELECTs into one; they differ in deduplication:
- UNION: removes duplicate rows (must sort + compare the whole set → O(n log n) cost).
- UNION ALL: keeps every row, no sort → always faster. Use
UNIONonly when you genuinely need to drop duplicates.
Requirements: same column count and compatible types; column names come from the first SELECT. ORDER BY goes only at the very end of the whole UNION, not inside each sub-SELECT.
Two related operators:
- INTERSECT: rows present in BOTH queries — SELECT user_id FROM premium INTERSECT SELECT user_id FROM active.
- EXCEPT (MINUS in Oracle): rows in the first query but not the second.
Real-world example — merging two tables into one report:
SELECT 'income' AS type, amount FROM income
UNION ALL
SELECT 'expense', -amount FROM expenses
ORDER BY type;