SQL ORDER BY Tutorial
Master SQL sorting with ORDER BY clause
ORDER BY is one of the most fundamental SQL clauses for organizing query results. It controls how data appears in your result set by sorting rows based on specified column values.
ORDER BY Key Concepts
Ascending Order
Default sorting behavior that arranges data from lowest to highest values. Numbers go from small to large, text goes alphabetically.
Descending Order
Reverse sorting using DESC keyword that arranges data from highest to lowest values. Essential for finding top performers or maximum values.
Multiple Columns
Sort by multiple criteria by listing columns in priority order. First column is primary sort, subsequent columns handle ties.
ORDER BY Syntax Breakdown
Start with SELECT
Begin your query with SELECT statement to specify which columns you want to retrieve from the database table.
Add FROM clause
Specify the table name using FROM keyword to indicate which table contains the data you want to sort.
Include ORDER BY
Add ORDER BY followed by the column name you want to sort by. This determines the sorting criteria for your results.
Specify Direction
Add DESC for descending order or leave blank for ascending. DESC shows highest values first, which is useful for rankings.
Ascending vs Descending Order
| Feature | ASC (Default) | DESC |
|---|---|---|
| Syntax | ORDER BY column | ORDER BY column DESC |
| Number Sort | 1, 2, 3, 4, 5 | 5, 4, 3, 2, 1 |
| Text Sort | A, B, C, D, E | Z, Y, X, W, V |
| Use Case | Chronological lists | Top performers, rankings |
This example demonstrates using ORDER BY DESC to find top rebounders in a basketball league. The DESC keyword ensures players with the most rebounds appear first in the results.
Basketball Query Breakdown
Identify Goal
Determine that you want to find the top rebounders from player statistics in your basketball league database table.
Select Data
Use SELECT to choose all columns or specific columns like player name, team, and rebounding statistics from the players table.
Apply Sorting
Add ORDER BY with the rebounds column and DESC keyword to sort players from highest to lowest rebounding numbers.
Execute Query
Run the query to get results showing top rebounders first, making it easy to identify the best performers in this category.
ORDER BY Benefits and Considerations
ORDER BY Best Practices
The default ascending order may not match your analytical needs
Improves performance and focuses on most relevant records
Dramatically improves query performance on large tables
Different databases handle NULL values differently in ORDER BY
Key Takeaways