UNION Operator

All SQL topics
∙ Topic

UNION Operator

The UNION operator in SQL is used to combine the result sets of two or more SELECT queries. It removes duplicate rows by default and returns a single combined result.

📝Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
union-operator.sql
📝 Edit Code
👁 Preview
💡 This preview does not execute SQL; it’s for reading/editing the query.
💡What is UNION?
  • 1Combines results of multiple SELECT queries.
  • 2Removes duplicate rows automatically.
  • 3Works only with SELECT statements.
  • 4Returns a single result set.
💡How UNION Works
  • 1Executes multiple SELECT queries.
  • 2Merges results into one table.
  • 3Removes duplicate records.
  • 4Sorts final output optionally.
💡UNION vs UNION ALL
  • 1UNION removes duplicates.
  • 2UNION ALL keeps duplicates.
  • 3UNION is slower due to filtering.
  • 4UNION ALL is faster.
💡Rules for UNION
  • 1Same number of columns required.
  • 2Columns must have compatible data types.
  • 3Column order must match.
  • 4Only SELECT statements allowed.
💡Use Cases of UNION
  • 1Merging data from multiple tables.
  • 2Combining reports.
  • 3Creating consolidated datasets.
  • 4Data integration tasks.
💡Benefits of UNION
  • 1Simple data merging.
  • 2Clean combined results.
  • 3Reduces complex queries.
  • 4Useful in reporting systems.
🏢Real-world
  • 1Combine data from multiple tables.
  • 2Merge customer lists from different regions.
  • 3Create unified reports.
  • 4Combine archived and active records.
  • 5Merge results from different systems.
Common Mistakes
  • 1Selecting different number of columns.
  • 2Using incompatible data types.
  • 3Forgetting column order consistency.
  • 4Confusing UNION with JOIN.
Best Practices
  • 1Ensure same number of columns in both queries.
  • 2Use compatible data types.
  • 3Use aliases for clarity.
  • 4Use UNION ALL if duplicates are needed.
Quick Summary
  • UNION combines multiple SELECT results.
  • Removes duplicates by default.
  • Requires same structure in queries.
  • UNION ALL keeps duplicates.
  • Used for merging datasets.
🎯Interview Questions
Q1. What is UNION in SQL?
Answer: It combines results of multiple SELECT queries into one result set.
Q2. What is the difference between UNION and UNION ALL?
Answer: UNION removes duplicates, UNION ALL keeps duplicates.
Q3. Can UNION be used with JOIN?
Answer: No, UNION works only between SELECT queries.
Q4. What are the rules of UNION?
Answer: Same number of columns and compatible data types are required.
Q5. Is UNION fast or slow?
Answer: UNION is slower than UNION ALL due to duplicate removal.
Quiz

What does UNION operator do?