…
…
SQL and Database Fundamentals · Lesson 22 / 41 · Set operations and CTEs
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The campus card system needs students and instructors in a single list. The registrar also asks two questions: which students took classes in both last fall and this fall, and which courses are not offered this term. All three questions need the results of two queries combined, overlapped, or subtracted.
So far you have always used JOIN to bring two tables together. JOIN combines tables side by side: it adds the department name to a student's row, or the course code to an enrollment's row. The row count may stay the same or change, but the result is always a wider table. The campus card question is different. Students are in one table, instructors are in another, and the person printing the cards needs one long list: 120 students first, then 20 instructors below them. No row matches another row here; the two lists are simply placed one under the other.
The tools that do this are called set operations. They take the results of two queries and combine or compare them into one result. They are the SQL versions of union, intersection, and difference from math class.
In this lesson you will:
| Operation | What it does | In math |
|---|---|---|
UNION | All rows of both results, duplicates removed | Union |
UNION ALL | All rows of both results, duplicates kept | No equivalent |
INTERSECT | Rows that appear in both results | Intersection |
EXCEPT | Rows in the first result that are not in the second | Difference |
Telling the four operations apart now will make the rest of the lesson easier. Match the questions from the case to the operations.
Which operation fits each question?
For each row, pick its match from the list, then check.
Writing a set operation is simple: you write two complete SELECT queries and put the name of the operation between them. Each query has its own FROM and, if you want, its own WHERE. The campus card list needs one more thing: the person printing the card must know whether a row belongs to a student or an instructor. For that you use the constant-value column you know from lesson 3: 'Student' AS role writes the same text on every student row.
Example 1 (case): Campus card list
SELECT first_name, last_name, 'Student' AS role FROM student UNION ALL SELECT first_name, last_name, 'Instructor' FROM instructor ORDER BY last_name, first_name;
| first_name | last_name | role |
|---|---|---|
| Clara | Abara | Instructor |
| Felix | Abara | Student |
| Mateo | Abara | Student |
| Noah | Abara | Student |
| Victor | Abara | Student |
| Yuki | Abara | Student |
(first 6 of 140 rows)
120 students and 20 instructors make 140 rows. ORDER BY was written once at the end and sorted both lists together, which is why students and instructors with the same last name appear mixed. Now put the lines of the same query in order yourself.
Put the query that returns the campus card list in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A set operation puts two results one under the other, so both results must have the same shape. There are three rules.
First, both queries must return the same number of columns. If one side has three columns and the other has two, it is unclear what to write under the third column, and PostgreSQL rejects the query. Second, the types of matching columns must be compatible: if the second column of the first query is a number, the second column of the second query must also be a number. Third, and the one people miss most often: columns are matched by position, not by name. The first column of the first query lands in the same column as the first column of the second query, whatever their names are. The column names of the result also come from the first query.
Look at Example 1 again with this in mind. The name role is written only in the first query; the constant 'Instructor' in the second query has no name, but its values still appear in the role column of the result. That is because the third column was matched with the third column. This rule also sets a trap: if you wrote last_name, first_name in reverse in the second query, the query would not fail, because both columns are text. But the instructors' last names would land in the first_name column and their first names in the last_name column. Having the same column names fixes nothing; SQL only looks at the position.
The only difference between the two operations is what happens to repeated rows. UNION ALL stacks the rows as they are. UNION looks at the whole result and keeps only one of any rows that are identical; you can think of it as applying DISTINCT from lesson 6 to the combined result. Because it has to compare all rows to do this, UNION does more work and is slower on large tables.
Let's see the difference using only the first name column.
Example 2 (case): The same two lists, two operations
SELECT first_name FROM student UNION ALL SELECT first_name FROM instructor;
Result: 140 rows. If you write UNION instead of UNION ALL in the same query, you get 55 rows.
| Query | Rows | Why |
|---|---|---|
SELECT first_name ... UNION ALL SELECT first_name ... | 140 | One row per person |
SELECT first_name ... UNION SELECT first_name ... | 55 | One row per distinct first name |
When the first names of 120 students and 20 instructors are combined with UNION, 55 rows come back. Why?
SELECT first_name FROM student UNION SELECT first_name FROM instructor;
"Then if I take first and last name together, there is no problem," you might think. First and last name together seem enough to tell two different people apart in most cases. Let's try it.
This time first and last name are taken together. How many rows come back?
SELECT first_name, last_name FROM student UNION SELECT first_name, last_name FROM instructor;
The rule that follows is this: if you do not really want to drop duplicates, write UNION ALL. If one card is printed per person, if every record is counted once, if the sales of two years are added together, then the repeats are information and must stay. UNION is the right tool only when the question asks "which distinct values exist?", such as "the list of cities that students and instructors come from". UNION ALL protects you from this mistake and is also faster.
The cell below gives the first names of students from Cairo and of the instructors of department 1 (Computer Programming) in one list. Run it: 7 rows come back. Then change UNION ALL to UNION and run it again. After that, write 'Toronto' instead of 'Cairo' and compare the two operations again.
Try it now· not graded; doesn't affect progress
In Cairo, UNION also gives 7 rows: Diego, Liam, Lucía, Mina, Nadia, Omar, Rosa. There are no repeated rows, so nothing is dropped. In Toronto there is a difference: UNION ALL gives 12 rows and UNION gives 10. Three students in Toronto are named Jin; all three rows are Jin | student, so UNION drops two of them. The same list also has two people named Diego, one student and one instructor. UNION keeps both, because the rows differ in the role column; UNION looks at the whole row, not at a single column.
The registrar's first question was "students who took classes in both 2025-Fall and 2026-Fall". This is an intersection question: you list the students of each term and keep those that are in both. INTERSECT does exactly this. We build the term lists with the JOIN you know from lesson 15: the enrollment table has no term information; that information is in course_offering.
Example 3 (case): Students who took classes in both terms
SELECT e.student_id FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 1 INTERSECT SELECT e.student_id FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 3;
Result: 88 students.
A student enrolls in several courses in one term, so each list is full of repeats on its own. INTERSECT drops repeats like UNION does, so each student appears once in the result.
EXCEPT returns the rows that are in the first result and not in the second. If you put EXCEPT between the same two queries, the question changes, and here the order matters. In UNION and INTERSECT, swapping the two queries does not change the result; in EXCEPT it does. 2026-Fall EXCEPT 2025-Fall means "studied this fall but not last fall" and returns 29 students: this year's first-year students. Guess the reverse order.
The order of the same two lists is swapped: 2025-Fall list EXCEPT 2026-Fall list. How many students come back?
SELECT e.student_id FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 1 EXCEPT SELECT e.student_id FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 3;
Putting the two numbers side by side, the table tells a story: 88 students continue, 29 students are new, and nobody studied last fall and skipped this fall. Writing a single EXCEPT and saying "there is no difference" would be wrong; each time, tell yourself which direction you are asking: "in the first and not in the second".
Most of the errors you meet with set operations come from the three rules in the second section. The messages are short, but if you know what they say, fixing them is easy.
| Query | Error | What it says |
|---|---|---|
SELECT first_name, last_name FROM student UNION SELECT first_name FROM instructor; | each UNION query must have the same number of columns | One side has 2 columns, the other has 1 |
SELECT first_name, year FROM student UNION SELECT first_name, title FROM instructor; | UNION types integer and character varying cannot be matched | Of the two columns in the same position, one is a number and the other is text |
SELECT first_name FROM student ORDER BY first_name UNION SELECT first_name FROM instructor; | syntax error at or near "UNION" | ORDER BY was written inside the first query |
The third error is the most surprising one, because the message never mentions ORDER BY. When PostgreSQL sees ORDER BY first_name, it thinks the query is finished; it does not expect the UNION that follows, so it reports "syntax error near UNION". The rule: ORDER BY is written once at the end and applies to the whole combined result. The column names you use there are also the names or aliases from the first query.
What happens when this query is run?
SELECT first_name, year FROM student UNION SELECT first_name, title FROM instructor;
There is another common fix for the column count error. For information that is missing on one side, you can write NULL or a constant in that position to make the counts equal: SELECT first_name, NULL AS last_name FROM .... The missing information then shows up as an empty cell in that column of the result.
The registrar's second question was "courses not offered this term". From all the course codes in the catalog, you subtract the codes of the courses offered this term: an EXCEPT.
Example 4 (case): Courses not offered this term
SELECT code FROM course EXCEPT SELECT c.code FROM course_offering o JOIN course c ON c.id = o.course_id WHERE o.term_id = 3 ORDER BY code;
| code |
|---|
| BUS102 |
| BUS204 |
| CPR102 |
| CPR104 |
| GEN102 |
| GEN104 |
(first 6 of 13 rows)
You could have answered this question with other tools before. In lesson 21 you used NOT EXISTS to find "rows with no counterpart", and in lesson 16 you used LEFT JOIN and IS NULL to find "rows that match nothing". All three give the same 13 courses. The advantage of the set operation is readability: the sentence "all courses minus the ones offered this term" appears in the query almost as it is. It also has a limit: EXCEPT only compares the columns in the two queries. If you also want the names of the courses that are not offered, you need to add name to both sides; with NOT EXISTS you can write any column you want in the outer query. One more subtle point: set operations treat two NULLs as equal and reduce them to one row. As you remember from lesson 7, with = NULL is not equal to anything, not even itself; set operations behave differently here.
Try it now· not graded; doesn't affect progress
Another common use of set operations is adding a report row. Under a grouped query that gives the number of students by department, you want to add a "Total" row in the same shape. The second query must also return two columns: text in the first column ('Total') and a number in the second.
Example 5 (case): Department counts and a total
SELECT d.name AS department, COUNT(*) AS students FROM student s JOIN department d ON d.id = s.department_id GROUP BY d.name UNION ALL SELECT 'Total', COUNT(*) FROM student ORDER BY students;
| department | students |
|---|---|
| New Media and Communication | 10 |
| Industrial Engineering | 12 |
| Computer Programming | 14 |
| Management Information Systems | 17 |
| Software Engineering | 20 |
| Psychology | 23 |
| Business Administration | 24 |
| Total | 120 |
(8 rows)
The total row is at the end because the sort is by the number and 120 is the largest number. GROUP BY belongs only to the first query; ORDER BY is again at the end and applies to the combined result. We wrote UNION ALL here: the student count of a department cannot equal the total, but even if it could, we would not want that row to disappear.
In real databases, set operations are used most often to combine data that has been split into parts. Some organizations keep each year's records in a separate table: enrollment_2025, enrollment_2026. To study the two years together, you stack these tables with SELECT ... FROM enrollment_2025 UNION ALL SELECT ... FROM enrollment_2026; writing UNION here would delete records that look exactly the same in both years and make the counts smaller. Combining customer lists from different branches, or looking for inconsistencies between two lists, are also typical jobs for set operations. EXCEPT is especially useful when moving data from one system to another: "records that are in the old system but did not move to the new system" can be found with a single query. Then you run the same query in reverse order to look at "records in the new system that are not in the old one".
The same tools work in every database. In the Earbud music app database (earbud.sql), which you will use in the last exercise of this lesson, listeners and artists are in separate tables. Both the listeners from Toronto and the artists from Toronto will be invited to a meetup in Toronto.
Example 6 (outside the case): Toronto invite list
SELECT nickname AS name, 'listener' AS role FROM listener WHERE city = 'Toronto' UNION ALL SELECT name, 'artist' FROM artist WHERE city = 'Toronto' ORDER BY role, name;
| name | role |
|---|---|
| Neon Heron | artist |
| gray_cloud | listener |
| pixel_ada | listener |
| silent_letter | listener |
| tempo_120 | listener |
(5 rows)
The listener table has no name column, it has nickname. That is fine: columns are matched by position, and the name alias you gave in the first query becomes the name of the whole column. The app's team also noticed an odd case: there is a song in the song_like table that never appears in the play table. SELECT song_id FROM song_like EXCEPT SELECT song_id FROM play returns one row: song number 12, liked but never played. With the same two tables you can ask the reverse question too.
Which query returns the songs that were played but never liked?
-- Query A SELECT song_id FROM song_like EXCEPT SELECT song_id FROM play; -- Query B SELECT song_id FROM play EXCEPT SELECT song_id FROM song_like;
You can also find the department you found with LEFT JOIN and IS NULL in lesson 16 using EXCEPT: all department ids minus the department ids of the students.
SELECT id FROM department EXCEPT SELECT department_id FROM student;
| id |
|---|
| 8 |
(1 row)
Department 8 is Data Science and Analytics. The second query has 120 rows, but the same department ids repeat; EXCEPT does not mind this, it only checks "is it in the list?".
SELECT first_name FROM student INTERSECT SELECT first_name FROM instructor ORDER BY first_name;
Result: 14 rows (Camila, Clara, Diego, Emeka, Fatima, Greta, Liam, Nikolai, Noah, Olivia, Rosa, Samuel, Tessa, Yuki). If you also take the last name with the first name, the intersection shrinks to a single row: Yuki Reyes. This row is the reason for the 139 in Example 2.
Combining two queries with different column counts. For the card list, if you write the first and last name of the students and only the first name of the instructors:
OutputSELECT first_name, last_name FROM student
UNION
SELECT first_name FROM instructor;
ERROR: each UNION query must have the same number of columnsWrite the SELECT lists of the two queries one under the other, count the columns, and match them in order: first column with first column, second with second. Either add the real column to the missing side (SELECT first_name, last_name FROM instructor), or, if that information really does not exist, put NULL there: SELECT first_name, NULL AS last_name FROM .... Once the counts match, look one more time: do columns in the same position carry the same meaning? Because the query runs, you cannot be sure that last names have not landed in the first name column.
Next lesson: Some queries got long in this lesson; next is splitting a long query into named, readable steps with WITH (CTE).
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.