Use it when queries are slow or plans change.
Indexes & Query Plans
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.
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.
query → planner uses statistics → chooses index or scan → executes
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
Databases owns engine index/optimizer behavior. Observability can retain query latency/throughput telemetry; it does not replace plan/engine verification.
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
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 · 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.
Subtopics
Go one level deeper into this subject.
A B-tree index keeps column values sorted so the database can find, range-scan and order rows without reading the whole table.
Subtopic Reading EXPLAIN PlansEXPLAIN shows how the database will run a query; EXPLAIN ANALYZE runs it and shows actual time and row counts per step.
Subtopic Table Statistics and ANALYZEThe query planner relies on statistics about row counts and value distribution; stale statistics lead to bad plans.
Subtopic Partial and Expression IndexesPartial indexes cover only rows matching a condition; expression indexes index the result of a function such as lower(email).
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.
EXPLAIN ANALYZE <query>— first check for this topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -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 type | Use |
|---|---|
| B-tree (default) | Equality and range lookups, sorting |
| Hash | Equality only |
| GIN / full-text | Arrays, JSON, text search (PostgreSQL) |
| Composite | Several columns; order matters (leftmost prefix) |
| Covering/INCLUDE | Answer 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
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
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
EXPLAIN (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 msCompare 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.Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
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%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.
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.
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.
| Boundary | Inspect | Healthy interpretation | Do not infer |
|---|---|---|---|
| Intent | B-tree concepts | Intended object/scope is explicit and versioned where relevant | Intent is already effective |
| Owning runtime/control plane | Composite indexes / Selectivity | Owner accepts and reports the expected object state | Downstream dependencies are healthy |
| Effective state | Covering/index-only access | Independent read-back matches the intended state | Every client sees the same result |
| Consumer outcome | EXPLAIN/query plans | The original bounded check succeeds in the same time window | Production correctness outside this scope |
Deep reference
Design & tradeoffs
Scope
Observability can retain query latency/throughput telemetry; it does not replace plan/engine verification.