SQL UNION

Combine the results of two queries.

✍️ 3 exercises + code challenge in this lesson

UNION combines the result sets of two or more SELECT statements.

  • Each query must have the same number of columns, with compatible types.
  • UNION removes duplicates; UNION ALL keeps them (and is faster).
  • The column names come from the first query.

Key Takeaways: SQL UNION

Mastering SQL UNION helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL UNION Code Example

SQL
SELECT City, 'Customer' AS Type FROM Customers WHERE Country = 'Pakistan'
UNION
SELECT 'Warehouse: ' || Category, 'Stock' FROM Products WHERE Stock = 0
ORDER BY Type, City;
Free sign-in required · Google login available

SQL UNION Practice Exercises

Check what you learned in “SQL UNION”.

/ 3 solved
Fill in the blank

Combine two result sets and keep duplicates.

SELECT City FROM Customers  SELECT City FROM Customers;
✓ Correct! Not quite. Try again.
Multiple choice

What does UNION do with duplicate rows?

✓ Correct! Not quite. Try again.
Code challenge

Select CustomerName from Customers in 'UAE' UNION CustomerName from Customers in 'UK', sorted by name.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services