🔹 ORDER BY Command
Definition: The ORDER BY
clause 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];
🎓 Sample Table: students
id | name | age | grade |
1 | Asha | 15 | A |
2 | Rohan | 14 | B |
3 | Meena | 16 | A |
SELECT * FROM students
ORDER BY age ASC;
🟢 Output: Students sorted by age in ascending order.
id | name | age | grade |
2 | Rohan | 14 | B |
1 | Asha | 15 | A |
3 | Meena | 16 | A |
SELECT name, grade FROM students
ORDER BY grade DESC, name ASC;
🟢 Output: Sorted by grade descending, and name ascending within same grade.
name | grade |
Rohan | B |
Asha | A |
Meena | A |
📌 When to Use ORDER BY:
Use it when you want to control the order in which records are displayed in your result set.
⚠️ Common Mistakes:
- Not specifying ASC or DESC—defaults to ASC.
- Using column names that don't exist in the table.
- Ordering by column positions can be confusing. Prefer column names.