Advertisement
Google Ad Slot: content-top
MySQL ORDER BY
MySQL ORDER BY Clause
The ORDER BY clause in MySQL is used to sort the result set in ascending (ASC) or descending (DESC) order based on one or more columns.
Syntax:
SELECT column1, column2 FROM table_name ORDER BY column1 [ASC | DESC];
ASC→ Sorts in ascending order (default).DESC→ Sorts in descending order.
Demo Database
Below is a selection from the "Students" table in the school_db database:
student_id |
name |
gender |
city |
age |
score |
course_id |
phone_number |
|
|---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
Sorting in Ascending Order (Default)
- Retrieves all students sorted by age (smallest to largest).
Sorting in Descending Order
- Retrieves all students sorted by age (largest to smallest).
Sorting by Multiple Columns
- Sorts students by age in ascending order, and if two students have the same age, they are sorted by name in descending order.