liveBook · Manning

Sorting algorithm

As explained in 100 SQL Server Mistakes and How to Avoid Them

A sort operation arranges rows according to specified ordering keys during query execution or index maintenance.

Mistake: ordering every query because ordered output feels safer. Sorting is a presentation operation, not a set-based requirement, and can make a query substantially slower. One comparison ran 25% slower with ordering enabled; its sort represented 91% of estimated plan cost. section 5.4

Compare unordered and ordered output

SET STATISTICS TIME ON; SELECT CustomerContactFirstName, CustomerContactLastName, CustomerContactEmail FROM dbo.CustomerContacts; SELECT CustomerContactFirstName, CustomerContactLastName, CustomerContactEmail FROM dbo.CustomerContacts ORDER BY CustomerContactEmail; Use Include Actual Execution Plan in SQL Server Management Studio when investigating the difference. Treat displayed costs as estimates rather than direct performance measurements. section 5.4

Apply these rules:

  • Order rows only when the consumer genuinely requires a specific sequence. section 5.4
  • Measure unordered and ordered versions on the same test setup, without capturing execution plans during timing tests. section 5.4
  • If ordering is necessary, inspect whether a covering nonclustered index can improve the query. section 5.4

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains sort operators, estimated plan costs, timing tests, and inaccurate statistics, but does not develop sorting internals.
Examples
Uses CustomerContacts queries ordered by email, execution-plan figures, timing output, and a covering-index definition.
What you can do after
Diagnose sorting overhead by comparing T-SQL timings and inspecting plans in SQL Server Management Studio.
How it connects
Connects sorting with set theory, execution plans, Query Store, statistics, and covering indexes.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.