Indexes and Query Performance

Learn why a query that reads a whole table slows down as the data grows, and how an index fixes it. See how B-tree and hash indexes find rows, read query plans with EXPLAIN and EXPLAIN ANALYZE, and estimate how many rows a condition selects. Then design composite and covering indexes and choose a set of indexes for a real workload, keeping in view what every index costs on inserts and updates.

IntermediateLesson 5 of 8 in Database Design and Advanced SQL Course

What you will learn

  1. Compare reading a whole table with looking rows up in an index, and describe how B-tree and hash indexes find rows and which searches each one supports.
    • Compare a full table scan with an index lookup
      Explain what an index is, why it cuts the work a query does, how to create and drop one, and which indexes the database creates for you.
    • Explain how a B-tree index finds and orders rows
      Describe the structure of a B-tree index, trace a lookup and a range scan, and recognize which conditions and sort orders it can serve.
    • Use hash indexes for exact-match lookups
      Explain how a hash index locates rows, what it cannot do, where it is available, and when it is worth choosing over a B-tree.
  2. Ask the database how it will run a query, read each step of the plan, and use estimated and measured figures to find the slow part.
    • Ask for a query plan and read its structure
      Explain what the query optimizer does, display a plan with EXPLAIN in common systems, and read a plan as a tree of steps.
    • Recognize scan, lookup, sort and join steps
      Name the common steps in a plan, explain what each one does with rows, and tell which ones point to a missing or unused index.
    • Interpret costs, estimates and EXPLAIN ANALYZE
      Read the estimated cost, row and width figures, compare them with measured times and row counts, and take measurements safely.
  3. Estimate how many rows a condition selects, explain how the optimizer uses that estimate, and recognize the data and conditions that make an index useless.
    • Estimate selectivity and cardinality
      Define selectivity and cardinality, estimate the matching rows for equality, range and combined conditions, and explain where the estimates come from.
    • Predict whether the optimizer will use an index
      Use selectivity, table size and the form of a condition to predict whether an index is used, and rewrite conditions so that it can be.
  4. Choose the column order of a multicolumn index for the queries it must serve, and build indexes that answer queries without reading table rows.
    • Order the columns of a composite index
      Explain how a multicolumn index is sorted, apply the leftmost-prefix rule, and choose a column order that serves equality, range and sort needs.
    • Build covering indexes for index-only queries
      Recognize when an index covers a query, read the signs in a plan, add included columns, and weigh the extra size.
  5. Weigh what each index costs on writes and storage against what it saves on reads, and choose a small set of indexes for a realistic mix of queries.
    • Weigh the cost of indexes on writes and storage
      Explain how inserts, updates and deletes maintain every index, what indexes cost in storage and build time, and how to find indexes that do not pay off.
    • Select a set of indexes for a workload
      Start from the important queries and writes, propose and merge candidate indexes, use partial indexes where they fit, and check the result with query plans.

Indexes and Query Performance study guide

5 chapters

1

Explain how indexes speed up queries

An index gives the database an organized route to matching rows. To see why that helps, follow the pages read by a full scan and by an index lookup, then trace a B-tree search and a hash lookup. The choice of structure also determines whether the same index can support a date range or return rows in order. Creating an index is simple SQL; choosing a useful one starts with understanding those differences.

1.1 Compare a full table scan with an index lookup

A query can return three rows after reading a million. The returned row count tells you what the query found; the access method tells you how much data it had to inspect.

Scan the table or search an index

Without a suitable index, SELECT * FROM orders WHERE customer_id = 42; reads every row and checks its customer. This full table scan, also called a sequential scan, grows in proportion to the table. Doubling the rows roughly doubles the work.

An index stores values from its key columns in a separate, organized structure, with a way to reach each original row. Think of a book index: find a term, then follow its page references. The database searches the smaller structure and fetches the matching table rows.

Data moves in fixed-size pages, so count page accesses before worrying about milliseconds. If 1,000,000 rows fit 100 to a page, the table occupies 10,000 pages. A full scan visits all of them. A three-level B-tree can find one matching row with about three index-page accesses and one table-page access: about four in this example. Fetching many matches adds more table-page visits, so four is not the cost of every indexed query.

Create the access path
CREATE INDEX idx_orders_customer ON orders (customer_id);

The name identifies the table and search column. Remove it in PostgreSQL or SQLite with DROP INDEX idx_orders_customer;. MySQL uses DROP INDEX idx_orders_customer ON orders;.

A PRIMARY KEY or UNIQUE constraint already supplies an index for checking duplicate keys. Do not create another identical index without a reason. In SQLite, INTEGER PRIMARY KEY instead uses the table's built-in rowid key. CREATE UNIQUE INDEX combines lookup support with duplicate rejection.

Where the rows live

A clustering index stores the table rows in its key order; a table can have at most one such physical ordering. A secondary index points to rows elsewhere. In MySQL's InnoDB, the primary-key tree stores the rows. A secondary entry carries the primary key, so reaching a full row usually means searching that tree too. PostgreSQL stores rows in a separate heap, an unordered table area; all its indexes are secondary.

Keep result meaning separate from speed

An index also helps a join, or the search part of UPDATE and DELETE. It does not change the result of a fully determined query. It can change the order in which rows arrive, though. SELECT * FROM orders LIMIT 10 has no guaranteed subset. Use a unique ordering such as ORDER BY order_date, id when the selected ten must be predictable.

Indexing every column is expensive: entries take space and need maintenance when rows change. An index must match a query's search, join or ordering needs. A query reading much of a table may gain little unless the index also contains all the columns it needs.

Key Takeaways

  • A full scan checks the whole table; an index lookup follows organized keys to matching rows.
  • Page accesses explain why finding a few rows through an index can save substantial work.
  • Primary-key and unique constraints already provide lookup structures.
  • InnoDB stores rows in its primary-key tree; PostgreSQL indexes point into a separate heap.
  • Use a unique ORDER BY when a LIMIT subset must be predictable.

1.2 Explain how a B-tree index finds and orders rows

A B-tree keeps keys in order while keeping every root-to-leaf path the same length. It can find one key quickly and continue through neighboring keys for a range.

Follow a search down the tree

Each node occupies a page and holds many keys. The number of children of an internal node is its fanout. A B-tree is not a binary tree: hundreds of children per page keep it shallow. In a rough fanout-200 model, successive levels reach 200, 40,000 and 8,000,000 entries. About three levels therefore suffice for 1,000,000 keys. Growing 200-fold adds roughly one level, not 200 times as much lookup work.

For customer_id = 42, start at a root with separators 1000 and 2000. Follow the child below 1000. At separators 10, 50 and 300, choose the interval between 10 and 50. A leaf containing 41, 42, 42 and 43 has two matches; follow both row references.

PostgreSQL and InnoDB use the B+-tree variant: every data entry is in the leaves, internal keys guide searches, and linked leaves support ordered scans. SQLite's index B-trees also hold entries in interior pages and walk the tree to find the next key. All are called B-tree indexes in everyday database documentation.

Search a range and use its order

For dates from March 1 through March 31, descend to the first key at or after March 1. Continue in order and stop after March 31. The work is one descent plus the index entries and table rows inside the range. A wider range costs more.

Query needWhat the ordered keys provide
Equality or an IN listOne key or several key searches
<, >= or BETWEENA bounded or open-ended run of keys
IS NULLThe portion containing NULL keys
ORDER BY order_date DESC LIMIT 10A backward scan that can stop early
MIN(order_date) or MAX(order_date)Access to one end of the non-NULL keys

A fixed-prefix pattern such as LIKE 'Mar%' also describes a key range. PostgreSQL with a non-C collation needs suitable pattern indexing, such as text_pattern_ops, for this use. A leading wildcard such as LIKE '%son' gives no starting prefix.

Keep the indexed value visible

A plain index on email orders the stored text, not LOWER(email). To search the lowercase expression, PostgreSQL and SQLite can use:

CREATE INDEX idx_users_email_lower ON users (LOWER(email));

MySQL 8.0.13 and later use double parentheses around a functional key: ((LOWER(email))). The query must use the matching indexed expression.

For a date column, an alternative is to replace YEAR(order_date) = 2026 with order_date >= '2026-01-01' AND order_date < '2027-01-01'. This leaves the column bare and handles timestamps throughout the last day of the year. Match types too: in MySQL, a text phone compared with the number 5551234 requires numeric conversion of the stored strings; compare with '5551234' to allow a text-key lookup.

Key Takeaways

  • A large fanout keeps a balanced B-tree shallow as the table grows.
  • Sorted keys support equality, ranges and ordered output.
  • A range scan descends once, then walks through the matching run.
  • A leading wildcard gives a plain B-tree no useful starting prefix.
  • Use a matching expression index or rewrite a function-wrapped condition as a bare-column range.
  • Compare an indexed column with a value of the appropriate type.

1.3 Use hash indexes for exact-match lookups

A hash index finds a key by calculating where it belongs. This suits exact matches, but the calculated location loses the key's original ordering.

Route a value to a bucket

For WHERE token = 'k7Q2xR', the engine hashes the token, visits the resulting bucket and checks the candidate entries. Different values can share a hash result, a collision, so it must still verify the original value. Hashing is a way to narrow candidates, not evidence that two values are equal.

With well-spread values, an equality lookup takes about the same small amount of work as the table grows. A B-tree lookup grows logarithmically, but its high fanout also keeps searches to a few page accesses. A hash index is therefore a candidate to measure, not an automatic large speedup.

Recognize the missing order
NeedB-treeHash index
Exact equalitySupportedSupported
Date rangeOrdered keys bound the scanHash locations do not bound the range
Prefix text searchA suitable prefix range can helpPrefixes do not identify buckets
Sorted output or minimumKey order can supply itKey order is unavailable

