Aral Code

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

SQL The 3 most expensive products
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.

SQL The 5 most recent 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:

SQL Page 2 of products (5 per page)
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

DatabaseTop 3 syntax
MySQL, SQLite, PostgreSQL... LIMIT 3
SQL ServerSELECT 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:

SQL Barangays, with repeats
SELECT barangay FROM customers;

Add DISTINCT to show each value only once:

SQL Each barangay once
SELECT DISTINCT barangay
FROM customers
ORDER BY barangay;
SQL All product categories
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:

SQL Each grade-and-section combination
SELECT DISTINCT grade, section
FROM students
ORDER BY grade, section;

Counting distinct values

SQL How many different customers have ordered?
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

SQL The 3 cheapest drinks
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. 🙂

1. Which query gives the 5 cheapest products?
2. What does DISTINCT do?
3. For page 3 with 10 items per page, what is the OFFSET?
4. Where does LIMIT go in a query?

By Sir Reyel · Last updated 2026-12-04