Start learning free

LESSON 43 OF 173 · BACKEND: SQL

LIMIT and OFFSET in Java

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.

String query = "";
query += "SELECT name, city ";
query += "FROM customers ";
query += "ORDER BY name ";
query += "LIMIT 2 ";
query += "OFFSET 2 ";

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: the connection db and the empty string query are already there. 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, each added with +=: SELECT, FROM, ORDER BY, LIMIT, then OFFSET.


Hint
Page n skips (n − 1) × 3 rows, so page 2 skips 3. End each string with a space inside the quotes: += joins the pieces into one query, and the spaces keep the words apart.


STEP 1 OF 5
    Ctrl + Enter to check

    Sql Limit Offset in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free