A multicolumn hash index needs the whole key. In a system supporting a hash key on (country, city), the hash of the pair cannot locate every city from country alone. PostgreSQL hash indexes are single-column and cannot enforce UNIQUE; B-trees enforce uniqueness there.

Check what the system provides

PostgreSQL creates a hash index explicitly:

CREATE INDEX idx_sessions_token ON sessions USING HASH (token);

Hash indexes there have supported crash recovery and replication since version 10. A PostgreSQL hash entry stores a 32-bit hash code, so longer text values do not make that stored code longer. A B-tree stores the key values themselves. Equality searches on long tokens or URLs can therefore make hash indexing worth comparing.

In MySQL, InnoDB builds B-tree indexes for user-defined indexes. The MEMORY engine uses hash indexes by default and offers USING BTREE as an alternative. SQLite has no persistent hash-index type. A plain CREATE INDEX defaults to B-tree in PostgreSQL, SQLite and InnoDB.

The useful decision is whether equality is the column's only important access pattern, and whether uniqueness, ranges or ordering will be needed. Measure a hash candidate against a B-tree under the actual workload before giving up those capabilities.

A plan step called Hash Join does not identify a hash index. It builds a temporary hash table from an input during the query. A database can run that join while reading both tables with sequential scans.

Key Takeaways

  • Hash indexes route exact-match keys to buckets and verify candidate values.
  • Hash values do not preserve key order, so ranges and sorting need another access path.
  • A multicolumn hash key needs the full key; PostgreSQL hash indexes support only one column.
  • System support differs: PostgreSQL offers hash, InnoDB user indexes are B-tree, and SQLite has no hash-index type.
  • A Hash Join builds a temporary structure independently of persistent hash indexes.
2

Read query plans with EXPLAIN

SQL describes the rows you want; the query plan shows how the database intends to produce them. Read plans from the scans upward, recognize the joins and sorts that consume those rows, and separate estimated work from measured time. Following the row counts through a plan often reveals more than the name of its chosen index. A useful diagnosis connects the expensive step to a change you can test on realistic data.

2.1 Ask for a query plan and read its structure

The query optimizer, or planner, compares possible access paths, join orders and join methods. It uses data statistics to estimate their costs and chooses the lowest estimated cost. The resulting query plan is a tree of steps that pass rows upward.

Ask for the plan

In PostgreSQL and MySQL, prefix a query with EXPLAIN:

EXPLAIN SELECT * FROM orders WHERE customer_id = 42;

SQLite uses EXPLAIN QUERY PLAN for its readable high-level plan. Plain SQLite EXPLAIN lists virtual-machine instructions. Plain EXPLAIN plans a statement without executing it; measured execution uses a different command.

Read each tree from its deepest inputs toward the result. An index search produces rows, a join combines inputs, and a parent sort orders the join's output. Indentation shows which step supplies which other step. It does not prescribe the order of conditions in the SQL text: the optimizer can reorder ordinary filters and inner joins.

Read a SQLite access path

Before an index, the customer query can show SCAN orders. After creating idx_orders_customer on orders (customer_id), it can show:

SEARCH orders USING INDEX idx_orders_customer (customer_id=?)

SEARCH means it visits a subset selected by a condition. SCAN means a complete traversal; it can traverse a table or an index. USING COVERING INDEX means the needed column values come from the index. USE TEMP B-TREE FOR ORDER BY means a separate ordering step. Similar wording names temporary work for grouping or removing duplicates.

Find the useful fields in MySQL

Traditional MySQL output has one row per table access. possible_keys lists candidates; key names the chosen index or is NULL. rows estimates the rows examined.

typeAccess meaning
ALLFull table scan
indexFull index scan
rangePart of an index
refMatches through a non-unique lookup
eq_ref or constAt most one match per primary-key or unique lookup

In Extra, Using index means covering access, Using filesort means an extra sort, and Using where means filtering rows after access. Using filesort alone does not tell you whether sorting spilled to disk.

Distinguish searching from filtering

An illustrative PostgreSQL plan is:

Index Scan using idx_orders_customer on orders
  (cost=0.43..164.12 rows=40 width=36)
  Index Cond: (customer_id = 42)

Index Cond guides index access. A Filter removes rows after the access step has obtained candidates. The same condition under a sequential scan's Filter still requires reading the table. A filter can reduce output without reducing the pages read.

Formats vary by version, especially in SQLite. For structured output, use PostgreSQL EXPLAIN (FORMAT JSON) or MySQL EXPLAIN FORMAT=JSON. MySQL EXPLAIN FORMAT=TREE is a readable text tree, not JSON.

Key Takeaways

  • The optimizer chooses a plan using estimated costs and data statistics.
  • Read plan inputs upward to the steps that consume their rows.
  • SQLite uses EXPLAIN QUERY PLAN for high-level access paths.
  • MySQL possible_keys lists candidates; key identifies the chosen index.
  • Index conditions guide access; filters reject candidates after access.
  • A full index scan and a selective index search perform different amounts of work.

2.2 Recognize scan, lookup, sort and join steps

An access step tells you how rows enter a plan. Other steps join, group or order those rows. Judge each step by its input size and role, not by whether its name sounds fast.

Choose among scan methods

A PostgreSQL Seq Scan reads table rows in sequence and checks any filter. It is efficient for a small table or a large matching fraction. An Index Scan searches keys and fetches matching heap rows; scattered fetches become costly when many rows match.

An Index Only Scan obtains the query's column values from the index. PostgreSQL can still need heap visits to check visibility. A Bitmap Index Scan first collects matching row locations. A Bitmap Heap Scan then visits table pages in physical order, avoiding repeated random visits to the same page. This often suits a moderate matching fraction, between a few lookups and a full scan.

Separate indexes can be combined. PostgreSQL BitmapAnd intersects matching locations and BitmapOr combines them. MySQL can report index_merge. Combining indexes adds work and does not preserve the ordered stream of a single B-tree scan.

Read sort and aggregate steps

A PostgreSQL Sort names a Sort Key. SQLite reports USE TEMP B-TREE FOR ORDER BY; MySQL reports Using filesort. An index that supplies the required order can remove a separate sort. This matters especially before LIMIT: fetching ten entries in order can avoid sorting a very large input.

HashAggregate groups through a temporary hash table. GroupAggregate consumes rows already sorted by the grouping key, which a matching index can supply. A plain Aggregate calculates one result, such as COUNT(*), over its input. These names describe work performed during the query, not index types.

Follow a join's inputs
Join stepHow it consumes rowsA useful setting
Nested LoopLooks for inner matches for each outer rowFew outer rows and an indexed inner key
Hash JoinBuilds a hash table from one input and probes it with the otherLarge unsorted inputs
Merge JoinWalks two inputs sorted by their join keysOrdered inputs, perhaps from indexes

SQLite implements joins as nested loops, so an inner join-key index is especially useful there.

Suppose a filter selects 200 customers from a country, and each has about 40 orders in a 2,000,000-row orders table. A Nested Loop with an index on orders.customer_id performs 200 lookups and returns about 8,000 order rows. Without that access path, a Hash Join might scan all 2,000,000 orders once. A Nested Loop with an inner full scan could repeat that whole scan for each customer.

Investigate a large scan returning few rows, a large sort before a small limit, or an inner full scan repeated many times. A full scan returning 40% of a table is a different case: sequential access may already be the cheaper plan. The useful question is how much work the chosen step does for these inputs.

Key Takeaways

  • Sequential, ordinary index, index-only and bitmap scans trade different kinds of page work.
  • A matching ordered index can remove a large sort before LIMIT.
  • A Nested Loop repeats its inner access for each outer row.
  • Hash joins and hash aggregates build temporary hash structures without needing hash indexes.
  • Compare the work done with the number of rows the query actually needs.

2.3 Interpret costs, estimates and EXPLAIN ANALYZE

An estimated plan predicts work; a measured plan reports what happened. Keep the units and repeated executions straight before deciding where the query spends its time.

Read estimates in planner units

PostgreSQL writes (cost=startup..total rows=N width=W). Startup is the work before the first output row; total is the work for all output. rows estimates output rows, and width estimates their average size in bytes. Parent costs include child costs. None of these cost numbers is a time in milliseconds.

At PostgreSQL's default cost settings, a sequential page read costs 1.0, a random page read 4.0, processing a row 0.01 and evaluating an operator 0.0025. For a table with 1,250 pages and 100,000 rows, a simple sequential scan costs:

1250×1.0+100000×0.01=2250

One comparison on every row adds 250, giving a total cost of 2,500. The filter can sharply reduce output rows even though all 100,000 rows are examined. Compare candidate costs for the same query and database; costs from different servers do not predict relative elapsed times.

Measure rows, time and loops

EXPLAIN ANALYZE executes the query. PostgreSQL adds actual time=startup..total rows=N loops=L, with time in milliseconds. Repeated steps report averages per execution. For actual time=0.004..0.005 rows=3 loops=200, multiply the total-time average by 200 to get about 1.0 ms, and multiply three rows by 200 to get 600 rows across executions.

Compare estimated rows with actual rows on the same per-execution basis. An estimate of 40 against 40,000 is a thousandfold miss. A large change in the data may have made statistics stale; related filter columns can also defeat an independence estimate. Refresh statistics with PostgreSQL ANALYZE orders;, SQLite ANALYZE; or MySQL ANALYZE TABLE orders;.

Measure data-changing statements on a disposable copy, or use a transaction and ROLLBACK for changes that can be rolled back. An analyzed INSERT, UPDATE or DELETE really executes. PostgreSQL can use BEGIN; EXPLAIN ANALYZE DELETE FROM orders WHERE status = 'test'; ROLLBACK;. MySQL's EXPLAIN ANALYZE, available from 8.0.18, also executes what it measures.

