DevPath · Learn to code ESPTEN

Advanced filtering

DISTINCT and LIMIT / OFFSET

DISTINCT: unique values

DISTINCT removes duplicate rows from the result. It is very useful for finding out which distinct values exist in a column:

-- All existing categories, without repeating
SELECT DISTINCT category FROM products;

If you select several columns, DISTINCT acts on the full combination of those columns.

LIMIT: limit the number of rows

LIMIT n returns at most n rows. Combined with ORDER BY it serves to get "the top N":

-- The 3 most expensive products
SELECT name, price FROM products
ORDER BY price DESC
LIMIT 3;

OFFSET: skip rows (pagination)

OFFSET m skips the first m rows before starting to return. Together with LIMIT it lets you paginate results:

-- Page 2 (rows 4 to 6) ordering by price ascending
SELECT name, price FROM products
ORDER BY price
LIMIT 3 OFFSET 3;

For LIMIT/OFFSET to give predictable results, always accompany them with an ORDER BY. Without order, the database can return the rows in any order.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← IN, BETWEEN, LIKE and IS NULLView the module →