SQL ORDER BY Clause πΆΒΆ
Prerequisites: WHERE 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!"