Test a diagnosis

Start with the expensive branch. Account for loops, then compare each parent's time with its children: adding every displayed time would count the same work repeatedly. A high parent time can reflect an expensive child, not work added by that parent.

In PostgreSQL, BUFFERS reports shared hit for pages already in its buffer cache and shared read for pages brought into that cache. A read can come from the operating system's cache, so it is not necessarily a physical disk read. Version 18 includes buffer reporting by default with ANALYZE.

Change one suspected cause, then compare plan, rows and timings over several runs with comparable cache conditions. Use realistic table sizes and distributions: a sound full scan on 500 development rows tells little about the best access path for 2,000,000 production rows.

Key Takeaways

  • Planner costs compare estimated work; actual times are milliseconds.
  • Estimated rows are output rows, not all examined rows.
  • Multiply per-execution actual rows and time by loops to assess repeated work.
  • Parent costs and times include children; summing them double-counts work.
  • A large estimate error suggests statistics or data-dependency problems.
  • Compare repeated measurements on realistic data under similar cache conditions.
  • A shared read brings a page into PostgreSQL's cache and can be served by the operating system cache.
3

Judge when an index helps using selectivity

The usefulness of an index depends on how much of the table a query needs. Estimate the matching fraction, then consider where those rows live and how the query expresses its conditions. A rare value and a common value in the same column can deserve different access methods. Statistics connect those data patterns to the optimizer's estimates, while searchable conditions give it a useful path to consider.

3.1 Estimate selectivity and cardinality

Selectivity is the fraction of table rows satisfying a condition. A highly selective condition keeps a small fraction. State the fraction directly to avoid confusing that wording with a large percentage.

Convert fractions into row counts
matching rows=selectivity×table rows

A column's cardinality is its number of distinct values. In plan discussions, cardinality can also mean the output row count of a step; check the context. High column cardinality often helps equality searches, but it does not guarantee that every value is rare.

Under an equal-frequency estimate, one value among 50,000 distinct customers matches one fifty-thousandth of an orders table. For 2,000,000 rows, that is 40 orders. Five equally frequent status values would give 20%, or 400,000 rows per status.

Allow for uneven data

Real statuses are often unevenly distributed. If 90% are delivered and 1% cancelled, their expected matches are 1,800,000 and 20,000. An optimizer's most common values list, or MCV list, records frequent values and their frequencies so it need not pretend those values occur equally often.

For a non-NULL value absent from the MCV list, PostgreSQL divides the leftover non-NULL fraction among the remaining distinct values:

1−NULL fraction−MCV frequency sumdistinct non-NULL values−MCV count

With 120 distinct countries, five MCVs covering 70%, and no NULLs, the remaining 30% is divided among 115 values. One other country gets about 0.0026 of the table, or about 5,217 rows. If 10% of rows have NULL country, only 20% remains for those same 115 values: about 3,478 rows. NULLs consume part of the population; they are not another ordinary equality value.

Estimate ranges and combined conditions

A histogram divides ordered values into buckets. Equal-frequency buckets each represent the same share of rows, even when their value ranges differ greatly. With 100 buckets, a cutoff halfway through bucket three covers two whole buckets and half another: 2.5%, or 50,000 of 2,000,000 rows, using an even spread inside that bucket.

For independent conditions joined by AND, multiply the fractions. A customer fraction of 1/50,000 and a pending fraction of 1/5 give eight expected orders. Independence is the critical premise.

Suppose 2% of rows describe Lyon customers, 5% describe France, and every Lyon customer in the table is in France. Multiplication predicts 0.1%, or 2,000 rows. The actual conjunction matches the same 2% as Lyon alone: 40,000 rows, twenty times the estimate. PostgreSQL CREATE STATISTICS can record cross-column dependencies.

Statistics are sampled summaries, refreshed with ANALYZE or MySQL ANALYZE TABLE. PostgreSQL also refreshes them automatically. After a large load or distribution change, compare estimates with actual row counts and refresh them before redesigning an otherwise suitable index.

Key Takeaways

  • Multiply a matching fraction by the table's row count to estimate matches.
  • Uniform equality estimates use the number of distinct values; MCV frequencies handle skew.
  • Subtract both MCV frequencies and the NULL fraction before estimating other non-NULL values.
  • Histograms estimate ranges using fractions of ordered buckets.
  • Multiplying AND selectivities assumes independence; related columns can produce large errors.
  • Statistics need refreshing after major changes to the data.

3.2 Predict whether the optimizer will use an index

An index can be available and still be more expensive than a full scan. The optimizer compares the pages and processing needed by each route, using the query's conditions and estimated matches.

Match the access path to the fraction

For a few matches, descending an index and fetching a few rows is cheap. For many scattered matches, those fetches may touch most table pages in an inefficient order. Reading the table in sequence can then win. There is no universal cutoff percentage: row width, caching, physical order and cost settings all matter.

Physical order changes the comparison. Orders inserted roughly by date may put a month's rows on neighboring pages. The same number of matches from randomly scattered customer IDs can require far more separate page visits. PostgreSQL records the relationship between column order and table order as correlation.

A 100-row table may occupy only a few pages, making a full scan sensible. A low-cardinality flag that is true in 95% of rows also offers little filtering for that common value. A rare false value may still justify a lookup. A covering index can help a broad query such as SELECT COUNT(*) FROM users WHERE is_active = true, because it can avoid reading the wider table rows.

Give the index a searchable condition

A sargable condition can guide a search using an indexed column or expression. Compare the key directly with the required value. For example, change total * 1.25 > 100 to total > 80. Change YEAR(order_date) = 2026 to a half-open date range from the start of 2026 to the start of 2027. A matching expression index is another option when the query needs a function result.

For customer_id = 42 OR email = 'ana@example.com', indexed access for both branches allows the engine to combine matches. A selective search for just one branch misses rows matching only the other. A scan is a common result. PostgreSQL can use bitmap OR; MySQL can use index merge.

Splitting the branches with UNION requires care. UNION removes duplicate output rows. Include a unique row key, such as id, so two distinct orders with identical displayed values remain distinct. UNION ALL instead retains overlap, so an order matching both branches can appear twice.

A negation is not inherently broad. If 90% of orders are delivered and the rest are non-NULL, status <> 'delivered' matches 10%. With NULLs, those rows do not satisfy the comparison and must be accounted for separately.

Look beyond WHERE

ORDER BY order_date DESC LIMIT 20 can read the last 20 index entries without a filter or a full sort. An indexed join key can support repeated inner lookups. Searchability is therefore only one reason for index use.

When a plan is slow, check the estimated fraction, access conditions and statistics. MySQL FORCE INDEX can override a choice, but a forced plan can age badly as data changes. Fix the reason for a poor estimate or an unusable condition first; PostgreSQL has no built-in index hints.

Key Takeaways

  • The best scan depends on matching fraction, row placement, table size and caching.
  • A full scan can be the correct choice even when a suitable index exists.
  • Bare-column comparisons and matching indexed expressions make conditions searchable.
  • An OR needs access to every branch's matches; a UNION rewrite must preserve row identity and overlap behavior.
  • Ordering, covering and joins can make an index useful without selective filtering.
4

Design composite and covering indexes

One index can support several queries if its columns follow their search and ordering needs. Trace the sorted tuples in a composite B-tree to see why the first column matters, then distinguish searchable key columns from extra values carried for output. Covering a query can remove table reads, but every added column increases the index's size and maintenance work. The plan shows whether that trade pays off.

4.1 Order the columns of a composite index

A composite index has several key columns. A B-tree on (customer_id, order_date) sorts first by customer, then by date within each customer.

Start with the leftmost prefix
CREATE INDEX idx_orders_cust_date
ON orders (customer_id, order_date);

This index directly narrows customer_id = 42 and customer_id = 42 AND order_date >= '2026-01-01'. All entries for that customer lie together, with dates ordered inside the group.

A date-only search normally lacks one starting customer group. Dates are spread across the groups, so the leftmost-prefix rule says to design searches around the leading columns. Some engines offer a skip scan: PostgreSQL 18 and MySQL 8.0.13 onward can search separate leading-value groups. This works best with few leading values. With 50,000 customers, 50,000 separate searches make a date-leading index a much better candidate for date-only work.

Put equality before a range

Compare two indexes for the same customer-and-date query:

Key orderOrdinary search work
(customer_id, order_date)Find one customer, then one date range inside it
(order_date, customer_id)Read the date range across customers and check the later customer key

After the first range column, later conditions can reject entries inside the index without necessarily shrinking the run traversed. A skip scan can sometimes jump over groups, but equality-first gives a direct contiguous search.

If both predicates are equality tests, either order can narrow to the same pair of values. Choosing the most selective column first is therefore an incomplete rule. Prefer the order that also serves the other important queries.

For Q1, WHERE customer_id = ? AND status = ?, and Q2, WHERE customer_id = ?, choose (customer_id, status). It serves both by a matching prefix. Reversing it serves Q1 directly; Q2 would depend on repeated searches through status groups.

Supply order after fixing a prefix

The customer-date index supports WHERE customer_id = 42 ORDER BY order_date DESC LIMIT 10. Once the customer is fixed, a backward scan returns its latest ten entries with no separate sort. Across all customers, however, it produces customer order first.

Reversing a scan reverses every key direction. An all-ascending index can supply both columns descending. It does not supply ORDER BY customer_id ASC, order_date DESC; declare that mixed direction, or its exact reverse, in the index.

A separate (customer_id) index is often redundant beside (customer_id, order_date), although the smaller index's measured benefit and constraint role still need review. Separate indexes on customer and status can be combined by bitmap or index-merge work, but they do not provide the same single ordered path as (customer_id, status).

