SQL ORDER BY Clause 📶¶
Mentor's Note: Data is often stored randomly in a database.
ORDER BYis like the "Sort" button in Excel. It organizes the chaos into a readable list. 💡
🌟 The Scenario: The School Ranking 🏆¶
Imagine a list of students and their marks. - Alphabetical: Sorting by name (A-Z) to find a student quickly. 🔤 - Rank: Sorting by marks (High to Low) to find the topper! 🥇
💻 1. The Basic Syntax¶
- ASC: Ascending (Default). 1 to 10, A to Z.
- DESC: Descending. 10 to 1, Z to A.
💻 2. Examples¶
A. Simple Ascending (A-Z)¶
-- Scenario: List students alphabetically
SELECT name FROM students
ORDER BY name; -- ASC is implied
B. Descending Order (High to Low)¶
-- Scenario: Find the highest paid employees first
SELECT emp_name, salary
FROM employees
ORDER BY salary DESC;
💻 3. Sorting by Multiple Columns 🪜¶
You can sort by more than one field. The second column is used as a "tie-breaker".
-- Scenario: Sort by Department, then by Name within that Dept
SELECT dept_name, emp_name
FROM employees
ORDER BY dept_name ASC, emp_name ASC;
📊 Visual Logic: The Multi-Sort¶
| Department | Name | (Step 1: Dept Sort) | (Step 2: Name Sort) |
|---|---|---|---|
| IT | Rahul | IT | Arjun |
| HR | Priya | IT | Rahul |
| IT | Arjun | HR | Priya |
💡 Interview Tip 👔¶
"Does
ORDER BYhappen before or after theWHEREclause? Answer: AFTER. The database first filters the rows, then it sorts what's left. PuttingORDER BYbeforeWHEREwill cause a syntax error!"