Both combine the results of two or more SELECT statements into one result set. The difference is duplicate handling. UNION - Combines results and removes duplicate rows. - To remove duplicates, the database must sort or hash the combined data, which adds cost. UNION ALL - Combines results and keeps all rows, including duplicates. - No duplicate-removal step, so it is faster and uses less memory and tempdb. Example SELECT City FROM Customers -- Pune, Mumbai, Delhi UNION SELECT City FROM Suppliers; -- Mumbai, Chennai Result: Pune, Mumbai, Delhi, Chennai (Mumbai once) SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers; Result: Pune, Mumbai, Delhi, Mumbai, Chennai (Mumbai twice) Rules for both - Each SELECT must return the same number of columns. - Corresponding columns must have compatible data types (the result uses data type precedence). - Column names in the result come from the first SELECT. - ORDER BY can appear only once, at the end, and applies to the whole combined result: SELECT Name, 'Customer' AS Type FROM Customers UNION ALL SELECT Name, 'Supplier' FROM Suppliers ORDER BY Name; When to use UNION ALL - When duplicates are impossible (for example, combining data from different years or partitions, or adding a distinguishing "Type" column). - When duplicates are meaningful and should be counted (combining transaction lists). - Whenever performance matters and duplicates do not need removing — UNION ALL should be the default choice. When to use UNION - When you genuinely need a distinct list, such as a unique list of email addresses from several tables. - Even then, consider whether DISTINCT on a single query or a different design is clearer. Performance note A common mistake is using UNION by habit, causing unnecessary sorts on large datasets. Check the execution plan: UNION typically shows a Distinct Sort or Hash Match (aggregate) operator that UNION ALL avoids. Related set operators - INTERSECT: rows present in both queries (distinct). - EXCEPT (MINUS in Oracle): rows in the first query that are not in the second (distinct). SELECT CustomerId FROM Customers EXCEPT SELECT CustomerId FROM Orders; -- customers who never ordered UNION vs JOIN - UNION stacks rows vertically (more rows, same columns). - JOIN combines tables horizontally (more columns, matched rows). LINQ equivalents in C#: Union removes duplicates, Concat keeps them (like UNION ALL), Intersect and Except mirror the SQL operators. Interview summary: "UNION merges result sets and removes duplicates, which requires extra sorting or hashing. UNION ALL keeps everything and is faster. Use UNION ALL unless you specifically need distinct rows."
Ravindra Wadile · · 0 likes