Key Takeaways

  • A composite B-tree sorts by its first key, then by later keys within equal prefixes.
  • Put equality keys before the range or ordering key for a direct bounded search.
  • Choose leading equality columns with the whole workload's prefix needs in mind.
  • Skip scans can help with few leading values but do not replace sound column ordering.
  • A backward scan reverses every key direction; mixed ordering needs a compatible index.
  • A composite prefix can make a narrower index redundant; separate single-column indexes are not the same access path.

4.2 Build covering indexes for index-only queries

An index covers a query when it holds every column that query needs for selection, filtering, joins, grouping and ordering. Covering describes the relationship between the index and that query; it is not a separate index structure.

Check all referenced columns

With a SQLite index on (customer_id, order_date), this query can obtain its values entirely from the index:

SELECT order_date FROM orders WHERE customer_id = 42;

Its plan can say USING COVERING INDEX. If the select list adds total, the same index still finds the right rows but must fetch the missing value from the table. Covering requires the filter columns too: selecting only order_date while filtering on an absent status still needs that status value.

PostgreSQL reports Index Only Scan; MySQL uses Using index in Extra. Do not confuse MySQL's access type index, which means scanning a whole index, with its separate covering note.

Carry output values without changing the key

PostgreSQL and SQL Server support included columns:

CREATE INDEX idx_orders_cust_date_total
ON orders (customer_id, order_date) INCLUDE (total);

The key still searches and orders by customer then date. total is stored as payload for output; it is not another search or sort key. If the index is UNIQUE, uniqueness applies to the key columns, not the included payload. PostgreSQL has supported INCLUDE since version 11.

MySQL and SQLite use trailing key columns for this purpose, such as (customer_id, order_date, total). Putting the payload last preserves the useful customer-date prefix. In InnoDB, secondary entries already carry the primary key. If id is the primary key, (customer_id) can cover SELECT id FROM orders WHERE customer_id = 42 without explicitly adding id.

Check PostgreSQL heap visits

PostgreSQL also needs to know that a row is visible to the query. Its visibility map marks heap pages whose rows are all visible. With that mark, the index-only path can skip the heap. Without it, the executor visits the heap even though all column values are in the index.

EXPLAIN ANALYZE reports these visits as Heap Fetches. VACUUM maintains visibility-map information. An archive with mostly unchanged rows can benefit greatly; a table whose pages are constantly changed may still need many visits. Read the actual heap-fetch count before attributing a speedup to avoided table access.

Pay for the extra values

Wider entries mean fewer entries per page, more storage and more pressure on the cache. Changing an included column now requires index maintenance too. Add a small number of narrow values for frequent, important queries. Trying to cover SELECT * copies much of the table into another structure and makes every future column requirement harder to support economically.

Key Takeaways

  • Covering requires every column used by the query, including filters and joins.
  • INCLUDE carries payload without changing search order or key uniqueness.
  • InnoDB secondary indexes already contain the primary-key columns.
  • A PostgreSQL Index Only Scan can still perform heap fetches for visibility checks.
  • Extra payload reduces table reads at the price of larger entries and more write work.
5

Choose indexes for a workload

Indexes earn their place by saving important query work often enough to justify their costs. Start with the queries and writes the database actually receives, then combine compatible access paths and test the result. Read-heavy catalogs and fast-growing event logs place different demands on the same index design. Storage, build time, insert speed and changing query patterns belong in the decision alongside lookup time.

5.1 Weigh the cost of indexes on writes and storage

An index is maintained data. Reads may become faster because writes keep that extra structure ready. Measure both sides of that exchange when deciding how many indexes a table can afford.

Count the extra write work

An insert adds entries to the table's indexes. With one primary-key index and four full secondary indexes, each inserted row adds five index entries. Loading 1,000,000 rows therefore involves 5,000,000 index insertions, in addition to writing the rows. A delete removes or marks the corresponding entries. A unique index also searches for an existing equal key before accepting a new one.

An update must maintain indexes affected by changed key values, payload values or partial-index membership. Engine behavior matters for unaffected indexes too. PostgreSQL can use a HOT update to leave ordinary indexes untouched when indexed columns are unchanged and the original page has room for the new row version. Without those conditions, extra index work can remain. Indexing a frequently changed last_seen_at column can remove a valuable opportunity to avoid that work.

Indexes can also save write time when an update or delete first needs to find a few rows. The search saving and the maintenance cost are separate effects.

Account for space and page changes

Every index occupies storage and competes with table data for memory. Several indexes together can exceed the table's size. Backups and replicas must carry that extra data too. A wide covering index costs more pages than a narrow lookup index.

A full B-tree page can split, moving entries into an additional page and adding maintenance work. Increasing keys tend to append at one end. Random keys, such as random UUIDs, spread changes over the tree and can touch more pages with more unused space between entries. The amount of free space after a split depends on the engine and insertion pattern; it is not a fixed half-full outcome.

Plan builds and bulk loads

Building an index reads the table and consumes time and resources. PostgreSQL's ordinary build blocks writes while it runs. CREATE INDEX CONCURRENTLY allows inserts, updates and deletes during the build but does more total work and cannot run inside a transaction block. A failed concurrent build can leave an invalid index that needs cleanup. InnoDB supports online secondary-index creation with concurrent changes.

For a new or mostly empty table receiving a large bulk load, loading rows first and building indexes afterward is usually faster than maintaining them entry by entry. Keep correctness constraints and the load's required access paths in view when planning that sequence.

Retire indexes using representative evidence

PostgreSQL's pg_stat_user_indexes.idx_scan counts index scans since statistics were reset. MySQL's sys.schema_unused_indexes helps identify candidates with no recorded use. Observe a representative period, including monthly work, before dropping an apparently idle index. Primary-key and unique indexes still enforce constraints even with no query scans.

A product catalog with thousands of reads per change can afford more lookup support than an event log receiving thousands of inserts per second. Revisit the trade when those rates change.

Key Takeaways

  • Each added index creates insert, delete, storage and cache costs.
  • Updates can maintain keys, payload and membership; PostgreSQL HOT avoids ordinary index updates only under its conditions.
  • Unique indexes spend work enforcing correctness even if no query scans them.
  • Index builds have resource and concurrency costs; bulk loading before building can save work.
  • Judge unused-index statistics over a representative period and preserve constraint enforcement.

5.2 Select a set of indexes for a workload

A workload is the mix of queries and writes, their frequencies and their response-time needs. Design indexes for that mix. A table's column list alone does not tell you which access paths deserve storage and maintenance.

Turn important queries into candidates

Find frequent and expensive queries with tools such as PostgreSQL pg_stat_statements or MySQL's slow query log. For each, record equality filters, ranges, joins, ordering, grouping and output columns. Propose equality-leading keys followed by the useful range or ordering key; add covering payload only when it saves enough work.

Consolidate compatible prefixes. (customer_id, order_date) can also serve customer-only access, so a separate (customer_id) is often unnecessary. But (customer_id, status) serves a different second-column filter. Sharing a first column does not mean two candidates can be replaced by one without testing.

Index a child table's foreign-key columns when those searches matter. Joins need them, and a parent deletion or key change must find referencing child rows. PostgreSQL and SQLite do not create that child index automatically; InnoDB supplies one if none suitable exists.

Index a useful subset

A partial index stores only rows satisfying its predicate. PostgreSQL and SQLite support:

CREATE INDEX idx_orders_pending ON orders (order_date)
WHERE status = 'pending';

A query whose conditions imply status = 'pending' can search this smaller date index. A query for all statuses cannot. SQL Server calls this a filtered index; MySQL has no partial indexes. Rows outside the predicate have no entry, while a change that moves a row into or out of the subset changes membership.

Work through an orders workload

The table has 2,000,000 rows and receives 20,000 new orders per hour.

  1. Customer history runs 5,000 times per hour: WHERE customer_id = ? ORDER BY order_date DESC LIMIT 10. Use (customer_id, order_date). The customer equality fixes the prefix; a backward date scan can stop after ten entries. It also supplies a child foreign-key access path.
  2. Overdue pending work runs 60 times per hour: WHERE status = 'pending' AND order_date < ?. Only 0.5%, about 10,000 rows, are pending. The partial date index searches that subset instead of indexing all 2,000,000 orders. New pending rows enter it; completed rows leave it.
  3. A daily monthly-revenue query sums total over a date range. With two years stored, one month touches about 1/24 of the rows, roughly 83,000. If a daily scan meets its time requirement, another index may not pay. If it must be faster, test a date-leading index, possibly carrying total; date-correlated table storage also helps.

Check plans on realistic data. Customer history should have an ordered access path without a separate sort; the pending query should use its subset index. Compare elapsed time, pages, insert throughput and status-update speed. Drop candidates that do not justify their costs. A searchable rewrite, fewer selected columns, a useful LIMIT or refreshed statistics may solve the problem without another index.

Key Takeaways

  • Start with query frequency, response-time needs and write rate.
  • Propose equality-leading keys, then range or order keys, then worthwhile payload.
  • Consolidate prefixes, but test replacements for indexes that merely share a leading column.
  • A partial index serves queries whose conditions imply its predicate.
  • A child foreign-key index supports joins and checks triggered by parent changes.
  • Validate the chosen set with realistic plans, read timings and write measurements.

Indexes and Query Performance examples

5 Walkthroughs

1

Follow the pages from a search to its rows

