TECHNOLOGIESTieInn Technologies

UNION, INTERSECT, and EXCEPT

SQL · 13 questions

Short notes

Key idea

Set operations stack the results of two queries on top of each other (instead of side by side like a join).

Syntax

SELECT city FROM customers
UNION                 -- combined, duplicates removed
SELECT city FROM stores;

UNION ALL             -- combined, duplicates kept (faster)
INTERSECT             -- in both
EXCEPT                -- in the first but not the second

Both queries need the same number of columns, with matching types, in the same order.

Example

Customers who signed up but never ordered:

SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;

Traps

  • UNION silently removes duplicates. If you're adding up rows from two months, use UNION ALL.
  • Columns match by position, not name. Swapping two columns in one query mixes them up.
  • Column names come from the first query.
  • One ORDER BY at the very end sorts the combined result.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    UNION, INTERSECT, and EXCEPT

  1. Question 1easy

    What's the difference between UNION and UNION ALL?

  2. UNION, INTERSECT, and EXCEPT

  3. Question 2medium

    SELECT first_name, city FROM a UNION ALL SELECT city, first_name FROM b. What happens?

  4. UNION, INTERSECT, and EXCEPT

  5. Question 3medium

    Customers live in 9 cities, and some have no city. What does this return?

    SELECT COUNT(*) FROM (
      SELECT city FROM customers
      UNION
      SELECT city FROM customers
    );
  6. UNION, INTERSECT, and EXCEPT

  7. Question 4medium

    What does this return?

    SELECT COUNT(*) FROM (
      SELECT customer_id FROM orders WHERE status = 'delivered'
      INTERSECT
      SELECT customer_id FROM orders WHERE status = 'cancelled'
    );
  8. UNION, INTERSECT, and EXCEPT

  9. Question 5hard

    38 customers have visited the website while logged in, and all 31 customers who ordered are among them. What does this return?

    SELECT COUNT(*) FROM (
      SELECT customer_id FROM orders
      EXCEPT
      SELECT customer_id FROM web_sessions
    );

8 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.