PostgreSQL: How to Make Queries on Multi-Million Row Tables Stop Being a Headache

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

If you’ve already wrestled with large tables in MySQL or SQL Server, you know all too well that performance isn’t a “nice to have”: it’s pure survival. In PostgreSQL, once a logging, audit, or transactions table comfortably crosses 20–30 million rows, a poorly designed query doesn’t just run slow… it can make the CPU scream, saturate disk I/O, and generate table bloat everywhere that impacts every other database running on the same cluster.

This guide is aimed at developers working in production who want concrete, fast-to-apply improvements that deliver real, measurable results—without heavy academic theory.

Let’s dive in:

1. SELECT: Be Radically Selective with Columns

PostgreSQL uses TOAST (The Oversized-Attribute Storage Technique) to move large values (TEXT, JSONB, BYTEA, etc.) out of the main table page. It’s a great feature… until you query all of them at once.

A very common mistake we see every day:

SELECT *
FROM facturas
WHERE cliente_id = 500;

If facturas has columns like descripcion TEXT, xml_factura XML, metadata JSONB, or similar, you are forcing the database engine to:

  • Read additional heap pages from disk
  • Decompress TOAST chunks your application might not even need
  • Stream kilobytes (or megabytes) over the wire that your application will simply discard

The mature, responsible approach:

SELECT id, numero_factura, fecha_emision, total, estado
FROM facturas
WHERE cliente_id = 500;

What do you actually gain?

  • Less memory pressure on the backend process
  • Significantly reduced network bandwidth usage (crucial if running on RDS or similar cloud providers with egress costs)
  • A much higher chance of satisfying queries with an Index-Only Scan
  • Considerably less random disk I/O

When a table reaches millions of rows, avoiding SELECT * ceases to be a micro-optimization and becomes sound architectural design.

2. SARGable Conditions: Let the Index Do Its Job

The Postgres query planner can only leverage an index if the WHERE condition is friendly to it (SARGable = Search ARGument able).

A classic performance-killing anti-pattern:

SELECT COUNT(*)
FROM logs
WHERE DATE(created_at) = '2026-02-23';

Every single row must be passed through the DATE() function. Goodbye index → hello almost guaranteed Sequential Scan.

The SARGable version that hits the index (and flies):

SELECT COUNT(*)
FROM logs
WHERE created_at >= '2026-02-23 00:00:00'
  AND created_at  < '2026-02-24 00:00:00';

The standard B-tree index on created_at can now do its job.

What if you genuinely need the function?

PostgreSQL offers a powerful mechanism: expression-based indexes.

CREATE INDEX idx_logs_dia ON logs (DATE(created_at));

Or with date truncation if you only query by month/year:

CREATE INDEX idx_logs_mes ON logs (DATE_TRUNC('month', created_at));

This is one of the best features in Postgres: it allows you to index practically any deterministic expression used in your WHERE clauses.

3. Sequential Scan Is Not Automatically the Enemy

Seeing this in your execution plan:

Seq Scan on logs  (cost=...)

does not automatically mean your query is broken.

A sequential scan makes complete sense when:

  • The query returns a large percentage of the table (say, > 5–15%)
  • Selectivity is very low
  • The planner correctly calculates that random index lookups would cost more than scanning contiguous pages sequentially

It becomes an issue when:

  • You expect only a few rows back
  • The table is massive
  • The planner still chooses a Seq Scan

The first step to check: update planner statistics.

ANALYZE logs;
-- o mejor aún, si puedes permitirte un ratito:
VACUUM ANALYZE logs;

Frequently, the planner makes suboptimal choices simply because table statistics are stale or outdated.

4. Ditch OFFSET for Deep Pagination: Use Keyset (Seek Method)

The classic database killer:

SELECT id, evento, created_at
FROM logs
ORDER BY id DESC
OFFSET 1000000
LIMIT 50;

To skip one million rows, Postgres must:

  1. Locate them
  2. Sort them
  3. Discard them one by one

This scales poorly. Beyond page 10,000, latency degrades significantly.

The pragmatic and scalable alternative: Keyset pagination

Page 1:

SELECT id, evento, created_at
FROM logs
ORDER BY id DESC
LIMIT 50;

Suppose the last id returned is 105432.

Page 2:

SELECT id, evento, created_at
FROM logs
WHERE id < 105432
ORDER BY id DESC
LIMIT 50;

