ASC and DESC direction in MySQL - Time & Space Complexity
When we sort data in a database using ASC (ascending) or DESC (descending), it takes time to arrange the rows.
We want to understand how the time needed grows as the amount of data grows.
Analyze the time complexity of the following SQL query that sorts data.
SELECT *
FROM employees
ORDER BY salary ASC;
This query fetches all employees and sorts them by their salary from lowest to highest.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the list of employees by salary.
- How many times: The sorting algorithm compares and rearranges items multiple times depending on the number of employees.
As the number of employees grows, the sorting work grows faster than just adding more rows.
| 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: The work grows faster than the number of rows, roughly multiplying by n log n.
Time Complexity: O(n log n)
This means that if you double the number of rows, the sorting work grows a bit more than double, but not as much as square.
[X] Wrong: "Sorting with ASC or DESC takes the same time as just reading the rows once."
[OK] Correct: Sorting requires comparing and rearranging many rows, which takes more time than just reading them.
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 sorting change?"