Skip to main content

PostgreSQL Performance: Indexing Strategies

A slow application is usually a slow database. Before you cache everything in Redis, verify your indexes.

The EXPLAIN ANALYZE Command
#

This is your best friend. It tells you exactly how Postgres executes a query.

EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';

If you see Seq Scan (Sequential Scan), Postgres is reading every row in the table. That’s O(N). We want O(log N).

Index Types
#

  1. B-Tree (Default): Great for =, <, >, BETWEEN.

    CREATE INDEX idx_users_email ON users(email);
  2. GIN (Generalized Inverted Index): Essential for JSONB and Full-Text Search.

    CREATE INDEX idx_products_data ON products USING GIN (data);

Partial Indexes
#

Optimization: If you frequently query a subset of data (e.g., is_active=True), creating an index ONLY for those rows saves space and speeds up writes.
CREATE INDEX idx_active_users ON users(id) WHERE is_active = TRUE;