Lesson 3 of 10 · 7 min · 2 hands-on steps

Sorting, Limiting & DISTINCT

Order results, take the top N, and remove duplicates.

ORDER BY

SQL · try it
SELECT name, price FROM products ORDER BY price;        -- cheapest first
SQL · try it
SELECT name, price FROM products ORDER BY price DESC;   -- most expensive first

Sort by several columns, where the second breaks ties:

SQL · try it
SELECT name, department_id, salary FROM employees
ORDER BY department_id, salary DESC;

LIMIT: just the top few

SQL · try it
SELECT name, price FROM products ORDER BY price DESC LIMIT 2;

LIMIT with OFFSET is how websites show page 2, page 3… of results:

SQL · try it
SELECT name FROM customers ORDER BY name LIMIT 2 OFFSET 2;

DISTINCT: no duplicates

SQL · try it
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 done

Step 1 of 2 · Top 3 earners

Return the name and salary of the 3 highest-paid employees, highest first.

SQL
SELECT name, salary FROM employees;

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What does ORDER BY price DESC do?

Create a free account to track your progress.