Skip to content

SQL ORDER BY Clause πŸ“ΆΒΆ

Prerequisites: WHERE Clause

Mentor's Note: Data is often stored randomly in a database. ORDER BY is 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ΒΆ

SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC|DESC];
  • 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 BY happen before or after the WHERE clause? Answer: AFTER. The database first filters the rows, then it sorts what's left. Putting ORDER BY before WHERE will cause a syntax error!"


πŸ“ˆ Learning PathΒΆ