HomeBlogDatabase Indexing Explained with Real-World Examples

Engineering Guide · 8 min read · May 18, 2026

Database Indexing Explained with Real-World Examples

Adding indexes blindly slows down writes without fixing slow reads. This guide breaks down how B-Tree, composite, covering, and partial indexes actually work in production using real EXPLAIN ANALYZE diagnostics.

Author
Smit Desai
Published
May 18, 2026
Read time
8 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

When a production endpoint suddenly slows from 40ms to 3.5 seconds after six months of quiet operation, the database didn't suddenly get lazy. The table simply crossed the threshold where sequential disk scans stopped fitting comfortably in RAM.

Yet I often audit sluggish apps that already have 14 indexes on a single 18-column table—and the critical query is still doing a full table scan. Indexing only works when the index structure matches how your queries filter, sort, and project rows. Here is how database indexing works under the hood, with concrete SQL examples you can verify in EXPLAIN.

Database Indexing and EXPLAIN ANALYZE Query Optimization


How a B-Tree Index Actually Saves Time

Without an index, finding WHERE account_id = 8841 forces the engine to read every data page on disk (a Sequential Scan). A standard B-Tree index builds a balanced, sorted tree over your chosen key(s), keeping tree depth tiny—typically 3 to 4 hops even across 50 million rows.

Think of a B-Tree like a sorted directory: instead of flipping through every page of a 5,000-page ledger, you jump to the root page, follow two branch pointers, and land directly on the leaf pointer telling you where the row sits.

Why Databases Ignore Valid Indexes

Three everyday developer habits silently disable B-Tree indexes:

  1. Wrapping indexed columns in functions: Writing WHERE LOWER(email) = 'smit@example.com' prevents using a standard index on email. Either normalize on write, use case-insensitive CITEXT, or create an expression index: CREATE INDEX idx_users_lower_email ON users (LOWER(email)).
  2. Leading wildcards: LIKE 'abc%' uses a B-Tree index cleanly; LIKE '%abc%' cannot use a standard B-Tree because the sorted prefix is unknown. Use a trigram GIN index (pg_trgm) or full-text search instead.
  3. Implicit type casts: Comparing a VARCHAR column to an integer parameter (WHERE phone = 9876543210) forces row-by-row casting and skips the index.

Composite Indexes: The Equality-Sort-Range Rule

Single-column indexes rarely optimize real SaaS queries because production queries filter and sort across multiple fields simultaneously. Consider a job queue or order dashboard query:

SELECT id, total_cents, created_at
FROM orders
WHERE workspace_id = 19
  AND status = 'processing'
  AND created_at >= NOW() - INTERVAL '30 days'
ORDER BY created_at DESC
LIMIT 25;

If you create separate indexes on workspace_id, status, and created_at, the database usually picks just one (or merges bitmaps expensively) and still scans thousands of irrelevant rows. Instead, design one composite index using Equality → Sort → Range:

-- Equality columns (workspace_id, status) first; Sort/Range (created_at DESC) last
CREATE INDEX idx_orders_workspace_status_created
    ON orders (workspace_id, status, created_at DESC);

Because workspace_id and status are exact equality filters, all matching rows sit contiguously inside the index, already pre-sorted by created_at DESC. PostgreSQL or MySQL walks straight to the first 25 entries and stops immediately—zero in-memory sorting required.

For deeper query planner diagnostics, read the PostgreSQL performance tips reference.


Partial and Covering Indexes: Two High-Leverage Patterns

1. Partial Indexes for Skewed Operational Tables

Imagine an email_deliveries table with 20 million historical rows where 99.9% have status = 'sent' and only 800 rows currently have status = 'queued'. Indexing the entire status column wastes hundreds of megabytes indexing 'sent' rows you never poll.

A partial index indexes only the active working set:

CREATE INDEX idx_email_deliveries_queued
    ON email_deliveries (scheduled_at ASC)
    WHERE status = 'queued';

This index stays just a few kilobytes large, remains permanently cached in memory, and makes worker polling instantaneous while adding zero index maintenance overhead once a row flips to 'sent'.