13 steps
Trace a lookup, extend it into a range, and choose between B-tree and hash access.
  1. 1
    IntroductionGive the database a route to the matches

    A library service stores many loans, but a reader usually asks for only a few. Follow the pages needed to find those loans, then see how the index structure changes what the service can search. A B-tree keeps keys in order, so it serves exact and range searches; a hash index serves only exact matches, so the right choice depends on the query.

    The goal is to connect a query's needs to the work done by its access path.

  2. 2
    ExampleCount the full scan

    The loans table contains 960,000 rows, with 120 rows per table page. A query asks for one loan by its unique reference, but no suitable index exists.

    960000÷120=8000

    The scan checks all 8,000 table pages to find that one row. Returning one row does not mean reading one row: without an organized route, the engine must inspect the table for a match.

  3. 3
    ExampleFollow a three-level lookup

    Add a B-tree on the reference. In a simplified three-level tree, the engine reads a root page, follows a separator to an internal page, then reaches a leaf entry. That entry identifies the loan's table row.

    About three index-page accesses plus one table-page access replace the 8,000-page scan for this one match. More matches would add entry and row-access work; the tree descent is not the whole cost of a broad query.

  4. 4
    ChallengeSeparate access speed from result order

    The service runs SELECT id FROM loans LIMIT 5. After adding an index, it gets a different five IDs. Is the index giving an incorrect result, and how should the query request the five smallest unique IDs?

    ---reveal---

    The query did not define which five rows it wanted, so the changed subset can be valid. Add ORDER BY id before LIMIT 5; the unique ID order then determines which rows come first.

  5. 5
    ExplanationUse many branches per page

    A B-tree stays shallow because each internal page leads to many children. This fanout is often in the hundreds, unlike a binary tree's two children.

    In a rough fanout-100 model, successive levels reach 100, 10,000 and 1,000,000 entries. Growing beyond one level's capacity means adding a level, not reading every extra key. Equal root-to-leaf path lengths keep the search tree balanced.

  6. 6
    ExampleFind the beginning of a date range

    Now the service asks for loans due from April 1 up to, but not including, April 8. A B-tree on due_at orders the dates.

    The engine first descends to the first entry at or after April 1. In PostgreSQL's linked-leaf structure, it can then continue along the leaves. It has found the starting position once; it does not restart from the root for every later entry in the week.

  7. 7
    ExampleStop at the upper boundary

    Continue through the ordered date entries while due_at < '2026-04-08'. Stop as soon as the next key is outside the interval. Fetch the referenced loan rows when the query needs their other columns.

    A wider interval means more index entries and table rows to read, even though the initial descent is unchanged. Ordered continuation explains both the advantage of a narrow range and the rising cost of a broad one.

  8. 8
    ChallengeExpose the stored date key

    In MySQL, a B-tree indexes the timestamp returned_at, but a query uses YEAR(returned_at) = 2024. Rewrite the condition so the plain timestamp key can guide a search and timestamps throughout December 31 remain included.

    ---reveal---

    Use returned_at >= '2024-01-01' AND returned_at < '2025-01-01'. The half-open interval searches stored timestamps directly and includes every time before the next year begins.

  9. 9
    ExplanationRoute an exact token to a bucket

    A login lookup has a different need: find the row for one complete session token. A hash index hashes that value and goes to its bucket.

    The engine must still compare the candidate token values. Unequal values can share a hash result, so arriving in the right bucket does not establish equality. Hashing makes the candidate set small on average, without arranging tokens in their original order.

  10. 10
    ConnectionCheck the system before choosing hash

    PostgreSQL offers an explicit single-column USING HASH index. It cannot enforce uniqueness there. InnoDB user-defined indexes are B-tree; MySQL MEMORY tables default to hash and also offer B-tree. SQLite has no hash-index type.

    This affects the design before any timing comparison: the required index must be supported by the engine and must provide the query's required operations. B-tree remains a general-purpose equality option too.

  11. 11
    ChallengeKeep the useful ordering

    A PostgreSQL table is searched both by an exact URL and by URL prefixes. A proposal replaces its B-tree with a hash index because URLs are long. What capability would the replacement lose?

    ---reveal---

    It would lose ordered prefix-range access. Hash results do not preserve the URL text order, so a prefix cannot identify a bounded run. Compact hash entries may help equality, but they do not satisfy the second search requirement.

  12. 12
    ChallengeChoose for the whole request

    The library's main query finds one reader's loans in a date interval and returns them in date order. A designer proposes hashing just the date, then sorting every matching result. Why is an ordered B-tree a better starting candidate for the date-range part?

    ---reveal---

    A B-tree can bound the interval and traverse the matching dates in order. Hashing the date cannot perform that range search or supply date order. The remaining reader condition still needs its own place in the overall index design.

  13. 13
    RecapTrace the work before choosing the structure

    For a proposed index, follow the route: find candidate entries, reach any needed table rows, and check whether the key order serves the request. Use page work to compare a lookup with a scan. Use the required operations to decide whether hash or B-tree belongs in the comparison.

2

Read a plan and locate repeated work

14 steps
Move from access paths to join inputs, row estimates and measured loop totals.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow rows through the plan
  2. 2
    ExplanationRead children before parents
  3. 3
    ExampleDistinguish a search from a later filter
  4. 4
    ChallengeRead the SQLite change
  5. 5
    ExplanationRecognize the scan trade-offs
  6. 6
    ExampleSet up the join inputs
  7. 7
    ChallengeRecognize costly repetition
  8. 8
    ExplanationKeep estimates in their own units
  9. 9
    ExampleScale the actual figures by loops
  10. 10
    ChallengeCompare rows on the same basis
  11. 11
    ConnectionFind the work added by a parent
  12. 12
    TipCompare cache conditions as well as time
  13. 13
    ChallengeChoose one testable diagnosis
  14. 14
    RecapConnect row flow to the expensive step
3

Estimate matches and explain the scan choice

12 steps
Work through frequency estimates, dependencies and searchable conditions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionPredict how much of the table is needed
  2. 2
    ExampleTranslate a uniform equality estimate
  3. 3
    ExampleReplace the uniform guess with frequency
  4. 4
    ExampleAllocate only the remaining non-NULL rows
  5. 5
    ExplanationRead a fraction of a histogram bucket
  6. 6
    ChallengeNotice the dependent condition
  7. 7
    ExplanationTurn matches into page work
  8. 8
    ExampleMake a numeric condition searchable
  9. 9
    ChallengeSeparate availability from usefulness
  10. 10
    TipKeep identities when splitting OR
  11. 11
    ChallengeChoose the first repair
  12. 12
    RecapExplain the choice with data and access
4

Build an ordered path and add useful payload

12 steps
Trace composite entries for a customer history and check whether the index covers its output.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDesign for a concrete query
  2. 2
    ExampleGroup by device, then by time
  3. 3
    ExampleUse the fixed prefix for descending time
  4. 4
    ChallengeServe a second prefix query
  5. 5
    Key InsightTreat skip scans as repeated searches
  6. 6
    ChallengeReverse every key direction
  7. 7
    ExplanationCheck every required column
  8. 8
    ExampleAdd reading as payload
  9. 9
    ChallengeRead the remaining heap work
  10. 10
    ConnectionCompare another engine's stored values
  11. 11
    ChallengeBalance two real search needs
  12. 12
    RecapKeep search order and coverage distinct
5

Choose a small index set for a busy service

13 steps
Turn query rates and write costs into candidates, then test what deserves to stay.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart from the work the service receives
  2. 2
    ExampleCount the maintained structures
  3. 3
    ExplanationInclude changes after insertion
  4. 4
    ChallengeDo not mistake zero scans for zero value
  5. 5
    ExampleList the workload before the keys
  6. 6
    ExampleChoose the history path
  7. 7
    ExampleKeep a small waiting subset
  8. 8
    ChallengeTest the predicate against another query
  9. 9
    Key InsightMerge prefixes with a reason
  10. 10
    TipPlan how the index will be built
  11. 11
    ExampleMeasure the proposed set
  12. 12
    ChallengeDecide whether to add the report index
  13. 13
    RecapKeep evidence for each index that stays

Indexes and Query Performance practice questions

40 Practice Questions in 4 sets

Set 1: Find rows and read the access path10 Practice Questions

Question 1 of 10

A table contains 720,000 rows with 120 rows per page. How many table pages does a full scan visit?
  1. 600 pages
  2. 60,000 pages
  3. 6,000 pages
  4. 720,000 pages
Show answerHide answer
Answer: C
Divide 720,000 rows by 120 rows per page to get 6,000 table pages. A full scan visits the entire table even if its filter returns very few rows. Counting 720,000 pages treats each row as a page and ignores that 120 rows share each page.

Question 2 of 10

An ordinary B-tree indexes recorded_at. What feature lets it find all entries in a narrow time interval efficiently?
  1. Its keys are stored in sorted order.
  2. Its keys are grouped into hash buckets.
  3. Its entries hold every table column.
  4. Each page has two child pointers.
Show answerHide answer
Answer: A
Sorted keys place an interval in an ordered run, so the engine can find its beginning and stop at its end. A hash bucket supports exact-key routing but does not preserve time order. The B-tree does not have to store every table column to search the interval.

Question 3 of 10

A PostgreSQL service looks up long API tokens by equality and must reject duplicate token values. What index type can provide both lookup and uniqueness?
  1. A unique hash index on the token.
  2. A non-unique hash index on the token.
  3. A B-tree index on the token length.
  4. A unique B-tree index on the token.
Show answerHide answer
Answer: D
A unique B-tree supports exact-token lookup and rejects duplicate tokens. PostgreSQL hash indexes cannot be declared unique, even when the workload uses only equality and the values are long. Indexing token length would not enforce uniqueness of the original token values.

Question 4 of 10

MySQL lists two names under possible_keys and one name under key. Where do you find the index selected for this table access?
  1. In the possible_keys field.
  2. In the key field.
  3. In the rows field.
  4. In the Extra field.
