ORDER BY with ASC and DESC in SQL - Time & Space Complexity
When we sort data using ORDER BY, the database rearranges rows based on column values.
We want to know how the time to sort grows as the data size grows.
Analyze the time complexity of this SQL query:
SELECT *
FROM employees
ORDER BY salary DESC, name ASC;
This query sorts employees first by salary from highest to lowest, then by name alphabetically.
Sorting involves comparing rows multiple times to order them.
- Primary operation: Comparing and swapping rows during sorting.
- How many times: Depends on sorting algorithm, but many comparisons grow with number of rows.
Sorting takes more time as rows increase, but not just adding up; it grows faster.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30-40 comparisons |
| 100 | About 700-800 comparisons |
| 1000 | About 10,000-12,000 comparisons |
Pattern observation: Operations grow faster than the number of rows, roughly multiplying by n log n.
Time Complexity: O(n log n)
This means sorting takes a bit more than just looking at each row once; it grows a little faster as data grows.
[X] Wrong: "Sorting rows takes the same time no matter how many rows there are."
[OK] Correct: Sorting compares many pairs of rows, so more rows mean many more comparisons, not just a simple increase.
Understanding how sorting time grows helps you explain database performance clearly and confidently.
"What if the data was already sorted? How would that affect the time complexity of ORDER BY?"
Practice
ORDER BY clause do in an SQL query?Solution
Step 1: Understand the purpose of ORDER BY
TheORDER BYclause is used to arrange the rows returned by a query in a specific order.Step 2: Differentiate from other clauses
Filtering is done byWHERE, grouping byGROUP BY, and limiting rows byLIMIT. OnlyORDER BYsorts the results.Final Answer:
It sorts the query results in a specified order. -> Option AQuick Check:
ORDER BY = sorts 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 isORDER BY column_name ASC|DESC. Here,DESCmeans descending order.Step 2: Check each option
SELECT * FROM Employees ORDER BY Salary DESC; uses correct keywords and syntax. Options B, C, and D use invalid keywords likeSORT BY, missingBY, or incorrect direction word.Final Answer:
SELECT * FROM Employees ORDER BY Salary DESC; -> Option AQuick 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 ProductID and Price, what will be the order of ProductID after running this query?SELECT ProductID FROM Products ORDER BY Price ASC;
Solution
Step 1: Analyze ORDER BY clause
The query orders rows byPricein ascending order, meaning from smallest to largest price.Step 2: Understand output column
The query selectsProductIDbut orders byPrice. So theProductIDvalues will appear sorted according to their prices ascending.Final Answer:
Products sorted by Price from lowest to highest. -> Option DQuick Check:
ORDER BY Price ASC = lowest to highest [OK]
- Assuming sorting is by selected column instead of ORDER BY column
- Confusing ASC with DESC
- Thinking ORDER BY changes selected columns
SELECT Name FROM Customers ORDER BY Age DESCENDING;
Solution
Step 1: Check ORDER BY direction keywords
SQL usesASCfor ascending andDESCfor descending order.DESCENDINGis not a valid keyword.Step 2: Validate other parts
ORDER BY works with DESC. ASC is optional. We assumeAgeexists as no schema given.Final Answer:
The keyword DESCENDING is invalid; use DESC instead. -> Option BQuick Check:
Use DESC, not DESCENDING [OK]
- Typing DESCENDING instead of DESC
- Thinking DESC is not allowed
- Assuming ASC is mandatory
Students with columns Name, Grade, and Age. You want to list students sorted first by Grade descending (highest grade first), and then by Age ascending (youngest first) within the same grade. Which query achieves this?Solution
Step 1: Understand sorting priorities
We want to sort byGradedescending first, so highest grades come first.Step 2: Apply secondary sorting
Within the same grade, sort byAgeascending, so younger students appear first.Step 3: Match query syntax
SELECT * FROM Students ORDER BY Grade DESC, Age ASC; matches the required order:ORDER BY Grade DESC, Age ASC. Other options reverse order or directions.Final Answer:
SELECT * FROM Students ORDER BY Grade DESC, Age ASC; -> Option CQuick Check:
ORDER BY Grade DESC, Age ASC = correct multi-level sort [OK]
- Reversing ASC and DESC directions
- Swapping column order in ORDER BY
- Using only one column for sorting
Ready to prove it?
Pass the test and this pattern moves unknown
