- Learn
- Computer Science & IT
- Programming
- Database Design and Advanced SQL
- Indexes and Query Performance
Indexes and Query Performance
IntermediateLesson 5 of 8 in Database Design and Advanced SQL Course
What you will learn
- 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 lookupExplain 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 rowsDescribe 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 lookupsExplain how a hash index locates rows, what it cannot do, where it is available, and when it is worth choosing over a B-tree.
- Compare a full table scan with an index lookup
- 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 structureExplain 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 stepsName 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 ANALYZERead the estimated cost, row and width figures, compare them with measured times and row counts, and take measurements safely.
- Ask for a query plan and read its structure
- 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 cardinalityDefine 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 indexUse selectivity, table size and the form of a condition to predict whether an index is used, and rewrite conditions so that it can be.
- Estimate selectivity and cardinality
- 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 indexExplain 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 queriesRecognize when an index covers a query, read the signs in a plan, add included columns, and weigh the extra size.
- Order the columns of a composite index
- 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 storageExplain 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 workloadStart from the important queries and writes, propose and merge candidate indexes, use partial indexes where they fit, and check the result with query plans.
- Weigh the cost of indexes on writes and storage
Indexes and Query Performance study guide
1Explain 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 need | What the ordered keys provide |
|---|---|
Equality or an IN list | One key or several key searches |
<, >= or BETWEEN | A bounded or open-ended run of keys |
IS NULL | The portion containing NULL keys |
ORDER BY order_date DESC LIMIT 10 | A 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
| Need | B-tree | Hash index |
|---|---|---|
| Exact equality | Supported | Supported |
| Date range | Ordered keys bound the scan | Hash locations do not bound the range |
| Prefix text search | A suitable prefix range can help | Prefixes do not identify buckets |
| Sorted output or minimum | Key order can supply it | Key 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.
2Read 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.
type | Access meaning |
|---|---|
ALL | Full table scan |
index | Full index scan |
range | Part of an index |
ref | Matches through a non-unique lookup |
eq_ref or const | At 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 step | How it consumes rows | A useful setting |
|---|---|---|
| Nested Loop | Looks for inner matches for each outer row | Few outer rows and an indexed inner key |
| Hash Join | Builds a hash table from one input and probes it with the other | Large unsorted inputs |
| Merge Join | Walks two inputs sorted by their join keys | Ordered 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:
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.
3Judge 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
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:
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.
4Design 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 order | Ordinary 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.
5Choose 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.
- 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. - 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. - A daily monthly-revenue query sums
totalover 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 carryingtotal; 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
1Follow the pages from a search to its rows
13 steps
- 1IntroductionGive 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.
- 2ExampleCount 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.
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.
- 3ExampleFollow 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.
- 4ChallengeSeparate 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 idbeforeLIMIT 5; the unique ID order then determines which rows come first. - 5ExplanationUse 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.
- 6ExampleFind 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_atorders 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.
- 7ExampleStop 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.
- 8ChallengeExpose the stored date key
In MySQL, a B-tree indexes the timestamp
returned_at, but a query usesYEAR(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. - 9ExplanationRoute 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.
- 10ConnectionCheck the system before choosing hash
PostgreSQL offers an explicit single-column
USING HASHindex. 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.
- 11ChallengeKeep 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.
- 12ChallengeChoose 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.
- 13RecapTrace 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.
2Read a plan and locate repeated work
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow rows through the plan
- 2ExplanationRead children before parents
- 3ExampleDistinguish a search from a later filter
- 4ChallengeRead the SQLite change
- 5ExplanationRecognize the scan trade-offs
- 6ExampleSet up the join inputs
- 7ChallengeRecognize costly repetition
- 8ExplanationKeep estimates in their own units
- 9ExampleScale the actual figures by loops
- 10ChallengeCompare rows on the same basis
- 11ConnectionFind the work added by a parent
- 12TipCompare cache conditions as well as time
- 13ChallengeChoose one testable diagnosis
- 14RecapConnect row flow to the expensive step
3Estimate matches and explain the scan choice
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPredict how much of the table is needed
- 2ExampleTranslate a uniform equality estimate
- 3ExampleReplace the uniform guess with frequency
- 4ExampleAllocate only the remaining non-NULL rows
- 5ExplanationRead a fraction of a histogram bucket
- 6ChallengeNotice the dependent condition
- 7ExplanationTurn matches into page work
- 8ExampleMake a numeric condition searchable
- 9ChallengeSeparate availability from usefulness
- 10TipKeep identities when splitting OR
- 11ChallengeChoose the first repair
- 12RecapExplain the choice with data and access
4Build an ordered path and add useful payload
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDesign for a concrete query
- 2ExampleGroup by device, then by time
- 3ExampleUse the fixed prefix for descending time
- 4ChallengeServe a second prefix query
- 5Key InsightTreat skip scans as repeated searches
- 6ChallengeReverse every key direction
- 7ExplanationCheck every required column
- 8ExampleAdd reading as payload
- 9ChallengeRead the remaining heap work
- 10ConnectionCompare another engine's stored values
- 11ChallengeBalance two real search needs
- 12RecapKeep search order and coverage distinct
5Choose a small index set for a busy service
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart from the work the service receives
- 2ExampleCount the maintained structures
- 3ExplanationInclude changes after insertion
- 4ChallengeDo not mistake zero scans for zero value
- 5ExampleList the workload before the keys
- 6ExampleChoose the history path
- 7ExampleKeep a small waiting subset
- 8ChallengeTest the predicate against another query
- 9Key InsightMerge prefixes with a reason
- 10TipPlan how the index will be built
- 11ExampleMeasure the proposed set
- 12ChallengeDecide whether to add the report index
- 13RecapKeep evidence for each index that stays
Indexes and Query Performance practice questions
Set 1: Find rows and read the access path10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
recorded_at. What feature lets it find all entries in a narrow time interval efficiently?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
possible_keys and one name under key. Where do you find the index selected for this table access?Show answerHide answer
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
SELECT id FROM tickets LIMIT 6 returns a different six IDs. What query change makes the six smallest IDs the required result?Show answerHide answer
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
Index Cond: (account_id = 73) and Filter: (state = 'open'). How does this access step use the two conditions?Show answerHide answer
Question 7 of 10
USE TEMP B-TREE FOR ORDER BY after a table search. What extra work is the query performing?Show answerHide answer
Question 8 of 10
actual time=0.010..0.030 rows=4 loops=150. What total output and approximate inclusive time does this represent across its executions?Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
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?Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
score. The column has exact numeric values. How can WHERE score + 18 >= 90 be rewritten to expose a direct search on that key?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
(department_id, hired_at). What condition directly searches its one-column leftmost prefix?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
loans (borrower_id, due_date). What change to SELECT due_date FROM loans WHERE borrower_id = 18 makes that index stop covering the query?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
WHERE team_id = ? AND opened_at >= ?. What two-column B-tree order gives a direct contiguous search for one team's time range?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
CREATE UNIQUE INDEX ux_assets_code ON assets (code) INCLUDE (description);. What happens when two inserted rows share code 'AX7' but have different descriptions?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
(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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
region_id ASC, priority DESC, created_at DESC. What B-tree order can provide that entire ordering through a backward scan?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Access method
type field, separately from the name of its selected index.Aggregate
B
B-tree
B+-tree
Backward scan
Bitmap scan
Bucket
Buffer cache
C
Cardinality
Clustering index
Collision
Composite index
Concurrent index build
Correlation
Covering access
Covering index
E
Estimated rows
EXPLAIN
EXPLAIN is a PostgreSQL and MySQL command that displays a planned execution strategy and its estimates without executing the query.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.EXPLAIN ANALYZE result can show that an inner lookup returned far more rows than its estimate predicted.Expression index
LOWER(email) supports a lowercase email lookup without converting every row during the search.F
Fanout
Filter
Foreign-key index
orders.customer_id helps locate orders before a referenced customer is deleted.Full table scan
H
Hash function
Hash index
Hash Join
Heap
Heap fetch
Histogram
HOT update
I
Included column
Independence
Index
orders.customer_id lets a customer-history query locate matching orders without checking every row.Index condition
Index Cond when showing that search in a plan.customer_id = 42 narrows access before a separate state filter rejects candidates.Index hint
Index key
(customer_id, order_date) groups one customer's entries together and orders their dates.Index maintenance
Index predicate
status = 'pending' excludes rows needed by a query for pending or shipped orders.Index scan
Index-only scan
L
Leaf
Leftmost prefix
customer_id of (customer_id, order_date) supports customer-only lookups.Loops
M
Merge Join
Most common values list
N
Nested Loop
P
Page
Page split
Partial index
Plan node
Q
Query optimizer
Query plan
R
Range scan
Redundant index
S
Sargable condition
total > 80 exposes the stored total key after an arithmetic filter is rearranged.Secondary index
Selectivity
Skip scan
Slow query log
Sort
Startup cost
Statistics
T
Total cost
U
Unused-index statistics
V
Visibility map
W
Workload
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.