ORDER BY & Sorting: Concept
Module: SQL Fundamentals
ORDER BY sorts query results by one or more columns. Results are returned in specified order - ascending (smallest to largest) or descending (largest to smallest).
**ORDER BY Basics:**
- ASC: Ascending order (default) - 1, 2, 3 or A, B, C
- DESC: Descending order - 3, 2, 1 or C, B, A
- Multiple columns: Sort by first column, then second for ties
**Execution Order:**
ORDER BY happens AFTER SELECT, so you can use column aliases.
**NULL Handling:**
- Default: NULLs sort first (ASC) or last (DESC)
- NULLS FIRST: Force NULLs to beginning
- NULLS LAST: Force NULLs to end
**Performance:**
- Sorting is expensive on large datasets
- Indexes on ORDER BY columns enable fast sorting
- Without index: Full sort in memory (slow)
- With index: Read in sorted order (fast)
**Sort Priority:**
When sorting by multiple columns, first column has highest priority.
Example: ORDER BY department, salary DESC
- First sort by department (A-Z)
- Within each department, sort by salary (high to low)
ORDER BY is essential for user interfaces - users expect sorted lists. Critical for data analysts (reports), backend developers (APIs), and BI tools (dashboards). Sorting large datasets without indexes can cause 10-100x slowdowns. Understanding sort optimization is key to scalable applications.
Every application needs sorted data - product listings by price, customer lists by name, order history by date, leaderboards by score. ORDER BY is used in pagination, top-N queries, and report generation. Understanding sort performance prevents slow queries on large datasets.