Lesson 3 of 10 · 7 min · 2 hands-on steps
Sorting, Limiting & DISTINCT
Order results, take the top N, and remove duplicates.
ORDER BY
SELECT name, price FROM products ORDER BY price; -- cheapest first
SELECT name, price FROM products ORDER BY price DESC; -- most expensive first
Sort by several columns, where the second breaks ties:
SELECT name, department_id, salary FROM employees ORDER BY department_id, salary DESC;
LIMIT: just the top few
SELECT name, price FROM products ORDER BY price DESC LIMIT 2;
LIMIT with OFFSET is how websites show page 2, page 3… of results:
SELECT name FROM customers ORDER BY name LIMIT 2 OFFSET 2;
DISTINCT: no duplicates
SELECT DISTINCT city FROM customers;
Without
ORDER BY, a database can return rows in any order, and the order may change. If the order matters, always say so.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · Top 3 earners
Return the name and salary of the 3 highest-paid employees, highest first.
SELECT name, salary FROM employees;
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Unique cities
Return each city that has customers, once, in alphabetical order.
SELECT city FROM customers;
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does ORDER BY price DESC do?
Create a free account to track your progress.