UNION and UNION ALL

Updated · 7 min read
mediumPostgreSQL 18sqlunionunion-allset-operationsinterview

UNION stacks the rows of two queries into one result, one on top of the other. A join puts tables side by side, adding columns; a union puts results end to end, adding rows. Navika's activity, her enrollment and her two payments, lives in two tables, but on a timeline it belongs in one list. UNION ALL builds that list. This lesson covers the rules for stacking (same number of columns, compatible types), the difference between UNION and UNION ALL, and how to sort and label a combined result.

In One Minute

  • query1 UNION query2 returns the rows of both, with duplicates removed.
  • UNION ALL keeps every row, duplicates included, and is faster because it doesn't check.
  • Both queries need the same number of columns, with compatible types, in the same order.
  • Column names come from the first query.
  • One ORDER BY at the very end sorts the whole combined result.
UNION returns everything from both queries, each row once

The Basics

SQL
SELECT column1, column2 FROM table_a
UNION [ALL]
SELECT column1, column2 FROM table_b
[ORDER BY ...];

Navika's activity, from two tables, as one timeline:

SQL▶ Try it
SELECT 'enrollment' AS kind, enrolled_on AS on_date, status AS detail
FROM enrollments
WHERE student_id = 103
 
UNION ALL
 
SELECT 'payment', paid_on, amount_usd::text
FROM payments
WHERE student_id = 103
 
ORDER BY on_date;
Output
    kind    |  on_date   | detail
------------+------------+--------
 enrollment | 2025-11-10 | active
 payment    | 2025-11-14 | 225.00
 payment    | 2025-12-19 | 225.00
(3 rows)

The first query found one enrollment, the second two payments, and UNION ALL stacked all three. The literal 'enrollment' and 'payment' label where each row came from, a common trick. The columns are named by the first query (kind, on_date, detail); the second query's columns line up by position, not by name. amount_usd::text converts the amount to text so it can share a column with status.

One enrollment row and two payment rows, stacked and sorted by date into one timeline

Matching Columns and Types

Each query must return the same number of columns, and each column must have a compatible type. A different count fails:

SQL▶ Try it
SELECT student_id, first_name FROM students
UNION
SELECT student_id FROM payments;
Output
ERROR:  each UNION query must have the same number of columns

And a number can't share a column with text:

SQL▶ Try it
SELECT student_id FROM students
UNION
SELECT title FROM courses;
Output
ERROR:  UNION types integer and character varying cannot be matched
The second query's columns fill the first query's columns in order; a different count or type is an error

Convert one side when you mean it, as the timeline did with amount_usd::text. Compatible types, such as INTEGER with NUMERIC, or VARCHAR with TEXT, combine without help.

UNION Versus UNION ALL

UNION removes duplicate rows from the combined result; UNION ALL keeps them all. States from students and from cities:

SQL▶ Try it
SELECT state FROM students
UNION ALL
SELECT state FROM cities
ORDER BY state;
Output
 state
-------
 CA
 CA
 CA
 TX
 TX
(5 rows)

Five rows: three students and two cities. With plain UNION, the duplicates collapse:

SQL▶ Try it
SELECT state FROM students
UNION
SELECT state FROM cities
ORDER BY state;
Output
 state
-------
 CA
 TX
(2 rows)

Two rows. UNION compares whole rows, like SELECT DISTINCT over the combined result, and that comparison costs time: the database has to sort or hash every row to find the duplicates. UNION ALL just appends.

UNION ALL keeps all 5 state values; UNION collapses them to CA and TX

Sorting and Limiting a Union

One ORDER BY at the end sorts the whole result, using the first query's column names (or positions, like ORDER BY 2). An ORDER BY in the middle, on just one query, is a syntax error. To sort or limit one part on its own, wrap it in parentheses. The most and least expensive courses, in one result:

SQL▶ Try it
(SELECT title, fee_usd FROM courses ORDER BY fee_usd DESC LIMIT 1)
UNION ALL
(SELECT title, fee_usd FROM courses ORDER BY fee_usd LIMIT 1);
Output
      title       | fee_usd
------------------+---------
 Java Collections |  550.00
 Git Basics       |  250.00
(2 rows)

Each parenthesized query keeps its own ORDER BY and LIMIT. To filter or group the combined rows, wrap the whole union in a subquery, as Subqueries shows.

Common Mistakes

Using UNION by habit. It removes real duplicates and costs a sort. Use UNION ALL by default.

Columns in a different order. SELECT paid_on, amount_usd ... UNION SELECT amount_usd, paid_on fails or mixes values. Line them up.

Naming columns in the second query. Only the first query's names count.

ORDER BY in the middle. Put it at the end, or wrap that query in parentheses.

Interview Corner

What's the difference between UNION and UNION ALL?

UNION removes duplicate rows from the combined result; UNION ALL keeps every row. UNION ALL is faster because it doesn't check for duplicates.

What are the requirements for a UNION?

Each query must return the same number of columns, with compatible types, in the same order. The result's column names come from the first query.

What's the difference between a JOIN and a UNION?

A join combines tables side by side, matching rows and adding columns. A union stacks query results end to end, adding rows.

Practice

Challenge: Build one list of every person and course name in the Fee Tracker: each student's first name with the label 'student', and each course title with the label 'course'. Name the columns name and kind, and sort by kind, then name.

Show solution
SQL▶ Try it
SELECT first_name AS name, 'student' AS kind FROM students
UNION ALL
SELECT title, 'course' FROM courses
ORDER BY kind, name;
Output
       name        |  kind
-------------------+---------
 Git Basics        | course
 Java Basics       | course
 Java Collections  | course
 Java OOP          | course
 JavaScript Basics | course
 SQL Basics        | course
 Advitha           | student
 Navika            | student
 Srihitha          | student
(9 rows)

Nine rows: six courses and three students. first_name and title are both text, so they share the name column.

Quick check: UNION and UNION ALL

3 questions
1students has states CA, CA, TX; cities has CA, TX. How many rows does SELECT state FROM students UNION SELECT state FROM cities return?
2Where do a union's column names come from?
3Why prefer UNION ALL?

Key Takeaways

You want toWrite
Stack, keep everythingSELECT ... UNION ALL SELECT ...
Stack, remove duplicatesSELECT ... UNION SELECT ...
Label the sourceSELECT 'payment' AS kind, ...
Sort the whole result... UNION ALL SELECT ... ORDER BY on_date;

Was this tutorial helpful?

Lesson 43 of 115