UNION and UNION ALL in PostgreSQL - Time & Space Complexity
When combining results from two queries, it's important to know how the time to get results grows as data grows.
We want to understand how using UNION and UNION ALL affects the work the database does.
Analyze the time complexity of the following code snippet.
SELECT column1 FROM tableA
UNION
SELECT column1 FROM tableB;
SELECT column1 FROM tableA
UNION ALL
SELECT column1 FROM tableB;
This code combines rows from two tables, either removing duplicates (UNION) or keeping all rows (UNION ALL).
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all rows from both tables.
- How many times: Once for each table's rows.
- Additional for UNION: Comparing rows to remove duplicates, which involves checking all combined rows.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations for UNION ALL | Approx. Operations for UNION |
|---|---|---|
| 10 | About 20 row reads | About 20 reads + some comparisons |
| 100 | About 200 row reads | About 200 reads + more comparisons |
| 1000 | About 2000 row reads | About 2000 reads + many comparisons |
Pattern observation: UNION ALL grows linearly with input size, while UNION adds extra work to check for duplicates, which grows faster.
Time Complexity: O(n) for UNION ALL, O(n log n) for UNION
This means UNION ALL just reads all rows once, while UNION must also sort or compare rows to remove duplicates, which takes more time as data grows.
[X] Wrong: "UNION and UNION ALL take the same time because they both combine rows."
[OK] Correct: UNION removes duplicates, which needs extra work to compare rows, so it takes more time than UNION ALL.
Understanding how UNION and UNION ALL scale helps you explain query performance clearly and shows you know how databases handle data combining.
"What if we added an index on the column used in UNION? How would the time complexity change?"
Practice
UNION and UNION ALL in PostgreSQL?Solution
Step 1: Understand the behavior of UNION
UNIONcombines results from two queries and removes duplicate rows to give unique results.Step 2: Understand the behavior of UNION ALL
UNION ALLcombines results but keeps all rows, including duplicates.Final Answer:
UNIONremoves duplicates,UNION ALLkeeps duplicates. -> Option AQuick Check:
Duplicates removed = UNION, duplicates kept = UNION ALL [OK]
- Thinking UNION ALL removes duplicates
- Believing UNION allows different column counts
- Confusing column name requirements
UNION ALL in PostgreSQL?Solution
Step 1: Check the correct keyword spacing
The correct keyword isUNION ALLwith a space between UNION and ALL.Step 2: Verify the SELECT statements are complete
Both queries must be valid SELECT statements with matching column counts and types.Final Answer:
SELECT name FROM students UNION ALL SELECT name FROM teachers; -> Option AQuick Check:
Correct syntax uses 'UNION ALL' with space [OK]
- Writing UNIONALL as one word
- Missing SELECT in second query
- Adding WHERE without condition
Table A:id | value
1 | 'apple'
2 | 'banana'
Table B:id | value
2 | 'banana'
3 | 'cherry'
What is the result of this query?
SELECT value FROM A UNION SELECT value FROM B ORDER BY value;
Solution
Step 1: Combine values from both tables using UNION
UNIONremoves duplicates, so 'banana' appears only once.Step 2: Order the combined results alphabetically
Ordering by value gives: 'apple', 'banana', 'cherry'.Final Answer:
apple, banana, cherry -> Option DQuick Check:
UNION removes duplicates, so only one 'banana' [OK]
- Including duplicate 'banana' with UNION
- Ignoring ORDER BY effect
- Confusing UNION with UNION ALL
SELECT id FROM table1 UNION ALL SELECT id FROM table2;
It returns an error. What is the most likely cause?
Solution
Step 1: Check column counts in both SELECT statements
UNION ALL requires both SELECTs to have the same number of columns.Step 2: Identify error cause
If column counts differ, PostgreSQL throws an error.Final Answer:
The two SELECT statements have different numbers of columns. -> Option BQuick Check:
Column count mismatch causes UNION ALL error [OK]
- Thinking table names must match
- Believing UNION ALL disallows SELECT
- Ignoring column count mismatch
SELECT id, name FROM employees WHERE department = 'Sales'
SELECT id, name FROM contractors WHERE department = 'Sales'
and keep all rows including duplicates. Which query correctly does this and why?
Solution
Step 1: Understand requirement to keep duplicates
To keep duplicates, useUNION ALLbecauseUNIONremoves duplicates.Step 2: Check WHERE clause usage
Both queries filter department = 'Sales', so WHERE must be in both queries.Final Answer:
SELECT id, name FROM employees UNION ALL SELECT id, name FROM contractors WHERE department = 'Sales'; Because UNION ALL keeps duplicates. -> Option CQuick Check:
Keep duplicates = UNION ALL with correct WHERE clauses [OK]
- Using UNION instead of UNION ALL
- Omitting WHERE in second query
- Thinking UNION ALL is invalid
Ready to prove it?
Pass the test and this pattern moves unknown
