MySQL ORDER BY Keyword
🔢 MySQL ORDER BY Keyword
The ORDER BY keyword in MySQL is used to sort the result set of a query in ascending or descending order.
👉 It is widely used in reports, rankings, pagination, and interviews.
1️⃣ What is ORDER BY?
-
Sorts rows based on one or more columns
-
Default sorting is ascending
-
Affects only the result, not stored data
📌 Sorting can be done on numbers, strings, and dates.
2️⃣ Basic Syntax
3️⃣ ORDER BY ASC (Ascending – Default) ⭐
✔ Lowest marks first
✔ ASC is optional
4️⃣ ORDER BY DESC (Descending) ⭐
✔ Highest salary first
✔ Very common in Top-N queries
5️⃣ ORDER BY Multiple Columns ⭐
📌 First sorts by department,
📌 then sorts salary inside each department
6️⃣ ORDER BY with Column Position ❓
📌 Sorts by 2nd column (marks)
⚠️ Not recommended (less readable)
7️⃣ ORDER BY with Alias ⭐
✔ Alias can be used in ORDER BY
8️⃣ ORDER BY with WHERE
📌 WHERE filters rows before sorting
9️⃣ ORDER BY with GROUP BY ⭐
✔ Sorts grouped results
🔟 ORDER BY with LIMIT (Very Important)
✔ Top 5 highest salaries
✔ Very common interview question
1️⃣1️⃣ ORDER BY with NULL Values
-
ASC→ NULLs come first -
DESC→ NULLs come last
1️⃣2️⃣ ORDER BY vs GROUP BY ⭐ (Interview)
| Feature | ORDER BY | GROUP BY |
|---|---|---|
| Purpose | Sorting | Grouping |
| Affects | Result order | Aggregation |
| Aggregate functions | ❌ No | ✔ Yes |
1️⃣3️⃣ Common Mistakes ❌
❌ Expecting ORDER BY to store sorted data
❌ Forgetting ASC/DESC meaning
❌ Using column position blindly
❌ Confusing ORDER BY with GROUP BY
📌 Interview Questions & MCQs (Very Important)
Q1. What does ORDER BY do?
A) Groups rows
B) Filters rows
C) Sorts rows
D) Deletes rows
✅ Answer: C
Q2. Default order of ORDER BY?
A) DESC
B) RANDOM
C) ASC
D) NULL
✅ Answer: C
Q3. Can ORDER BY use column alias?
A) Yes
B) No
✅ Answer: A
Q4. Which clause is executed last?
A) WHERE
B) GROUP BY
C) ORDER BY
D) HAVING
✅ Answer: C
Q5. Which query gives top 3 salaries?
A) Correct
B) Incorrect
✅ Answer: A
Q6. Can ORDER BY sort by multiple columns?
A) Yes
B) No
✅ Answer: A
🔥 Real-Life Use Cases
✔ Ranking students/employees
✔ Leaderboards
✔ Latest records first
✔ Pagination sorting
✔ Reports & dashboards
✅ Summary
-
ORDER BYsorts query results -
Default order is ASC
-
Supports multiple columns
-
Works with aliases & LIMIT
-
Essential for ranking & pagination
-
Very important for SQL exams & interviews
