Module 01 · lesson 7

LIMIT and OFFSET: limiting the count

The site's home page needs a "TOP 3 most expensive products" block. Not all 14 — exactly three.

Limiting the count

LIMIT returns no more than the number of rows you specify. For example, the 5 products with the largest stock:

SELECT name, stock
FROM products
ORDER BY stock DESC
LIMIT 5;

Skipping the start: OFFSET

OFFSET skips the first N rows. Together with LIMIT it's the basis of pagination (page-by-page output) — the second "page" of 5 products:

ORDER BY stock DESC
LIMIT 5 OFFSET 5   -- skip the first 5, take the next 5

Important: LIMIT without ORDER BY gives an unpredictable set — order first, then limit.

рядки після ORDER BY stock DESCrows after ORDER BY stock DESC filas tras ORDER BY stock DESC рядок 1row 1 fila 1рядок 2row 2 fila 2 рядок 3row 3 fila 3рядок 4row 4 fila 4 рядок 5row 5 fila 5рядок 6row 6 fila 6 рядок 7row 7 fila 7рядок 8row 8 fila 8 рядок 9row 9 fila 9рядок 10row 10 fila 10 сторінка 1page 1 página 1 LIMIT 5 сторінка 2page 2 página 2 OFFSET 5 LIMIT 5

Your turn

The home page needs a "TOP 3 most expensive" block. Output the name and price of the three most expensive products.

Summary

  • LIMIT N — no more than N rows.
  • OFFSET M — skip the first M.
  • LIMIT and OFFSET always go together with ORDER BY, otherwise the order is random.