What is the difference between UNION and UNION ALL, and when would you use each?
💡 Model Answer
UNION and UNION ALL are both set operations that combine the result sets of two SELECT statements, but they differ in how they handle duplicate rows. UNION removes duplicate rows from the combined result, effectively performing a DISTINCT operation on the unioned set. UNION ALL, on the other hand, returns all rows from both queries, including duplicates. Because UNION must perform a distinct operation, it typically requires an extra sort or hash step, which can add overhead, especially on large result sets. UNION ALL is faster because it simply concatenates the rows. Use UNION when you need a unique set of rows, such as when you want to list distinct product categories from two tables. Use UNION ALL when you want to preserve all occurrences, such as when aggregating logs or counting events where duplicates are meaningful. In performance‑critical scenarios, prefer UNION ALL and apply DISTINCT only if necessary.
Key points: UNION = distinct, UNION ALL = all rows, UNION ALL is usually faster, choose based on whether duplicates matter.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500