Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

Indexes & Query Plans

Direct answer

Indexes (usually B-trees) let the database find rows without scanning the table; the query planner chooses access paths using statistics and shows them in EXPLAIN plans.

When to use this

Use it when queries are slow or plans change.

First 30 seconds

1. Find the slow query (slow log / pg_stat_statements).

2. EXPLAIN ANALYZE <query> (PG/MySQL 8) / actual plan in SSMS.

3. Seq scan on a large table → missing or unusable index.

4. Estimates far from actual → update statistics.

5. Add index, re-run plan.

Operational verification

query → planner uses statistics → chooses index or scan → executes

Evidence · next step

Typical failures are adding redundant indexes, indexing low-selectivity columns without workload evidence, reading only estimated plans, ignoring parameter-sensitive plans/statistics, or treating a scan as automatically bad when most rows are needed. Preserve the first divergent observation and repeat the same bounded verification after remediation.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Common mistakes
What not to infer

Databases owns engine index/optimizer behavior. Observability can retain query latency/throughput telemetry; it does not replace plan/engine verification.

Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts · Databases owns engine index/optimizer behavior. Observability can retain query latency/throughput telemetry; it does not replace plan/engine verification.
Scope / prerequisiteUse it when queries are slow or plans change.
What next?3 suggested next steps
Child topics (this level)4
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification workflow Verify boundary

Capture the exact query and parameters, inspect its execution plan and row estimates, then compare reads/time and returned rows. Check index key order/selectivity and stale statistics before adding an index; validate write overhead and plan choice after any change.

Step 2 Failure signatures and limits Narrow the fault

Typical failures are adding redundant indexes, indexing low-selectivity columns without workload evidence, reading only estimated plans, ignoring parameter-sensitive plans/statistics, or treating a scan as automatically bad when most rows are needed.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

test · 1
Drill down

Subtopics

Go one level deeper into this subject.

Key points

Index columns used in WHERE, JOIN and ORDER BY; column order matters in composite indexes. Too many indexes slow writes. Compare estimated and actual rows in EXPLAIN ANALYZE.

Key checks
  • EXPLAIN ANALYZE <query> — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand

Operating model

Indexes & Query Plans explains how engines choose access paths to locate, join, sort and aggregate data. B-tree-style indexes trade write/storage cost for ordered lookup capability; composite key order, selectivity and predicates influence usefulness. The optimizer plan is an estimate/strategy that must be compared with runtime behavior.

ReferenceHow it works1 section · depth on demand

In depth

Indexes let the database find rows without scanning whole tables; the query planner decides whether and how to use them. Most performance problems come down to missing or unsuitable indexes, or queries written so indexes cannot be used.

Index typeUse
B-tree (default)Equality and range lookups, sorting
HashEquality only
GIN / full-textArrays, JSON, text search (PostgreSQL)
CompositeSeveral columns; order matters (leftmost prefix)
Covering/INCLUDEAnswer query from the index alone

Reading query plans:

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM interfaces WHERE device_id = 42;   -- PostgreSQL
EXPLAIN ANALYZE SELECT * FROM interfaces WHERE device_id = 42;              -- MariaDB/MySQL 8

Look for sequential/full scans on large tables, large differences between estimated and actual rows (outdated statistics), and expensive sorts. Indexes speed up reads but slow writes and use space — remove unused ones.

ReferenceImportant terms & boundaries1 section · depth on demand

Scope map

  • B-tree concepts
  • Composite indexes
  • Selectivity
  • Covering/index-only access
  • EXPLAIN/query plans
  • Scan vs seek/index lookup concepts
  • Index maintenance trade-offs
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

PostgreSQL PostgreSQL 14 or laterCreate an index for a frequent filter and confirm the planner uses it.

Assumptions: Run on a copy or during a quiet period; CONCURRENTLY avoids blocking writes.

CREATE INDEX CONCURRENTLY orders_created_at_idx ON orders (created_at);
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE created_at >= now() - interval '1 day';

Expected output

PostgreSQL PostgreSQL 14 or laterEXPLAIN (ANALYZE) SELECT * FROM orders WHERE created_at >= now() - interval '1 day';

Expected state: The plan uses an index scan and the actual row count is close to the estimate.

Index Scan using orders_created_at_idx on orders  (cost=0.43..812.20 rows=2950 width=48) (actual time=0.031..2.114 rows=3012 loops=1)
  Index Cond: (created_at >= (now() - '1 day'::interval))
Planning Time: 0.180 ms
Execution Time: 2.402 ms
Compare rows= (estimate) with actual rows=; large gaps mean stale statistics. A Seq Scan can still be correct when most of the table matches. Illustrative authored output: field layout matches the tool, values will differ in your environment.
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-29 · otherMariaDB / PostgreSQL / Microsoft SQL Server concepts PostgreSQL current documentation

Documentation verification: confirms the upstream model used by the Topic. It does not assert local production behavior.

Basis: https://www.postgresql.org/docs/current/using-explain.html · confidence 92%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
indexes & query plansdatabase indexquery planEXPLAIN databaseB-tree index
Embedded reference data

Quick lookup tables

Indexes & Query Plans verification boundary matrix

A compact lookup separating intent, owning component state, effective state and consumer-visible outcome for Indexes & Query Plans.

BoundaryInspectHealthy interpretationDo not infer
IntentB-tree conceptsIntended object/scope is explicit and versioned where relevantIntent is already effective
Owning runtime/control planeComposite indexes / SelectivityOwner accepts and reports the expected object stateDownstream dependencies are healthy
Effective stateCovering/index-only accessIndependent read-back matches the intended stateEvery client sees the same result
Consumer outcomeEXPLAIN/query plansThe original bounded check succeeds in the same time windowProduction correctness outside this scope
Depth when you need it

Deep reference

Design & tradeoffs

Scope

Observability can retain query latency/throughput telemetry; it does not replace plan/engine verification.

Confirmation

Confirm action

Continue?