Show answerHide answer
Answer: B
The key field names the index MySQL selected for that access. possible_keys lists candidates the optimizer considered, so an index appearing there may still be unused. rows estimates examined rows, while Extra adds details about operations such as filtering or sorting.

Question 5 of 10

After an index is added, SELECT id FROM tickets LIMIT 6 returns a different six IDs. What query change makes the six smallest IDs the required result?
  1. Add a non-unique index on ticket status.
  2. Add ORDER BY id when id is unique.
  3. Keep the query and refresh its statistics.
  4. Keep the query and force the new index.
Show answerHide answer
Answer: B
A unique ascending ORDER BY id makes the first six rows the six smallest IDs. Without ordering, LIMIT only caps the output count, so a changed access path may produce a different valid subset. Refreshing statistics can change the plan again but does not define the desired subset.

Question 6 of 10

A PostgreSQL plan shows Index Cond: (account_id = 73) and Filter: (state = 'open'). How does this access step use the two conditions?
  1. It searches open rows, then filters its candidate rows by account.
  2. It combines two index searches, then intersects their row locations.
  3. It reads all table rows, then searches an index for the open ones.
  4. It searches account 73, then filters its candidate rows by state.
Show answerHide answer
Answer: D
The index condition guides the search to account 73; the filter then rejects candidates whose state is not open. A displayed filter is not evidence of a second index search. The account lookup can reduce access work even though the state condition is checked afterward.

Question 7 of 10

SQLite reports USE TEMP B-TREE FOR ORDER BY after a table search. What extra work is the query performing?
  1. Ordering the fetched rows separately.
  2. Building a permanent index for later queries.
  3. Enforcing a unique constraint on the result.
  4. Combining two persistent hash indexes.
Show answerHide answer
Answer: A
The temporary B-tree supplies the requested ordering because the chosen access path does not supply it directly. It belongs to this execution and is not a permanent index added to the table. A compatible persistent index might avoid this work on a later execution.

Question 8 of 10

A PostgreSQL inner step reports actual time=0.010..0.030 rows=4 loops=150. What total output and approximate inclusive time does this represent across its executions?
  1. 4 rows and 0.030 ms.
  2. 600 rows and 6.0 ms.
  3. 600 rows and 4.5 ms.
  4. 150 rows and 4.5 ms.
Show answerHide answer
Answer: C
The displayed rows and times are averages per execution, so 150 runs produce about 600 rows and take about 4.5 ms in total. Adding startup time to total time would give 6.0 ms, but total already includes startup. These figures describe this step's inclusive work, not an additional amount to add to every parent.

Question 9 of 10

In a serial PostgreSQL plan, a Nested Loop runs once and takes 92 ms. Its outer child runs once and takes 12 ms; its inner child takes 0.35 ms per run with 200 loops. The inner child's actual rows greatly exceed its estimate, while the outer estimate is close. Where should the first investigation focus?
  1. The repeated inner access and its row estimate.
  2. The outer scan and its small row-estimate error.
  3. The loop parent's added work beyond its child operations.
  4. The outer scan, since every inner lookup depends on it.
Show answerHide answer
Answer: A
The inner access accounts for about 70 ms across 200 runs, compared with 12 ms on the outer side. Its large estimate error is also a concrete clue to why this repeated work was chosen. The parent's 92 ms includes its children, so adding the displayed times would double-count them.

Question 10 of 10

A MySQL table has a timestamp column sent_at and a B-tree on it. A slow query filters with YEAR(sent_at) = 2025, orders by sent_at DESC and returns 15 rows. What first change addresses both the searchable filter and the opportunity to stop early?
  1. sent_at >= '2025-01-01' AND sent_at <= '2025-12-31', with descending order and the limit.
  2. sent_at >= '2025-01-01' AND sent_at < '2026-01-01', with descending order and the limit.
  3. sent_at >= '2025-01-01' AND sent_at <= '2026-01-01', with descending order and the limit.
  4. sent_at >= '2025-01-01' AND sent_at < '2026-01-01', with the ordering removed and the limit kept.
Show answerHide answer
Answer: B
The half-open range searches the bare timestamp key, includes all of 2025 and excludes the start of 2026. Keeping descending order lets the B-tree stop at the latest 15 matching entries. An inclusive upper bound of December 31 omits later times on that date, while including January 1 admits a timestamp from the next year.
Set 2: Estimate matches and diagnose index choices10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A filter matches 2,400 of 600,000 rows. What is its selectivity as a percentage?
  1. 4%
  2. 0.04%
  3. 25%
  4. 0.4%
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An optimizer uses equal frequencies for 30,000 distinct non-NULL member IDs in a 900,000-row table. How many rows does it estimate for one member ID?
  1. 3 rows
  2. 30 rows
  3. 300 rows
  4. 30,000 rows
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A table has 80 rows on two pages. Its filter has a suitable index, but the optimizer chooses a full scan. What is the most likely cost-based explanation?
  1. Reading two pages can cost less than index navigation and row fetches.
  2. The presence of a filter disables indexes on every table this small.
  3. An index can become useful only after the table has a million rows.
  4. A full scan means the index has stopped receiving inserted entries.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A column has 60 distinct non-NULL values. Its four MCVs account for 62% of all rows, and NULLs account for 10%. PostgreSQL spreads the remainder evenly. What fraction is estimated for one non-NULL value outside the MCV list?
  1. 0.633%
  2. 7%
  3. 0.5%
  4. 0.467%
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An equal-frequency histogram has 50 buckets. A range includes three whole buckets and one quarter of the next, with an even spread inside that bucket. How many of 800,000 rows are estimated to match?
  1. 48,000 rows
  2. 64,000 rows
  3. 52,000 rows
  4. 13,000 rows
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A PostgreSQL B-tree indexes score. The column has exact numeric values. How can WHERE score + 18 >= 90 be rewritten to expose a direct search on that key?
  1. WHERE score >= 72
  2. WHERE score >= 108
  3. WHERE score - 18 >= 90
  4. WHERE ABS(score) >= 72
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A PostgreSQL plan's parent has estimated total cost 850 and its only child has total cost 790. What can you infer about the parent's total cost?
  1. It excludes the child cost; their combined cost is 1,640 ms.
  2. It includes the child cost; the runtime must be exactly 850 ms.
  3. It excludes the child cost; 60 is the cost of the entire query.
  4. It includes the child cost; 850 is not a millisecond prediction.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A 500,000-row table has 6% of rows with city = 'Oslo' and 10% with country = 'Norway'. Every Oslo row is a Norway row. An estimate multiplies the two fractions. By what factor does it underestimate the conjunction, and what kind of statistics could address the cause in PostgreSQL?
  1. 100-fold; statistics describing cross-column dependencies.
  2. 10-fold; statistics describing cross-column dependencies.
  3. 10-fold; more distinct-value detail for city alone.
  4. 6-fold; more equal-frequency buckets for country alone.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A query returns label from parcels, whose primary key is id, where depot_id = 91 OR tracking_code = 'T82'. Both columns are indexed, but different parcels may share a label. How can the query be split with UNION while preserving one output row per matching parcel, including repeated labels?
  1. Union each branch's id, label, then select label from that result.
  2. Union each branch's label, then select label from that result.
  3. Union all each branch's id, label, then select label from that result.
  4. Union all each branch's label, then select label from that result.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two serial plans return the same result. Plan X performs 400 indexed inner lookups, averaging 0.20 ms each. Plan Y scans the inner table once in 55 ms. Their other work is measured at 10 ms each. Under these measurements, what conclusion is supported?
  1. Plan X is faster by about 55 ms because its inner access is indexed.
  2. Plan Y is faster by about 80 ms because its inner scan runs once.
  3. Plan X is faster by about 25 ms because its average lookup is short.
  4. Plan Y is faster by about 25 ms despite scanning the inner table.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Design keys for filters, order and output10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A B-tree indexes (department_id, hired_at). What condition directly searches its one-column leftmost prefix?
  1. WHERE hired_at >= '2025-08-01'
  2. WHERE department_id = 12
  3. WHERE LOWER(job_title) = 'analyst'
  4. WHERE salary >= 60000
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

SQLite has an index on loans (borrower_id, due_date). What change to SELECT due_date FROM loans WHERE borrower_id = 18 makes that index stop covering the query?
  1. Add ORDER BY due_date to the existing query.
  2. Change the borrower equality value from 18 to 27.
  3. Add a range condition on the indexed due_date column.
  4. Add an unindexed returned_at column to the select list.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A frequent query uses WHERE team_id = ? AND opened_at >= ?. What two-column B-tree order gives a direct contiguous search for one team's time range?
  1. (team_id, opened_at)
  2. (opened_at, team_id)
  3. (opened_at, closed_at)
  4. (closed_at, team_id)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

