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.

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:
- Wrapping indexed columns in functions: Writing
WHERE LOWER(email) = 'smit@example.com'prevents using a standard index onemail. Either normalize on write, use case-insensitiveCITEXT, or create an expression index:CREATE INDEX idx_users_lower_email ON users (LOWER(email)). - 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. - Implicit type casts: Comparing a
VARCHARcolumn 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. Cuttingshared readfrom 45,000 pages down to 6shared hitpages 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.