ORDER BY & Sorting: Examples
Module: SQL Fundamentals
Basic Sorting - Single Column
basic
HR needs employee list sorted by salary (highest paid first) for compensation review
-- Sort by salary (descending - highest first)
SELECT employee_id, first_name, last_name, salary, department
FROM employees
ORDER BY salary DESC;
-- Sort by name (ascending - alphabetical)
SELECT employee_id, first_name, last_name, department
FROM employees
ORDER BY last_name ASC; -- ASC is optional (default)
-- Salary descending:
employee_id | first_name | last_name | salary | department
5 | Alice | Johnson | 95000 | Engineering
12 | Bob | Smith | 87000 | Sales
23 | Carol | Davis | 75000 | Marketing
-- Name ascending:
employee_id | first_name | last_name | department
23 | Carol | Davis | Marketing
5 | Alice | Johnson | Engineering
12 | Bob | Smith | Sales
ORDER BY sorts results. DESC = descending (high to low), ASC = ascending (low to high, default). Essential for ranked lists, leaderboards, and organized reports.
All
Multi-Column Sorting with Priority
intermediate
Product catalog needs sorting: first by category, then by price within each category
SELECT product_name, category, price, rating
FROM products
ORDER BY category ASC, price DESC;
-- Sort priority:
-- 1. Category (A-Z)
-- 2. Within each category, price (high to low)
product_name | category | price | rating
Laptop Pro | Electronics | 1299.99 | 4.8
Tablet | Electronics | 599.99 | 4.5
Mouse | Electronics | 29.99 | 4.2
Sofa | Furniture | 899.99 | 4.7
Chair | Furniture | 199.99 | 4.3
Multiple columns create sort hierarchy. First column has highest priority. Within each category, products sorted by price (high to low). Critical for organized product listings.
All