By default, MySQL returns rows in no guaranteed order — the sequence depends on how the data is stored internally. The ORDER BY clause lets you control that order and sort results by one or more columns, either ascending or descending.
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC];
ASC — ascending order (A → Z, 0 → 9, oldest → newest). This is the default.DESC — descending order (Z → A, 9 → 0, newest → oldest).| id | name | city | age |
|---|---|---|---|
| 1 | Rahim Uddin | Dhaka | 22 |
| 2 | Sara Begum | Chittagong | 20 |
| 3 | Karim Ali | Sylhet | 23 |
| 4 | Nila Akter | Dhaka | 21 |
| 5 | Rafi Hossain | Rajshahi | 24 |
-- Sort by age, youngest first (ASC is the default)
SELECT name, age FROM students
ORDER BY age ASC;
| name | age |
|---|---|
| Sara Begum | 20 |
| Nila Akter | 21 |
| Rahim Uddin | 22 |
| Karim Ali | 23 |
| Rafi Hossain | 24 |
-- Sort by age, oldest first
SELECT name, age FROM students
ORDER BY age DESC;
| name | age |
|---|---|
| Rafi Hossain | 24 |
| Karim Ali | 23 |
| Rahim Uddin | 22 |
| Nila Akter | 21 |
| Sara Begum | 20 |
Text columns are sorted alphabetically:
-- Sort by name A to Z
SELECT name, city FROM students
ORDER BY name ASC;
When you sort by multiple columns, MySQL sorts by the first column first. Rows that share the same value in the first column are then sorted by the second column.
-- Sort by city A to Z, then by age youngest first within each city
SELECT name, city, age FROM students
ORDER BY city ASC, age ASC;
| name | city | age |
|---|---|---|
| Sara Begum | Chittagong | 20 |
| Nila Akter | Dhaka | 21 |
| Rahim Uddin | Dhaka | 22 |
| Rafi Hossain | Rajshahi | 24 |
| Karim Ali | Sylhet | 23 |
Each sort column can have its own direction:
-- Sort by city A to Z, then by age oldest first within each city
SELECT name, city, age FROM students
ORDER BY city ASC, age DESC;
ORDER BY always comes after WHERE:
SELECT name, age FROM students
WHERE age > 20
ORDER BY age DESC;
When a column contains NULL values, MySQL treats NULL as the lowest possible value. This means:
ASC, rows with NULL appear first.DESC, rows with NULL appear last.-- NULL ages appear first in ascending order
SELECT name, age FROM students
ORDER BY age ASC;
NULL rows to the end in ascending order, you can use: ORDER BY age IS NULL ASC, age ASC. This sorts non-null rows first, then null rows at the end.
ORDER BY sorts the result set — it does not change the data in the table.ASC (ascending) is the default — you can omit it if you want ascending order.DESC must be written explicitly when you want descending order.ORDER BY comes after WHERE and before LIMIT in the query.NULL values sort as the lowest value — first in ASC, last in DESC.