Filtering & Sorting Lesson 7 of 21
SQL LIMIT and DISTINCT
Show only the top results with LIMIT and OFFSET (like pages of results), and remove duplicate values with SELECT DISTINCT.
Two small keywords answer two very common questions: "What are the top 3?" (LIMIT) and "What different values are there?" (DISTINCT).
LIMIT: only the first few rows
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;
LIMIT goes at the very end of the query. Combined with ORDER BY, it gives you "top N" lists: top students, best-selling products, latest orders.
SELECT id, order_date, status
FROM orders
ORDER BY order_date DESC
LIMIT 5;
OFFSET: skipping rows
OFFSET skips a number of rows before starting. Websites use this for "pages" of results:
SELECT id, name
FROM products
ORDER BY id
LIMIT 5 OFFSET 5;
Page 1 is OFFSET 0, page 2 is OFFSET 5, page 3 is OFFSET 10. The formula is OFFSET (page - 1) * per_page.
Other databases
| Database | Top 3 syntax |
|---|---|
| MySQL, SQLite, PostgreSQL | ... LIMIT 3 |
| SQL Server | SELECT TOP 3 ... |
| Oracle, standard SQL | ... FETCH FIRST 3 ROWS ONLY |
DISTINCT: removing duplicates
Which barangays do our customers come from? Selecting the column shows repeats:
SELECT barangay FROM customers;
Add DISTINCT to show each value only once:
SELECT DISTINCT barangay
FROM customers
ORDER BY barangay;
SELECT DISTINCT category
FROM products
ORDER BY category;
DISTINCT on several columns
With more than one column, DISTINCT removes rows where the whole combination repeats:
SELECT DISTINCT grade, section
FROM students
ORDER BY grade, section;
Counting distinct values
SELECT COUNT(DISTINCT customer_id) AS customers_who_ordered
FROM orders;
Eight customers exist, but only seven have placed orders. (Carlo Mendoza has never bought anything.) You'll learn COUNT properly in the aggregate functions lesson.
Putting it together
SELECT name, price
FROM products
WHERE category = 'Drinks'
ORDER BY price
LIMIT 3;
The full order of clauses so far: SELECT → FROM → WHERE → ORDER BY → LIMIT.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04