
📎 This article includes 2 downloadable practice files ↓
Advertisement
Set operators stack the results of two queries with the same number of columns.
| Operator | Returns | Example question |
|---|---|---|
| UNION | Rows from either, duplicates removed | All places we deal with |
| UNION ALL | Rows from either, duplicates kept (faster) | One timeline of orders and payments |
| INTERSECT | Rows in both | Customers who bought Laptops and Printers |
| EXCEPT | Rows in the first, not the second | Customers who never bought a Laptop |
SELECT customer_id FROM orders WHERE product_id = 1
INTERSECT
SELECT customer_id FROM orders WHERE product_id = 3;
SELECT order_date AS day, 'Order' AS type, order_id FROM orders
UNION ALL
SELECT paid_on, 'Payment', order_id FROM payments
ORDER BY day, type;
Column names come from the first query; one ORDER BY at the very end sorts the combined result.
💡 Oracle calls EXCEPT
MINUS. MySQL added INTERSECT and EXCEPT only in 8.0.31; on older MySQL use EXISTS / NOT EXISTS.Common mistakes
- UNION when you meant UNION ALL: two genuine ₹499 payments on the same day collapse into one.
- Columns in a different order in the two queries: SQL matches by position, not by name.
Practice
Download shop2.db and this lesson’s exercise file below. Open the database in DB Browser for SQLite (free), paste each task into the Execute SQL tab and compare with the expected result printed under it. Answers are at the bottom of the file.
📎 Practice files for this article
⬇ Download all 2 files (ZIP · 9 KB)
- 📄Practice database (SQLite)shop2.db: customers, products, 300 orders, payments, employees with managers and monthly targets.⬇ DB · 48 KB
- 🗃️Lesson 6 exercisesTasks with the real expected result under each, and answers at the bottom.⬇ SQL · 2 KB
Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.
Advertisement
✨ Ask AI about this article
Stuck on a step? Ask a question and the AI answers using this article.
Free · AI can be wrong