ORDER BY single column in MySQL - Time & Space Complexity
When we sort data in a database using ORDER BY on one column, it takes some time depending on how much data there is.
We want to understand how the time to sort grows as the number of rows increases.
Analyze the time complexity of the following code snippet.
SELECT *
FROM employees
ORDER BY salary;
This query selects all employees and sorts them by their salary in ascending order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the list of rows by the salary column.
- How many times: The sorting process compares and rearranges rows multiple times depending on the number of rows.
As the number of rows increases, the sorting work grows faster than just adding more rows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons and swaps |
| 100 | About 700 comparisons and swaps |
| 1000 | About 10,000 comparisons and swaps |
Pattern observation: The work grows faster than the number of rows, roughly multiplying by a bit more than the number of rows each time.
Time Complexity: O(n log n)
This means the time to sort grows a bit faster than the number of rows, but not as fast as checking every pair of rows.
[X] Wrong: "Sorting with ORDER BY takes the same time no matter how many rows there are."
[OK] Correct: Sorting needs to compare and rearrange rows, so more rows mean more work and more time.
Understanding how sorting time grows helps you explain database performance clearly and shows you know how data size affects queries.
"What if we added an index on the salary column? How would the time complexity of ORDER BY change?"
Practice
ORDER BY clause do in a MySQL query?Solution
Step 1: Understand the purpose of ORDER BY
TheORDER BYclause is used to sort the results of a query based on one or more columns.Step 2: Compare with other clauses
Filtering rows is done byWHERE, grouping byGROUP BY, and limiting rows byLIMIT. So, only sorting matchesORDER BY.Final Answer:
It sorts the query results by one or more columns. -> Option AQuick Check:
ORDER BY = Sort results [OK]
- Confusing ORDER BY with WHERE clause
- Thinking ORDER BY filters rows
- Mixing ORDER BY with GROUP BY
employees by the column salary in descending order?Solution
Step 1: Recall correct ORDER BY syntax
The correct syntax to sort results isORDER BY column_name ASC|DESC. Here,DESCmeans descending order.Step 2: Check each option
SELECT * FROM employees ORDER BY salary DESC; uses correct syntax. Options B, C, and D use invalid keywords or syntax.Final Answer:
SELECT * FROM employees ORDER BY salary DESC; -> Option DQuick Check:
ORDER BY + DESC = correct syntax [OK]
- Using SORT BY instead of ORDER BY
- Omitting BY after ORDER
- Using DOWN instead of DESC
products with columns id and price, what will be the order of id after running this query?SELECT id FROM products ORDER BY price ASC;
Assume the data:
id: 1, price: 50id: 2, price: 20id: 3, price: 30Solution
Step 1: Understand ORDER BY price ASC
The query sorts rows bypricein ascending order (lowest to highest).Step 2: Sort the data by price
Prices sorted ascending: 20 (id 2), 30 (id 3), 50 (id 1). So theidorder is [2, 3, 1].Final Answer:
[2, 3, 1] -> Option BQuick Check:
Sort by price ASC = [2, 3, 1] [OK]
- Confusing ASC with DESC order
- Sorting by id instead of price
- Ignoring the ORDER BY clause
SELECT name FROM customers ORDER salary DESC;
Solution
Step 1: Check ORDER BY syntax
The correct syntax requires the keywordBYafterORDER. The query usesORDER salary DESCwhich is invalid.Step 2: Confirm other parts are correct
DESCis valid withORDER BY. No WHERE clause is needed for sorting. ORDER BY comes after SELECT.Final Answer:
Missing BY keyword after ORDER -> Option CQuick Check:
ORDER BY needs BY keyword [OK]
- Omitting BY after ORDER
- Using ORDER before SELECT
- Confusing DESC usage
students with columns name and score. You want to list all students sorted by their score from highest to lowest, but if two students have the same score, sort those students alphabetically by name ascending. Which query achieves this?Solution
Step 1: Understand sorting requirements
Primary sort is byscoredescending (highest first). Secondary sort for ties is bynameascending (alphabetical).Step 2: Match query with requirements
SELECT * FROM students ORDER BY score DESC, name ASC; orders byscore DESCthenname ASC, matching the requirement. SELECT * FROM students ORDER BY name ASC, score DESC; reverses order priorities. SELECT * FROM students ORDER BY score ASC, name DESC; sorts score ascending and name descending, which is wrong. SELECT * FROM students ORDER BY score DESC; misses secondary sort.Final Answer:
SELECT * FROM students ORDER BY score DESC, name ASC; -> Option AQuick Check:
ORDER BY score DESC, name ASC = correct [OK]
- Reversing sort order priorities
- Missing secondary sort column
- Using ASC when DESC needed
Ready to prove it?
Pass the test and this pattern moves unknown