PostgreSQL has CREATE UNIQUE INDEX ux_assets_code ON assets (code) INCLUDE (description);. What happens when two inserted rows share code 'AX7' but have different descriptions?
  1. Both rows are accepted because the descriptions differ.
  2. The second row replaces the first description automatically.
  3. The second row is rejected for its duplicate code.
  4. Both rows are accepted if an index-only scan is possible.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A new table will receive 300,000 rows. It has a primary-key index and three full secondary indexes. How many index-entry insertions does the load require if all four indexes are maintained row by row?
  1. 900,000 insertions
  2. 1,500,000 insertions
  3. 300,000 insertions
  4. 1,200,000 insertions
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A service needs both WHERE workspace_id = ? AND stage = ? ORDER BY created_at DESC LIMIT 8 and WHERE workspace_id = ? ORDER BY created_at DESC LIMIT 8. Stages have several values within each workspace. What single B-tree gives the second query a directly ordered path while retaining indexed filtering for the first?
  1. (workspace_id, stage, created_at)
  2. (workspace_id, created_at, stage)
  3. (stage, workspace_id, created_at)
  4. (created_at, stage, workspace_id)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two frequent queries filter shipments by (hub_id, shipped_at range) and by shipped_at range alone. There are 70,000 hubs. A proposed design keeps only (hub_id, shipped_at). What issue should the review identify?
  1. The date-only query lacks a direct prefix; many hub groups make skip scans costly.
  2. The hub-and-date query lacks a direct prefix; the range must precede hub equality.
  3. The date-only query is directly ordered by date across all hub groups already.
  4. The hub-and-date query requires two separate indexes to intersect its conditions.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A PostgreSQL archive query selects logged_at, reading for one device_id, ordered by time. An index on (device_id, logged_at) INCLUDE (reading) yields an Index Only Scan, but almost every output row has a heap fetch. The archive pages were recently rewritten. What diagnosis fits, and what trade remains?
  1. Visibility checks still visit heap pages; adding more output payload removes those checks.
  2. Missing output values force heap access; visibility-map coverage does not explain the fetches.
  3. Visibility checks still visit heap pages; the payload still costs storage and write work.
  4. Visibility checks still visit heap pages; changing included payload never adds index work.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A query orders all rows by region_id ASC, priority DESC, created_at DESC. What B-tree order can provide that entire ordering through a backward scan?
  1. (region_id ASC, priority ASC, created_at ASC)
  2. (region_id DESC, priority ASC, created_at ASC)
  3. (region_id DESC, priority DESC, created_at ASC)
  4. (region_id ASC, priority DESC, created_at DESC)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

In PostgreSQL, 0.8% of 1,500,000 support cases are open. A frequent query selects created_at, owner_id for open cases before a date, orders by created_at and limits output to 30. What candidate supplies its time order and selected values while indexing only open cases?
  1. Key (created_at) with INCLUDE (owner_id) and WHERE state = 'open'.
  2. Key (owner_id, created_at) with INCLUDE (state) and WHERE state = 'open'.
  3. Key (created_at) with INCLUDE (state) and WHERE state = 'open'.
  4. Key (created_at) with INCLUDE (owner_id) and WHERE state <> 'open'.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Choose and verify an index set10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A unique index has zero recorded query scans. What continuing job can justify keeping it?
  1. Keeping the whole table sorted by every column.
  2. Refreshing all column statistics automatically.
  3. Rejecting duplicate key values on writes.
  4. Making every update skip index maintenance.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A PostgreSQL child table joins frequently through invoice_items.invoice_id. That column is a foreign key, but has no index. What candidate supports both the join lookup and searches when a referenced invoice changes?
  1. An index beginning with invoice_items.invoice_id.
  2. An index beginning with invoice_items.quantity.
  3. A second unique index on the parent invoice primary key.
  4. A partial index containing no rows with an invoice ID.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

InnoDB stores id as the primary key of bookings and has a secondary index on guest_id. Can SELECT id FROM bookings WHERE guest_id = 44 obtain its required values from that secondary index?
  1. No, every selected column must be listed in INCLUDE.
  2. No, a secondary index never stores a primary-key value.
  3. Yes, because secondary entries contain every table column.
  4. Yes, its entries also carry the primary-key value.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A PostgreSQL table has B-tree indexes only on id and email. An update changes only notes, and its original heap page has enough room for the new row version. What index-maintenance optimization is possible?
  1. A HOT update must rebuild both B-tree indexes.
  2. A HOT update can avoid new index entries.
  3. A hash join can avoid writing the updated row.
  4. A concurrent build can remove the primary-key index.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PostgreSQL events table receives heavy inserts. Q1 frequently uses WHERE source_id = ? ORDER BY event_time DESC LIMIT 12; Q2 rarely uses WHERE source_id = ?. Existing non-unique indexes are (source_id) and (source_id, event_time), and neither enforces a constraint. What first consolidation should be tested?
  1. Keep the source-only and test removing the composite index.
  2. Keep both and add a separate descending-time index for Q1.
  3. Replace both with (event_time, source_id) for both queries.
  4. Keep the composite and test removing the source-only index.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A PostgreSQL queue has an index on queued_at WHERE state = 'ready'. One worker query uses state = 'ready' AND queued_at < ?; a dashboard uses state IN ('ready', 'running') AND queued_at < ?. What coverage problem prevents this one partial index from answering the dashboard's full filter?
  1. The index omits ready rows whenever a date cutoff is added.
  2. The index omits running rows that the dashboard must include.
  3. The dashboard has two state values, so it must use a hash index.
  4. The dashboard can use this index alone because ready is in its list.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A query is measured once before an index is added: 160 ms with many shared reads. Its first measured run afterward takes 24 ms with almost all shared hits. The access path changed from Seq Scan to Index Scan. What comparison is still needed to establish the timing benefit under comparable conditions?
  1. Repeat both designs with comparable cache states and compare pages, rows and times.
  2. Convert both planner total costs into milliseconds and compare those values alone.
  3. Accept the ratio of the two single runs because the plan now names an index.
  4. Add the before and after step times to remove the effect of cached pages.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

After an import, a serial PostgreSQL Nested Loop still estimates 25 outer rows and 2 inner rows per lookup. Actual output is 4,000 outer rows and 15 inner rows per lookup. By what factor does actual join output exceed that estimate, and what evidence should be checked before adding another index?
  1. 160-fold; refreshed statistics and dependencies behind the row estimates.
  2. 7.5-fold; refreshed statistics and dependencies behind the row estimates.
  3. 1,200-fold; refreshed statistics and dependencies behind the row estimates.
  4. 1,200-fold; whether every output column has its own single-column index.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A PostgreSQL application frequently filters by client_id and orders by issued_at, and also filters by client_id plus payment_state. Candidates are (client_id, issued_at) and (client_id, payment_state). A proposal merges them into (client_id, issued_at, payment_state). What should be verified before accepting that replacement?
  1. Whether the two original indexes have identical entries because their prefixes match.
  2. Whether the trailing state key becomes the direct second-column search boundary.
  3. Whether scanning the client time-ordered run filters payment state fast enough.
  4. Whether including a third key removes all maintenance costs for state changes.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A large telemetry table receives 40,000 inserts per minute. A dashboard query runs 8,000 times per hour and misses its latency target; a daily report scans most rows and already meets its target. One proposed index speeds the dashboard but slows inserts; another covers the daily report and also slows inserts. What is the strongest next design test?
  1. Test the report covering index first, weighing its daily saving against slower inserts.
  2. Test the dashboard index against its latency target and required insert throughput.
  3. Build both candidates and compare only the dashboard read latency.
  4. Choose the lowest-cost dashboard plan using a small development table.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

67 Key Terms, each with its definition

A

Access method
An access method is the route used to obtain rows, such as a full table scan, a bounded index scan or an indexed key lookup.
MySQL reports a chosen access method in its type field, separately from the name of its selected index.
Aggregate
An aggregate computes a result over input rows, either as one overall result or as separate results for groups of equal keys.
An aggregate can sum order totals after a date scan has selected the rows belonging to the requested month.

B

B-tree
A B-tree is a balanced, ordered search tree with many children per internal node, supporting shallow lookups and ordered range scans.
A B-tree on a timestamp can find the first reading in an interval and continue through the interval in order.
B+-tree
A B+-tree is a B-tree variant with all data entries in linked leaves and internal separator keys that guide searches to those leaves.
PostgreSQL and InnoDB use B+-tree indexes whose leaf links support continuation through neighboring keys.
Backward scan
A backward scan traverses ordered index entries in reverse, reversing every key direction together while preserving the key hierarchy.
A backward scan of one customer's ascending date entries can return that customer's latest orders first.
Bitmap scan
A bitmap scan collects matching row locations from indexes, then visits the required table pages in physical order to reduce scattered fetches.
A bitmap scan can combine status matches and customer matches before accessing the necessary heap pages.
Bucket
A bucket is a location selected by a hash result where the index searches candidate entries before verifying their original key values.
A token lookup can check several entries in one bucket when different token values have collided.
Buffer cache
A buffer cache is database-managed memory holding data pages so later access can avoid bringing those pages in from outside that cache.
PostgreSQL counts a page already in its buffer cache as a shared hit during a measured query.

C

Cardinality
A column's cardinality is its distinct-value count; in plan analysis the same word can instead refer to a step's output row count.
A status column has low cardinality even though the table may contain millions of orders.
Clustering index
A clustering index stores the table rows in its key order, making that index the table's physical organization of row data.
InnoDB stores an order's full row in the clustering index identified by that table's primary key.
Collision
A collision occurs when different key values produce the same hash result, requiring a value check to distinguish genuine matches.
A collision between two tokens must not cause a lookup for one token to return the other token's row.
Composite index
A composite index has several key columns in a defined order, sorting each later column within equal values of its preceding keys.
A composite index on customer and date supports a single customer's history in chronological order.
Concurrent index build
A concurrent index build creates a PostgreSQL index while allowing writes, using extra work and running outside a transaction block.
A concurrent index build can help add an access path while new orders continue to arrive at the table.
Correlation
Correlation in PostgreSQL statistics describes how closely a column's logical value order follows the physical order of table rows.
High correlation for insertion dates can place a month's order rows together on neighboring table pages.
Covering access
Covering access retrieves every column a query needs from its index entries, reducing or avoiding the need to fetch wider table rows.
Covering access can help count a common status even though the filter keeps a large fraction of the table.
Covering index
A covering index contains every column used by a particular query, including columns needed for its output, conditions, joins and order.
An index can be a covering index for selecting dates but lose that role when the query also selects an absent total.

E

