Reading history

SQL UNION, UNION ALL, INTERSECT and EXCEPT

4 min read 0 views

Combine query results with SQL set operators: UNION vs UNION ALL, INTERSECT for common rows, EXCEPT (MINUS) for missing rows, and the rules both queries must follow.

Joins combine tables side by side, adding columns. Set operators combine query results top to bottom, working on whole rows. UNION merges two results, INTERSECT keeps rows found in both, and EXCEPT keeps rows from the first result that are missing from the second. They answer questions like “which cities have students from both departments?” with very little code.

In this lesson you will learn

  • The rules two queries must follow to be combined
  • UNION versus UNION ALL
  • Finding common rows with INTERSECT
  • Finding missing rows with EXCEPT (MINUS in Oracle)
  • How set operators compare with joins and subqueries

The Rules

  • Both queries must return the same number of columns.
  • Matching columns should have compatible types.
  • Column names in the result come from the first query.
  • Only one ORDER BY is allowed, at the very end, and it sorts the combined result.

UNION and UNION ALL

-- Cities of students in CSE, and in EEE
SELECT city FROM students WHERE dept = 'CSE'
UNION
SELECT city FROM students WHERE dept = 'EEE'
ORDER BY city;

-- UNION ALL keeps duplicates
SELECT city FROM students WHERE dept = 'CSE'
UNION ALL
SELECT city FROM students WHERE dept = 'EEE'
ORDER BY city;

Output

+------------+
| city       |
+------------+
| Chattogram |
| Dhaka      |
| Sylhet     |
+------------+
(3 rows)

+------------+
| city       |
+------------+
| Chattogram |
| Chattogram |
| Dhaka      |
| Dhaka      |
| Dhaka      |
| Sylhet     |
+------------+
(6 rows)
  • UNION removes duplicates: three distinct cities.
  • UNION ALL keeps every row: six rows, one per student. It is also faster, because the database does not need to sort or hash rows to find duplicates. Use it whenever duplicates are impossible or wanted.
  • A common use is merging similar tables, such as current_orders UNION ALL archived_orders.

INTERSECT and EXCEPT

-- Cities that have both CSE and EEE students
SELECT city FROM students WHERE dept = 'CSE'
INTERSECT
SELECT city FROM students WHERE dept = 'EEE';

-- Departments that have no students
SELECT code FROM departments
EXCEPT
SELECT dept FROM students;

Output

+------------+
| city       |
+------------+
| Chattogram |
| Dhaka      |
+------------+
(2 rows)

+------+
| code |
+------+
| ME   |
+------+
(1 row)
  • INTERSECT returns rows present in both results: Chattogram and Dhaka have both CSE and EEE students, while Sylhet has only one of them.
  • EXCEPT returns rows in the first result that do not appear in the second. Department ME has no students. Order matters: A EXCEPT B is not the same as B EXCEPT A.
  • Oracle calls EXCEPT MINUS. MySQL supports INTERSECT and EXCEPT from version 8.0.31.
  • Unlike = in WHERE, set operators treat two NULLs as equal when comparing rows.

Set Operators vs Joins and Subqueries

QuestionSet operatorAlternative
Rows in A or BUNIONOR in one query (same table)
Rows in both A and BINTERSECTEXISTS or an inner join
Rows in A but not BEXCEPTNOT EXISTS or a left join with IS NULL

The alternatives are covered in SQL Joins and SQL Subqueries. Set operators read more clearly when you compare whole rows of the same shape.

Common Mistakes

  1. Different column counts in the two queries, which is an error.
  2. Putting ORDER BY in the first query instead of at the end.
  3. Using UNION when UNION ALL is meant, silently dropping legitimate duplicate rows such as two identical payments.
  4. Lining up columns in the wrong order; columns are matched by position, not by name.

Practice Exercises

Exercise 1. List all distinct department codes that appear in either the students or the courses table.

Show answer
SELECT dept FROM students
UNION
SELECT dept FROM courses
ORDER BY dept;

Exercise 2. Find student ids that are not enrolled in any course.

Show answer
SELECT id FROM students
EXCEPT
SELECT student_id FROM enrollments;

Frequently Asked Questions

Can I combine more than two queries?

Yes. Chain them: q1 UNION q2 UNION q3. In standard SQL, INTERSECT binds more tightly than UNION and EXCEPT; use parentheses or a CTE to make the order clear.

Is UNION the same as a FULL OUTER JOIN?

No. UNION stacks rows from two results with the same columns. A full outer join matches rows from two tables and places their columns side by side.

Summary

  • Set operators combine whole rows from queries with the same column layout.
  • UNION removes duplicates; UNION ALL keeps them and is faster.
  • INTERSECT keeps common rows; EXCEPT keeps rows only in the first result.
  • One ORDER BY at the end sorts the final result.

Next: SQL Common Table Expressions (WITH).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *