ORDER BY multiple columns in SQL - Time & Space Complexity
When sorting data by more than one column, it is important to understand how the sorting time changes as the data grows.
We want to know how the sorting work increases when we order by multiple columns instead of just one.
Analyze the time complexity of the following code snippet.
SELECT *
FROM employees
ORDER BY department, salary DESC;
This query sorts employees first by their department, then by salary in descending order within each department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the entire list of rows based on multiple columns.
- How many times: The sorting algorithm compares and rearranges rows multiple times, depending on the number of rows.
Sorting time grows as the number of rows increases, because more rows mean more comparisons and swaps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 comparisons |
| 100 | About 700 to 800 comparisons |
| 1000 | About 10,000 to 12,000 comparisons |
Pattern observation: As the number of rows grows, the sorting work grows faster than the number of rows, roughly multiplying by a bit more than the number itself.
Time Complexity: O(n log n)
This means sorting takes more time as the list grows, but it grows in a way that is faster than simple counting but slower than multiplying by itself.
[X] Wrong: "Ordering by multiple columns makes sorting take twice as long as ordering by one column."
[OK] Correct: Sorting time depends mostly on the number of rows, not the number of columns sorted. Adding more columns to sort adds only a small extra cost per comparison, not doubling the whole sorting time.
Understanding how sorting scales with data size and multiple columns helps you explain query performance clearly and confidently in real situations.
"What if we added an index on the columns used in ORDER BY? How would the time complexity change?"
Practice
What does the SQL clause ORDER BY column1, column2 do?
Solution
Step 1: Understand ORDER BY with multiple columns
TheORDER BYclause sorts rows by the first column listed.Step 2: Sorting with tie-breaker column
If two or more rows have the same value in the first column, sorting continues by the second column.Final Answer:
Sorts the results first by column1, then by column2 if there are ties in column1 -> Option CQuick Check:
ORDER BY multiple columns sorts stepwise [OK]
- Thinking ORDER BY filters rows
- Assuming it groups data
- Believing it sorts only by the last column
Which of the following is the correct syntax to sort by age ascending and then by name descending?
SELECT * FROM users ORDER BY ...
Solution
Step 1: Specify sorting order for each column
UseASCfor ascending andDESCfor descending explicitly after each column.Step 2: Apply correct order for age and name
Since age is ascending and name is descending, writeage ASC, name DESC.Final Answer:
age ASC, name DESC -> Option AQuick Check:
Correct syntax uses ASC and DESC per column [OK]
- Omitting ASC or DESC and expecting default
- Mixing order keywords incorrectly
- Using ORDER BY twice in one query
Given the table products with columns category and price, what will this query return?
SELECT category, price FROM products ORDER BY category ASC, price DESC;
Solution
Step 1: Analyze ORDER BY clause
The query orders rows first bycategoryascending (A to Z).Step 2: Understand secondary sorting
Within each category, rows are sorted bypricedescending (highest to lowest).Final Answer:
Rows sorted by category alphabetically, then by price highest to lowest within each category -> Option AQuick Check:
ORDER BY sorts stepwise by listed columns [OK]
- Confusing ascending and descending order
- Thinking ORDER BY groups rows
- Ignoring second column sorting
Identify the error in this query:
SELECT * FROM employees ORDER BY salary DESC,;
Solution
Step 1: Check ORDER BY syntax
TheORDER BYclause lists columns separated by commas without trailing commas.Step 2: Identify trailing comma error
The comma afterDESCis extra and causes a syntax error.Final Answer:
Extra comma after DESC causes syntax error -> Option BQuick Check:
Trailing commas in ORDER BY cause syntax errors [OK]
- Leaving trailing commas in ORDER BY
- Forgetting ASC or DESC (defaults to ASC though)
- Assuming ORDER BY accepts invalid columns
You have a students table with columns grade (integer) and last_name (text). You want to list students sorted by grade descending, but for students with the same grade, sort by last name ascending. Which query achieves this?
Solution
Step 1: Determine primary sorting column and order
Primary sort is bygradedescending (highest grade first).Step 2: Determine secondary sorting column and order
For ties in grade, sort bylast_nameascending (A to Z).Step 3: Write correct ORDER BY syntax
UseORDER BY grade DESC, last_name ASCwith comma separating columns.Final Answer:
SELECT * FROM students ORDER BY grade DESC, last_name ASC; -> Option DQuick Check:
ORDER BY multiple columns with specified directions [OK]
- Swapping order of columns in ORDER BY
- Missing comma between columns
- Omitting ASC or DESC keywords
Ready to prove it?
Pass the test and this pattern moves unknown
