Start learning free

LESSON 43 OF 173 · BACKEND: SQL

LIMIT and OFFSET

Practice

A long list is often shown one page at a time: the first three products, then the next three, and so on. SQL has two words for it. LIMIT keeps only the first rows of the answer. OFFSET skips rows before LIMIT starts counting.

Paging needs sorted rows. Without ORDER BY, the database may send the rows in any order, and “the first three” would mean nothing. The database sorts first, then skips, then keeps.

Here is the idea on another table: customers in A-to-Z order, two per page. This query asks for page 2: it skips the first two customers and shows the next two.

const query = [
  "SELECT name, city",
  "FROM customers",
  "ORDER BY name",
  "LIMIT 2",
  "OFFSET 2",
].join(" ");

Your query must print page 2 of the products, three per page, cheapest first:

name | price
Mug | 12
Plant | 15
Teapot | 22
(3 rows)

Your task: write a query that shows each product's name and price from products, sorted by price, then skips the first 3 rows and keeps the next 3.


Assignment
Follow the Coding Tutorial to build the query one clause per line: SELECT, FROM, ORDER BY, LIMIT, then OFFSET.


Hint
Page n skips (n − 1) × 3 rows, so page 2 skips 3. Each clause is its own string in the array, with a comma after it: .join(" ") joins the pieces into one query, and the spaces keep the words apart.


STEP 1 OF 5
    Ctrl + Enter to check