MySQL ORDER BY Keyword
MySQL ORDER BY Keyword
The ORDER BY keyword in MySQL is used to sort the retrieved data from a table. By default, data can be sorted in ascending (ASC) or descending (DESC) order.
๐ Basic Syntax
-
ASCโ Ascending order (default) -
DESCโ Descending order
If no order is specified, MySQL sorts results in ascending order.
๐งช Example Table
Assume this table named students:
| id | name | marks |
|---|---|---|
| 1 | Aman | 88 |
| 2 | Riya | 92 |
| 3 | John | 75 |
| 4 | Neha | 88 |
๐ท Sort in Ascending Order
Result:
| name | marks |
|---|---|
| John | 75 |
| Aman | 88 |
| Neha | 88 |
| Riya | 92 |
๐ฝ Sort in Descending Order
Result:
| name | marks |
|---|---|
| Riya | 92 |
| Aman | 88 |
| Neha | 88 |
| John | 75 |
๐ง Sorting by Multiple Columns
If two or more values are the same, you can sort using a secondary column.
Here:
-
Sorted first by marks (DESC)
-
If marks are equal, then by name (ASC)
๐ Using ORDER BY With WHERE Clause
โณ Using ORDER BY With LIMIT
Returns highest two marks.
๐ Summary
| Feature | Example |
|---|---|
| Sort ascending | ORDER BY name ASC |
| Sort descending | ORDER BY marks DESC |
| Sort multiple columns | ORDER BY marks DESC, name ASC |
| With WHERE clause | WHERE marks > 80 ORDER BY name |
