Learn SQL/Beginner/Sorting & Limiting/SQL Pagination with LIMIT and OFFSET

SQL Pagination with LIMIT and OFFSET

Combine both to slice a sorted result into pages — exactly how most app UIs implement 'page 2, page 3...'

What & Why

Pagination combines LIMIT (page size) with OFFSET (which page). For a page size of 2: page 1 is OFFSET 0, page 2 is OFFSET 2, page 3 is OFFSET 4 — the offset is always (page_number - 1) * page_size.

See How It Works

BUSINESS QUESTION

Page 2 of a 2-per-page campaign listing, sorted by spend descending.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT name, spend FROM marketing.campaigns
ORDER BY spend DESC
LIMIT 2 OFFSET 2;
RESULT — page 2
namespend
Finance Retargeting50000.00
Retention Webinar45000.00

Page 1 (OFFSET 0) would have returned Enterprise Search and Spring Launch instead — the two highest-spend campaigns.

Beginner business practice

Sign up free to try it on a real business scenario