Trung BìnhDatabase iconDatabase

UNION và UNION ALL trong SQL khác nhau như thế nào?

UNION ALL luôn nhanh hơn UNION vì không cần sort+deduplicate — chỉ dùng UNION khi thực sự cần loại bỏ duplicates; ORDER BY chỉ đặt ở cuối toàn bộ UNION, không trong từng SELECT.

  • UNION deduplicate bằng cách sort + compare toàn bộ result set — O(n log n) overhead, chậm với large results.
  • UNION ALL giữ tất cả rows kể cả duplicates, không sort — luôn nhanh hơn, dùng khi biết không có duplicates hoặc duplicates là intentional.
  • Column compatibility: cùng số columns và compatible (không nhất thiết identical) types — SELECT id, name FROM users UNION SELECT order_id, product_name FROM orders hợp lệ nếu types compatible.
  • Column names lấy từ SELECT đầu tiên.
  • ORDER BY chỉ được đặt ở cuối toàn bộ UNION, không được đặt trong từng SELECT — (SELECT ... ORDER BY x) UNION (SELECT ...) là error trong nhiều databases.
  • INTERSECT: rows xuất hiện trong CẢ HAI queries — SELECT user_id FROM premium_users INTERSECT SELECT user_id FROM active_users.
  • EXCEPT (MINUS trong Oracle): rows trong query đầu nhưng không có trong query thứ hai — SELECT email FROM all_users EXCEPT SELECT email FROM unsubscribed.
  • Practical use case: SELECT 'income' as type, amount FROM income UNION ALL SELECT 'expense', -amount FROM expenses ORDER BY date — combine two different tables for unified report.

Xem toàn bộ Database cùng filter theo level & chủ đề con.

Mở danh sách Database