2. Covering Indexes (INCLUDE) for Index-Only Scans

Normally, matching an index leaf still requires jumping to the table heap to fetch non-indexed columns like total_cents. A covering index attaches extra payload columns to the leaf nodes so the database answers the entire query straight from the index (Index Only Scan):

CREATE INDEX idx_orders_dashboard_cover
    ON orders (workspace_id, status, created_at DESC)
    INCLUDE (total_cents, currency);

Keep INCLUDE payloads slim—never stuff large TEXT or JSONB blobs into covering indexes, or you will bloat memory across every leaf page.


Verifying With EXPLAIN (ANALYZE, BUFFERS)

Never guess whether an index helped. Run EXPLAIN (ANALYZE, BUFFERS) in staging on production-like row counts before and after adding the index:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents, created_at
FROM orders
WHERE workspace_id = 19 AND status = 'processing'
ORDER BY created_at DESC
LIMIT 25;

Watch two numbers closely:

  • Execution Time: Should drop from hundreds of milliseconds to low single-digit milliseconds.
  • Buffers: shared hit / read: Indicates how many 8 KB pages the engine touched. Cutting shared read from 45,000 pages down to 6 shared hit pages is how you cure CPU spikes and I/O throttling.

On a Laravel and MySQL rebuild I led, fixing missing composite indexes alongside N+1 Eloquent loops dropped one mission-critical dashboard from 3,982 queries down to 52 queries under 30ms—a process I documented step by step in optimizing slow database queries in Laravel and MySQL.


Quick Reference: Choosing the Right Index Type

Index Type Best Used For Avoid When
B-Tree (Default) Exact lookups, ORDER BY, < / > ranges, prefix% Unanchored LIKE '%term%' or JSON key filtering
Composite B-Tree Multi-column WHERE + ORDER BY queries Leading column is rarely filtered in queries
Partial Index Skewed queues (status = 'pending'), active-only unique slugs Queries omit the exact WHERE predicate
Covering (INCLUDE) High-frequency read dashboards fetching 2–4 small columns Heavy write tables with wide text columns
GIN (PostgreSQL) JSONB containment (@>), arrays, full-text (tsvector) Simple scalar lookups or write-heavy low-read logs
BRIN (PostgreSQL) Huge append-only time-series tables ordered by created_at Tables where rows are frequently updated/reordered

Also remember what indexes cannot solve: if your application hammers the database thousands of times per second for identical leaderboards, feature flags, or rate limits, offload those hot keys to Redis rather than scaling SQL read replicas endlessly. The Redis developer guide outlines data structures built specifically for those patterns.


Auditing Slow Production Queries With SmitDev

If your database CPU sits above 70% or deploys feel fragile under traffic spikes, throwing bigger RDS instances at the problem only buys temporary relief. Often, a targeted audit of slow query logs, index bloat, and ORM hydration cuts cloud spend while making every page feel instant.

Whether you need help to upgrade old software or want dedicated senior bandwidth to eliminate query bottlenecks, SmitDev works directly inside your stack—available via $55/day (8–9 hours) focused optimization sprints, flexible hourly developer support, or $1,999/month dedicated delivery. Get in touch on our contact page and share your slow query symptoms.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

Why does my database ignore an index I already created?

Common culprits include wrapping the indexed column in a function like LOWER(email), using leading wildcards like LIKE '%term', mismatched data types causing implicit casts, or low selectivity where the planner decides a sequential scan is cheaper.

What is the golden rule for composite index column order?

Follow Equality, Sort, Range (ESR): put exact-match equality columns first, sorting columns (ORDER BY) next, and range filters (>, <, BETWEEN) last. Reversing this order forces the database to scan far more index entries.

Can having too many database indexes hurt performance?

Yes. Every INSERT, UPDATE, and DELETE must update every index on the table, increasing write amplification, WAL/binlog volume, and memory pressure as unused indexes compete for shared buffer pool RAM.

When should I use a partial index instead of a full index?

Use a partial index when queries consistently target a small subset of rows—such as WHERE status = 'pending' or WHERE deleted_at IS NULL. It keeps the index tiny enough to stay permanently hot in RAM.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.