Sorting and pagination

Draft

SQL tables do not promise a natural order. Use ORDER BY when order matters, then LIMIT and OFFSET when you want a page.

Sort rows

ORDER BY makes result order explicit instead of trusting table storage order.

SELECT name, starts_at
FROM events
ORDER BY starts_at DESC;
Loading plan...

Limit and offset

LIMIT and OFFSET can fetch one page from a larger ordered result.

SELECT name, starts_at
FROM events
ORDER BY starts_at DESC
LIMIT 2 OFFSET 2;
Loading plan...

Sort with an index

An index with the same order can let PostgreSQL avoid a separate sort step.

SELECT name, starts_at
FROM events
ORDER BY starts_at DESC
LIMIT 1;
Loading plan...

Try Yourself

Loaded Database:sorting-and-pagination.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Select the three newest events.
2.Select the second page of two oldest events using LIMIT and OFFSET.

What We Learned

  • ORDER BYdefines the order of result rows.
  • LIMITcaps how many rows are returned.
  • OFFSETskips rows before returning a page.
  • Index-backed ordercan avoid a separate sort when the index matches the order.