Estimated rows
The estimated rows figure in a PostgreSQL plan predicts output rows from a step, which can be fewer than the rows it examines.
A sequential scan can have ten estimated rows while still checking a table containing a million rows.
EXPLAIN
EXPLAIN is a PostgreSQL and MySQL command that displays a planned execution strategy and its estimates without executing the query.
Running EXPLAIN before a SELECT reveals whether the chosen access path scans a table or searches an index.
EXPLAIN ANALYZE
EXPLAIN ANALYZE executes a statement and reports its plan with measured timings and row counts alongside the optimizer's estimates.
An EXPLAIN ANALYZE result can show that an inner lookup returned far more rows than its estimate predicted.
Expression index
An expression index stores the result of an expression as its key, allowing searches that use the matching expression directly.
An expression index on LOWER(email) supports a lowercase email lookup without converting every row during the search.

F

Fanout
The fanout of an internal tree node is its number of children; a large fanout lets a small number of levels reach many keys.
With a rough fanout of 200, adding one level increases the tree's entry capacity by about a factor of 200.
Filter
A filter is a condition checked against candidates after an access step obtains them, reducing output without necessarily reducing pages read.
A sequential scan's filter can return ten rows after the scan has checked all rows in the table.
Foreign-key index
A foreign-key index is an index on a child table's referencing columns that supports joins and searches for rows affected by parent changes.
A foreign-key index on orders.customer_id helps locate orders before a referenced customer is deleted.
Full table scan
A full table scan reads every row of a table, applying any filter as it goes, even if only a few rows eventually qualify.
A full table scan of a large shipment table may check millions of rows to find three matching shipments.

H

Hash function
A hash function maps a key value to a hash result used to choose candidate storage locations; different keys can share that result.
The hash function sends a searched session token to a bucket before the engine verifies candidate values.
Hash index
A hash index routes exact key values to buckets using hash results, supporting equality lookups without preserving the keys' order.
A hash index can find an exact token, but a timestamp range needs an ordered access path or a scan.
Hash Join
A Hash Join builds a temporary hash table from one input and probes it with the other, without requiring a persistent hash index.
A Hash Join may read the orders table once and match its rows against a temporary customer hash table.
Heap
A heap is PostgreSQL's table row-storage area, which does not keep rows continuously sorted according to an index key.
A customer index can place matching keys together even when their referenced rows are spread through the heap.
Heap fetch
A heap fetch is a table-row visit reported by a PostgreSQL index-only scan when visibility cannot be established from its visibility map.
Many heap fetches can limit the benefit of a covering index on a table whose rows change constantly.
Histogram
A histogram summarizes the spread of ordered column values across buckets, allowing the optimizer to estimate the fraction inside a range.
An equal-frequency histogram can estimate a date cutoff using complete buckets and a fraction of the next.
HOT update
A HOT update is a PostgreSQL shortcut avoiding ordinary index updates when indexed values stay unchanged and the original heap page has room.
Changing only notes can allow a HOT update if notes are unindexed and the new version fits on the same page.

I

Included column
An included column is non-key index payload available for query output without guiding searches or extending the key's uniqueness rule.
A total stored as an included column can cover customer-history output while leaving customer-date key order intact.
Independence
Independence means one condition does not change the matching fraction of another, allowing their fractions to be multiplied for an AND estimate.
Assuming independence for city and country can underestimate matches when every city row has the same country.
Index
An index is an organized structure of table key values with row references that can speed matching searches, joins or ordered access.
An index on orders.customer_id lets a customer-history query locate matching orders without checking every row.
Index condition
An index condition is a predicate used to guide index access; PostgreSQL labels it Index Cond when showing that search in a plan.
The index condition customer_id = 42 narrows access before a separate state filter rejects candidates.
Index hint
An index hint is an instruction that restricts the optimizer's index choice, potentially preserving an access path after the data changes.
MySQL's FORCE INDEX is an index hint that can become costly if the matching value later grows common.
Index key
An index key is the column or ordered group of columns whose values organize entries and guide searches within an index.
The index key (customer_id, order_date) groups one customer's entries together and orders their dates.
Index maintenance
Index maintenance is the write work that keeps index entries and membership consistent as rows are inserted, changed or deleted.
Index maintenance rises when a table adds several secondary indexes that all receive new entries on inserts.
Index predicate
An index predicate is the row condition defining membership in a partial index; an eligible query must imply that condition.
The index predicate status = 'pending' excludes rows needed by a query for pending or shipped orders.
Index scan
An index scan searches index entries and follows their references to fetch required table rows, which may lie on scattered pages.
An index scan for a rare customer can fetch a few rows while avoiding a complete read of the orders table.
Index-only scan
An index-only scan obtains needed column values from an index; PostgreSQL can still visit table rows to verify their visibility.
An index-only scan on a stable archive may report zero heap fetches when its pages are all-visible.

L

Leaf
A leaf is a tree node without child nodes; in a B+-tree index it stores key entries with references to their corresponding rows.
After choosing branches by separator keys, a customer lookup reaches a leaf holding the matching entries.
Leftmost prefix
A leftmost prefix is the leading consecutive portion of a composite key, which can directly bound a search without specifying later columns.
The leftmost prefix customer_id of (customer_id, order_date) supports customer-only lookups.
Loops
The loops figure counts a plan step's executions; PostgreSQL actual rows and times are per-execution averages when it repeats.
Multiplying three actual rows by 200 loops gives about 600 rows returned across those executions.

M

Merge Join
A Merge Join walks two inputs ordered on their join keys, combining matching keys as it advances through both ordered streams.
A Merge Join can receive sorted inputs from suitable indexes instead of sorting each input explicitly.
Most common values list
A most common values list records frequent column values and their observed frequencies, helping equality estimates account for skew.
A most common values list can show that delivered orders are much more frequent than cancelled orders.

N

Nested Loop
A Nested Loop is a join method that takes each outer-input row in turn and searches the inner input for its matching rows.
A Nested Loop over 200 customers can use 200 indexed searches to retrieve their orders efficiently.

P

Page
A page is a fixed-size block in which a database reads and writes data; one page commonly contains several table rows or index entries.
A query finding nearby rows may reuse one page, while scattered matches can require many page visits.
Page split
A page split redistributes entries into an additional B-tree page when an existing page cannot fit new entries, adding maintenance work.
An insert into a full leaf can trigger a page split and require changes to the tree's separator structure.
Partial index
A partial index stores entries only for rows satisfying a predicate, making a focused subset smaller to search and maintain.
A partial index on pending order dates can search overdue pending work without storing delivered orders.
Plan node
A plan node is one operation in an execution-plan tree, consuming any child inputs and passing its output rows to a parent.
A sort plan node takes the rows produced by its scan child and passes ordered rows upward.

Q

Query optimizer
A query optimizer chooses an execution plan by estimating the work of alternative access paths, join orders and processing methods.
The query optimizer can choose a scan for a common status and a lookup for a rare status in the same column.
Query plan
A query plan is a tree of execution steps that shows how a database will read, combine, filter, group or order a query's rows.
A query plan can reveal a large sort above a customer lookup even when the lookup itself is fast.

R

Range scan
A range scan finds a starting key in an ordered index and traverses entries until it reaches the boundary of the requested interval.
A range scan for one week of readings stops when it reaches the first timestamp beyond the week.
Redundant index
A redundant index adds little useful access beyond another index for the workload, making its storage and maintenance costs candidates for removal.
A customer-only index may be redundant beside a customer-date index that already serves customer lookups.

S

Sargable condition
A sargable condition can directly guide a search on an indexed column or matching indexed expression, giving the optimizer a usable search argument.
The sargable condition total > 80 exposes the stored total key after an arithmetic filter is rearranged.
Secondary index
A secondary index is stored separately from the table's row storage and carries references that let the database reach those rows.
An InnoDB secondary index on a customer ID carries the primary key needed to find each full order row.
Selectivity
The selectivity of a condition is the fraction of table rows satisfying it; a highly selective condition keeps a small fraction.
A selectivity of 0.01 means about 20,000 matches in a table containing 2,000,000 rows.
Skip scan
A skip scan performs separate searches through leading-key value groups, allowing some indexed searches that omit a leading key condition.
A skip scan can be useful with a few status groups but costly with tens of thousands of customer groups.
Slow query log
A slow query log is a record of queries meeting configured runtime criteria, helping identify expensive operations for workload investigation.
MySQL's slow query log can reveal a recurring report that deserves plan analysis before another index is added.
Sort
A sort arranges input rows by specified keys; it is a separate query step when the chosen access path does not supply the required order.
A sort before a small LIMIT can process far more rows than a matching ordered index scan would need.
Startup cost
The startup cost is a planner estimate of work before a step produces its first output row, expressed in cost units rather than time.
A large sort has a high startup cost because it must consume its input before returning ordered rows.
Statistics
Statistics are sampled summaries of table sizes and value distributions that the optimizer uses to estimate row counts and access costs.
After a large import changes status frequencies, refreshed statistics can change the chosen scan method.

T

Total cost
The total cost is a planner estimate of work to produce all output from a step, including startup work and the costs of its children.
A parent's total cost already includes its scan child, so adding the two displayed costs counts work twice.

U

Unused-index statistics
Unused-index statistics record observed index activity over a measurement period, identifying possible removals without judging constraint value.
Unused-index statistics collected for one day can miss an index that serves an important monthly report.

V

Visibility map
A visibility map records which PostgreSQL heap pages are all-visible, allowing index-only scans to skip visibility checks in those pages.
A recently changed archive page can lose its all-visible mark in the visibility map and need heap access.

W

Workload
A workload is a database's mix of queries and writes, including their frequencies and the response-time or throughput needs they must meet.
A workload with frequent customer histories and heavy inserts favors a small set of well-matched indexes.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started