Set operations with ORDER BY in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time needed to run a SQL query with set operations and ordering changes as the data grows.
Specifically, how does combining results and sorting them affect performance?
Analyze the time complexity of the following code snippet.
SELECT column1 FROM tableA
UNION
SELECT column1 FROM tableB
ORDER BY column1;
This query combines unique values from two tables and then sorts the final list by column1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning both tables to collect rows, then sorting the combined results.
- How many times: Each row in both tables is processed once; sorting compares rows multiple times depending on total rows.
As the number of rows in both tables grows, the time to scan grows linearly, but sorting takes more time as the combined data grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 scans + sorting 20 rows |
| 100 | About 200 scans + sorting 200 rows |
| 1000 | About 2000 scans + sorting 2000 rows |
Pattern observation: Scanning grows straight with input size, sorting grows faster but not as fast as scanning squared.
Time Complexity: O(n log n)
This means the time grows a bit faster than the number of rows because sorting takes more steps as data grows.
[X] Wrong: "The query runs in straight linear time because it just reads rows once."
[OK] Correct: Sorting the combined results requires extra comparisons, so the time grows faster than just reading rows.
Understanding how set operations and sorting affect query time helps you explain performance in real projects and shows you can think about data size impact.
"What if we replaced UNION with UNION ALL (which does not remove duplicates)? How would the time complexity change?"
Practice
UNION operation do when combining results from two SELECT queries?Solution
Step 1: Understand UNION operation
The UNION operation combines results from two SELECT queries into one result set.Step 2: Check duplicate handling
UNION removes duplicate rows, unlike UNION ALL which keeps duplicates.Final Answer:
Combines results and removes duplicate rows -> Option BQuick Check:
UNION removes duplicates = C [OK]
- Confusing UNION with UNION ALL
- Thinking UNION sorts results automatically
- Mixing UNION with JOIN operations
name?Solution
Step 1: Understand correct UNION syntax
The UNION combines two SELECT queries; ORDER BY applies after the last SELECT.Step 2: Check placement of ORDER BY
ORDER BY must come after the entire UNION, not between or before queries.Final Answer:
SELECT name FROM table1 UNION SELECT name FROM table2 ORDER BY name; -> Option CQuick Check:
ORDER BY after UNION = A [OK]
- Putting ORDER BY before UNION
- Using SORT BY instead of ORDER BY
- Placing ORDER BY between SELECTs
table1 with values (1, 'Alice'), (2, 'Bob')table2 with values (2, 'Bob'), (3, 'Charlie')What is the result of this query?
SELECT id, name FROM table1 UNION SELECT id, name FROM table2 ORDER BY id;
Solution
Step 1: Combine rows with UNION
UNION merges rows from both tables and removes duplicates, so (2, 'Bob') appears once.Step 2: Sort combined results by id
Ordering by id gives rows in order: 1, 2, 3.Final Answer:
(1, 'Alice'), (2, 'Bob'), (3, 'Charlie') -> Option AQuick Check:
UNION removes duplicates, ORDER BY sorts = B [OK]
- Expecting duplicates with UNION
- Ignoring ORDER BY sorting
- Confusing UNION with UNION ALL
SELECT name FROM table1 UNION ALL ORDER BY name SELECT name FROM table2;
Solution
Step 1: Check UNION ALL syntax
UNION ALL combines two SELECT queries; ORDER BY must come after both queries, not between.Step 2: Identify ORDER BY placement error
ORDER BY is incorrectly placed between UNION ALL and second SELECT, causing syntax error.Final Answer:
ORDER BY is placed incorrectly between UNION ALL and second SELECT -> Option DQuick Check:
ORDER BY after UNION ALL queries = D [OK]
- Placing ORDER BY between UNION ALL and second SELECT
- Thinking UNION ALL disallows ORDER BY
- Assuming column names must differ
employees with columns (id, name, department)contractors with columns (id, name, department)Write a query to list all unique names from both tables sorted alphabetically, but include duplicates if the same name appears in both tables.
Which query achieves this?
Solution
Step 1: Understand requirement for duplicates
The query should include duplicates if the same name appears in both tables, so duplicates must be kept.Step 2: Choose correct set operation
UNION removes duplicates, so it is not suitable. UNION ALL keeps duplicates from both tables.Step 3: Confirm sorting
ORDER BY name sorts the combined result alphabetically.Final Answer:
SELECT name FROM employees UNION ALL SELECT name FROM contractors ORDER BY name; -> Option AQuick Check:
UNION ALL keeps duplicates, ORDER BY sorts = A [OK]
- Using UNION which removes duplicates
- Confusing INTERSECT or EXCEPT with UNION
- Placing ORDER BY incorrectly
