0
0
MySQLquery~5 mins

ASC and DESC direction in MySQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: ASC and DESC direction
O(n log n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of employees grows, the sorting work grows faster than just adding more rows.

Input Size (n)Approx. Operations
10About 30 to 40 comparisons
100About 700 to 800 comparisons
1000About 10,000 to 12,000 comparisons

Pattern observation: The work grows faster than the number of rows, roughly multiplying by n log n.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how sorting time grows helps you explain database performance clearly and shows you know how data size affects queries.

Self-Check

"What if we added an index on the salary column? How would the time complexity of sorting change?"