5. Sorting Results with ORDER BY

5. Sorting Results with ORDER BY

Idea: ORDER BY arranges rows. Default is ascending (small to large). Use DESC for descending.

Shape

SELECT Column1 FROM TableName ORDER BY Column1 DESC;

Multiple Columns

ORDER BY LastName ASC, FirstName ASC

Placeholders for Examples

Coming soon: sorting products by price then name.

Advanced Deep Dive ADVANCED

Determinism: Without a full key ordering, ties can return in any order between executions. Add extra columns for stable results.

Collation Effects: Text sort order depends on database collation; accent and case sensitivity can alter ordering.

Sort Performance: Large sorts spill to tempdb if memory grant is insufficient; indexing on ordered columns can remove explicit sorts.

Computed Order: Ordering by expressions can prevent index usage; consider computed persisted columns indexed for heavy queries.

OFFSET / FETCH: Pagination still requires scanning preceding rows; design indexes supporting the ORDER BY keys to reduce cost.

next