Concrete advantages:

  • Near-constant response time regardless of page depth
  • Direct index traversal without scanning discarded rows
  • Far more resilient to concurrent inserts (minimal risk of skipped or duplicated records)

Essential requirement: the ordering column must be indexed and unique/deterministic (id autoincrement, created_at + id, etc.).

5. Index-Only Scans + INCLUDE: Less I/O Means Better Performance

An Index-Only Scan occurs when Postgres retrieves all required data directly from the index without touching the table heap.

Practical example:

CREATE INDEX idx_ventas_cliente_info
ON ventas (cliente_id)
INCLUDE (monto_total, fecha_emision, estado);

Query:

SELECT cliente_id, monto_total, fecha_emision
FROM ventas
WHERE cliente_id = 98765;

If the Visibility Map is current (kept clean by regular VACUUM operations), Postgres reads exclusively from the index → drastically reducing disk I/O.

6. BRIN: The Lightweight Index for Massive Append-Only Tables

B-tree indexes are exceptional… until a table reaches hundreds of millions of rows and the index size itself becomes costly to maintain in RAM and on disk.

BRIN (Block Range Index) stores summary metadata for physical page ranges rather than individual rows.

CREATE INDEX idx_logs_created_brin
ON logs USING BRIN (created_at);

When BRIN excels:

  • Append-only or mostly immutable datasets (logs, sensor telemetry, date-ordered transactions)
  • Data naturally ordered on disk by the indexed column
  • Range-based queries (filtering by days, months, years)

When NOT to use BRIN:

  • Point lookups on UUIDs or email addresses
  • Tables with heavy, random UPDATE or DELETE operations

BRIN indexes consume minimal disk space, build quickly, and on massive time-series logs can provide high performance gains at almost zero storage overhead.

7. MVCC and Bloat: Do Not Ignore Autovacuum

PostgreSQL relies strictly on Multi-Version Concurrency Control (MVCC). Every UPDATE or DELETE creates a new row version; the old version remains as “dead tuple” space until autovacuum reclaims it.

If autovacuum cannot keep up:

  • Tables and indexes suffer bloat
  • Reads must check more outdated versions (increasing unnecessary “Heap Fetches”)
  • Overall throughput drops across the entire database

Optimizing queries without monitoring and tuning VACUUM only treats the symptoms, not the root cause.

At a minimum, monitor dead tuples:

SELECT relname, n_dead_tup, n_live_tup, last_autovacuum
FROM pg_stat_all_tables
WHERE relname = 'logs'
ORDER BY n_dead_tup DESC;

On high-write tables, consider tuning parameters like autovacuum_vacuum_scale_factor and autovacuum_vacuum_cost_limit.

8. The Essential Diagnostic Tool: EXPLAIN ANALYZE

Never optimize queries based on assumptions.

Always inspect the actual execution plan:

EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
SELECT ...

Pay attention to:

  • Significant discrepancies between Rows Removed by Filter and estimated row counts
  • actual time vs. planner cost estimates
  • High loop counts in nested loops
  • Shared hit/read metrics to measure physical disk reads vs. buffer cache hits

Base decisions on execution statistics, not guesswork.

Real Case: From Seconds to Milliseconds

A problematic query encountered recently:

SELECT *
FROM transacciones
WHERE EXTRACT(MONTH FROM fecha) = 1;

Bottlenecks:

  • Function applied directly to the column → invalidates the standard index
  • Extracts January for every single year across all records
  • Triggers a full Sequential Scan

The optimized rewrite:

SELECT id, monto, referencia
FROM transacciones
WHERE fecha >= '2026-01-01'
  AND fecha  < '2026-02-01';

Typical benchmark on an ~80M row table:

  • Switched to an Index Scan or Bitmap Index Scan
  • Disk I/O drastically reduced
  • Execution time dropped from 4–12 seconds down to 15–80 ms

Summary: The Mindset That Drives Real Gains

Optimizing large PostgreSQL tables isn’t about collecting clever tricks. It’s about understanding how the query planner evaluates costs and designing queries with that execution model in mind:

  • Write SARGable WHERE conditions that indexes can consume cleanly
  • Request only the columns your application actually uses
  • Use INCLUDE to achieve Index-Only Scans when read patterns warrant it
  • Evaluate BRIN indexes for massive, naturally sorted datasets
  • Treat VACUUM configuration and statistics updates as vital parts of application performance, not optional maintenance

When you apply these fundamentals, scaling from hundreds of thousands to tens of millions of rows is no longer an emergency—it’s simply a matter of making sound engineering choices from day one.