SQL · Module 11 · Lesson 62 min read

Pagination, VACUUM & ANALYZE

OFFSET pagination – simple but slow at depth

ORDER BY id DESC LIMIT 20 OFFSET 100000 → the database still reads and throws away 100,000 rows. Pages also shift if new rows are inserted while the user scrolls (duplicates or skipped items).

Keyset (cursor / "seek") pagination ✅

Remember the last row you showed, and continue after it:

SQL
-- first page
SELECT … ORDER BY created_at DESC, id DESC LIMIT 20;
-- next page: pass the last (created_at, id) from the previous page
SELECT … WHERE (created_at, id) < ('2026-11-10 12:00', 812)
ORDER BY created_at DESC, id DESC LIMIT 20;
  • Uses the index → constant speed on page 1 or page 10,000
  • Stable even when new rows arrive
  • Needs a unique tie-breaker (id) and a matching index (created_at DESC, id DESC)
  • Can't jump directly to "page 37" — perfect for infinite scroll and "Load more"

MVCC and dead rows

PostgreSQL never overwrites a row in place. An UPDATE writes a new version and marks the old one dead; DELETE marks rows dead. This MVCC (multi-version concurrency control) lets readers and writers work without blocking each other — but dead rows pile up ("bloat").

VACUUM

  • Reclaims space from dead rows so it can be reused
  • Updates the visibility map (needed for index-only scans)
  • Autovacuum runs automatically in the background ✅ — usually you just leave it on
  • VACUUM (VERBOSE) table; manually after huge deletes
  • VACUUM FULL rewrites the table to shrink it on disk, but locks the table — use rarely

ANALYZE

Collects statistics (value distribution, distinct counts) that the planner uses to choose plans.

  • Autovacuum also runs it automatically
  • Run ANALYZE table; manually after big data loads
  • VACUUM ANALYZE does both

Monitoring

pg_stat_user_tables shows dead rows (n_dead_tup) and when vacuum/analyze last ran.

Example

SQL
CREATE TABLE feed AS
SELECT g AS id,
       TIMESTAMPTZ '2026-11-01' + (g || ' seconds')::interval AS created_at,
       'Post ' || g AS body
FROM generate_series(1, 200000) g;
CREATE INDEX idx_feed_keyset ON feed (created_at DESC, id DESC);
ANALYZE feed;

-- ❌ Deep OFFSET: reads and discards 150,000 rows
EXPLAIN ANALYZE
SELECT id, body FROM feed ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 150000;

-- ✅ Keyset: jump straight to the position using the index
-- (the app remembers the last row of the previous page)
EXPLAIN ANALYZE
SELECT id, body FROM feed
WHERE (created_at, id) < (TIMESTAMPTZ '2026-11-01' + INTERVAL '50000 seconds', 50000)
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- Index Scan using idx_feed_keyset … actual rows=20 — fast at any depth

-- Dead rows after a big update
UPDATE feed SET body = body || ' (edited)' WHERE id <= 50000;
SELECT pg_stat_force_next_flush();          -- statistics are normally flushed every few seconds
SELECT relname, n_live_tup, n_dead_tup
FROM pg_stat_user_tables WHERE relname = 'feed';
-- n_dead_tup ≈ 50000 (old row versions)

VACUUM (ANALYZE) feed;
SELECT relname, n_dead_tup, last_vacuum IS NOT NULL AS vacuumed
FROM pg_stat_user_tables WHERE relname = 'feed';
-- n_dead_tup = 0

-- Table size including indexes
SELECT pg_size_pretty(pg_total_relation_size('feed')) AS total_size;

DROP TABLE feed;