SQL ORDER BY
Master the art of sorting query results using ascending and descending order to make your data meaningful and organized.
What is ORDER BY?
When you run a SQL query, the database returns rows in no guaranteed order. The ORDER BY clause lets you sort the result set by one or more columns so the data comes back in a predictable, useful sequence.
Why Sorting Matters
Unsorted vs Sorted
The Syntax
ASC vs DESC
Where Does ORDER BY Go?
ORDER BY is always the last clause in a SELECT statement (before LIMIT, if present). The database filters and groups first, then sorts the final result.
Step-by-Step Approach
Example 1: Alphabetical Sort
| name ↑ | age |
|---|---|
| Alice | 16 |
| Bob | 17 |
| Charlie | 16 |
| Dana | 15 |
| Eve | 17 |
Example 2: Highest Score First
| name | score ↓ |
|---|---|
| Alice | 95 |
| Eve | 88 |
| Dana | 84 |
| Charlie | 72 |
| Bob | 61 |
Example 3: Multi-Column Sort
| grade ↑ | name | score ↓ |
|---|---|---|
| 9 | Dana | 84 |
| 9 | Bob | 61 |
| 10 | Alice | 95 |
| 10 | Eve | 88 |
| 11 | Charlie | 72 |
Sorting Text vs Numbers
How NULLs Are Sorted
NULL values represent missing data. Where they appear in sorted results depends on the database:
| Database | ASC Order | DESC Order |
|---|---|---|
| MySQL | NULLs first | NULLs last |
| PostgreSQL | NULLs last | NULLs first |
| SQLite | NULLs first | NULLs last |
Combining WHERE and ORDER BY
| name | score ↓ |
|---|---|
| Alice | 95 |
| Eve | 88 |
| Dana | 84 |
Sorting by Column Position
Instead of the column name, you can use its position number in the SELECT list. Column 1 is the first column listed, column 2 is the second, and so on.
Common Mistakes
Summary Table
| Feature | ASC | DESC |
|---|---|---|
| Direction | Low \(\to\) High | High \(\to\) Low |
| Text | \(A \to Z\) | \(Z \to A\) |
| Numbers | \(1, 2, 3, \dots\) | \(\dots, 3, 2, 1\) |
| Dates | Oldest \(\to\) Newest | Newest \(\to\) Oldest |
| Default? | Yes | No (must specify) |
| Multi-column | Mix freely: ORDER BY a ASC, b DESC | |
Question 1 of 5
What is the default sort order when you write ORDER BY without specifying ASC or DESC?
Question 2 of 5
Which query correctly returns student names sorted from highest score to lowest?
Question 3 of 5
Given the query:
ORDER BY grade ASC, name DESC
Which column is the primary sort key?
Question 4 of 5
A column named price is stored as VARCHAR. You run ORDER BY price ASC. Which order is correct?
Question 5 of 5
Where must the ORDER BY clause be placed in a SQL query?