Indexing Strategy and Design Questions
Choosing and designing indexes: B-tree, hash, composite, covering, partial, and full-text/inverted indexes, and the trade-offs between read acceleration and write/storage overhead. Covers selecting index columns from query patterns, cardinality and selectivity reasoning, diagnosing why an index is or is not used, and index maintenance: rebuilding or reorganizing a fragmented index, finding and dropping redundant or unused indexes, and rolling out a new index to production safely. Also covers indexing in analytical (bitmap, columnar), partitioned, and distributed/NoSQL systems. Central to database performance interviews.
Define index selectivity and cardinality. Given a customers table with 1,000,000 rows and a column 'country' with 5 unique values and a column 'customer_id' with 1,000,000 unique values, explain which column is a better candidate for an index and why. Also explain how selectivity affects optimizer choice.
Sample Answer
Direct answer
Cardinality is the number of distinct values a column has. Selectivity is that cardinality expressed as a fraction of the table: how much a single value narrows the result down. For a customers table with 1,000,000 rows, customer_id has 1,000,000 distinct values (cardinality 1,000,000, selectivity 1.0, meaning each value matches exactly one row), while country has 5 distinct values (cardinality 5, selectivity roughly 0.0000005 per exact-match lookup on customer_id, versus roughly 0.2, or 20%, per value on country, since values aren't evenly split here). customer_id is the far better index candidate: an index on it eliminates all but one row per lookup, while an index on country still leaves a large fraction of the table to sift through.
Structured elaboration
selectivity of a value v in column c=total rowsrows where c=v
Lower selectivity (a smaller fraction) is better for point lookups: it means a single value matches fewer rows, so an index eliminates more of the table. customer_id, being unique per row, has the best possible selectivity for equality lookups: exactly 1,000,0001 per value. country, with only 5 distinct values, has selectivity around 51=0.2 per value if the values were evenly distributed, meaning a typical WHERE country = ? still returns roughly a fifth of the entire table.
Why the optimizer cares. Every query plan is a bet on which access method reads the least data. An index lookup has a fixed per-row cost (walk the tree, then fetch the row), so it beats a sequential scan only when it fetches meaningfully fewer rows than the sequential scan would have to read anyway. At high selectivity (few matching rows), the index wins by a wide margin. At low selectivity (a large fraction of rows matching), the index degenerates toward reading almost the whole table anyway, PLUS the overhead of the index traversal itself, so the optimizer correctly prefers a sequential scan past some crossover point, which depends on the table's physical layout and the storage engine's cost model, not a single fixed percentage.
Worked example
Real distinct-value counts from the customers table used here, exactly matching the setup described above:
SELECT count(DISTINCT country) AS distinct_countries,
count(DISTINCT customer_id) AS distinct_customer_ids,
count(*) AS total_rows
FROM customers;
distinct_countries | distinct_customer_ids | total_rows
---------------------+------------------------+------------
5 | 1000000 | 1000000
Querying on the high-cardinality column, customer_id (already indexed as the primary key):
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id FROM customers WHERE customer_id = 777777;
Index Only Scan using customers_pkey on customers (cost=0.42..4.44 rows=1 width=4) (actual time=0.055..0.055 rows=1 loops=1)
Index Cond: (customer_id = 777777)
Heap Fetches: 0
Buffers: shared hit=1 read=3
Execution Time: 0.062 ms
Querying on the low-cardinality column, country, after building a matching index:
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id FROM customers WHERE country = 'US';
Bitmap Heap Scan on customers (cost=2253.67..16761.26 rows=201967 width=4) (actual time=3.275..34.310 rows=200301 loops=1)
Recheck Cond: (country = 'US'::text)
Heap Blocks: exact=11983
-> Bitmap Index Scan on idx_customers_country (actual time=2.442..2.442 rows=200301 loops=1)
Index Cond: (country = 'US'::text)
Execution Time: 37.387 ms
The customer_id lookup returned 1 row using 4 buffer reads and finished in a fraction of a millisecond, with Heap Fetches: 0 confirming it never touched the table storage at all. The country lookup, despite having its own index, matched 200,301 rows (roughly 20% of the table, since 'US' is one of the more common of the 5 values here) and took over 500x longer in this run, because at that selectivity the index still has to identify, and then fetch, a large fraction of the table's pages: the database chose a Bitmap Heap Scan (build a bitmap of matching pages from the index, then visit each page once) specifically because it's cheaper than either a naive row-by-row index scan or a full sequential scan at this selectivity, not because the index made the query fast in any absolute sense.
Trade-offs & pitfalls
Don't judge an index candidate purely by "does it have a reasonable number of distinct values": 5 distinct values across 1,000,000 rows sounds like it should help, and it does help somewhat (this query would be even slower with no index, and did cost less by the optimizer's own estimate than a plain sequential scan), but "helps somewhat" is a very different outcome from the near-instant, sub-millisecond result the high-cardinality column gets. In an OLTP (online transaction processing) system, where a filter like country = 'US' typically appears alongside a more selective predicate (a specific customer's transactions, say), it's the COMBINED selectivity of all the predicates in a composite index that matters, not any single column's cardinality in isolation. In an OLAP (online analytical processing) system, where a query is expected to summarize a large fraction of the table anyway, a low-selectivity column being "worse for point lookups" is often irrelevant, since the query was never going to touch a small slice of the table to begin with.
List the common index types you'd choose among (B-tree, hash, GIN/GiST, bitmap) and explain when you'd reach for each. Mention any important platform-specific caveats (for example Postgres's hash-index history).
Sample Answer
Direct answer
The choice among index types comes down to what operation the query needs to run against the column: exact-match only, range/sort, multi-valued (arrays, full text), or a small set of repeated values scanned in bulk. B-tree is the default and correct choice for the large majority of cases (equality, ranges, sorting). Hash is a narrow equality-only specialist. GIN (Generalized Inverted Index) and GiST (Generalized Search Tree), Postgres's two extensible index frameworks, serve composite or multi-valued data (full text, arrays, JSON, geometry). Bitmap indexes are a distinct storage structure in some other engines, built specifically for low-cardinality (few distinct values) columns in read-heavy analytics.
Structured elaboration
| Index type | Supports | Best fit | Key caveat |
|---|---|---|---|
| B-tree | =, <, >, BETWEEN, IN, IS NULL, sorted output, prefix LIKE 'foo%' | The default choice; high-cardinality (many distinct values) columns used in filters, joins, or ORDER BY | None of the others beat it unless you have a specific reason |
| Hash | = only | Pure equality lookups where you never sort or range-filter | In Postgres, not safe for production before version 10 (2017): pre-10 hash indexes were not write-ahead-logged, so a crash could corrupt them, and they were not replicated. Since version 10 they are crash-safe and replicated, but still cannot back a UNIQUE constraint and are single-column only, so a B-tree is almost always preferred anyway |
| GiST (Generalized Search Tree) | Nearest-neighbor and containment queries | Geometric/spatial data, and as infrastructure other extensions build on | Query-specific; not a general substitute for B-tree |
| GIN (Generalized Inverted Index) | Containment and membership (@>, <@, &&) | Full-text search (tsvector), jsonb, arrays: anything where one row maps to many indexed values | Slower, larger to maintain on write-heavy tables than a B-tree; Postgres mitigates this with a "fastupdate" pending list that batches new entries instead of updating the tree on every write, flushed in the background |
| BRIN (Block Range Index) | =, <, >, BETWEEN on physically-ordered data | Very large, naturally time-ordered or insert-ordered tables (a created_at column on an append-only log), where a tiny index (megabytes, not gigabytes) can still skip most of the table | Only useful when the column's values correlate with the physical row order; useless if the data is scattered |
Cardinality and column choice, briefly. Cardinality is the number of distinct values a column has relative to the row count. A column like customer_id (near-unique per row) is high-cardinality and a natural B-tree candidate. A column like status with 4 possible values is low-cardinality; a B-tree still works but each lookup returns a large fraction of the table, so the benefit shrinks. Cardinality does not automatically rule an index in or out, it changes how much benefit a given query gets from it, and that benefit has to be weighed against the fixed cost every index adds on every write.
Full-text and functional entries. GIN backs Postgres full-text search directly: build a tsvector column or expression (a processed, tokenized and stemmed representation of the text, the form Postgres full-text search actually matches against, not the raw string) and index it with GIN to support word-based search with ranking, which is a different tool from a functional (expression) index on a plain B-tree, which just lets you index the output of a function or expression (like lower(email)) rather than a raw column. Both are legitimate, and they solve different problems: GIN for "does this document contain these words," a functional B-tree for "make this exact computed value fast to look up."
Postgres's "Bitmap Scan" is not a bitmap index. Postgres shows Bitmap Heap Scan / Bitmap Index Scan in query plans, but that is a runtime execution strategy, built on the fly from an existing B-tree (or GIN, etc.) index, not a distinct stored index type you create. Oracle, by contrast, has a real, persisted CREATE BITMAP INDEX structure. It is deliberately optimized for low-cardinality columns (Oracle's own documentation gives no fixed numeric threshold here: it defines the guideline only relatively, as a distinct-value count that is small compared to the table's row count (its own example uses a 2-value gender column), so treat a specific number like "100 distinct values" as an informal rule of thumb, not something Oracle's docs actually say) in read-heavy decision-support/data-warehouse workloads. Its major caveat is concurrency: because one bitmap segment can represent thousands of rows, updating a single row locks that whole segment, which makes bitmap indexes a poor fit for OLTP (online transaction processing, meaning live application traffic with many concurrent small writes) tables and a real deadlock risk under contention. This is exactly why they are a data-warehouse tool, not a general-purpose one.
Worked example
Postgres's own type documentation groups these by supported operators, which maps directly onto the "what does the query need to do" decision:
B-tree: =, <, <=, >=, > (plus BETWEEN, IN, IS NULL, sorted retrieval)
Hash: = (equality only, no sort/range)
GiST: nearest-neighbor, geometric containment/overlap operators
GIN: @>, <@, = , && (containment/membership over multi-valued columns)
BRIN: =, <, <=, >=, > (only cheap when column correlates with physical order)
Applied to a concrete schema: an orders table with order_id (primary key, high cardinality: B-tree, default), customer_id (high cardinality, used in joins and equality filters: B-tree), status (4 values, low cardinality: B-tree still works, just returns a bigger fraction of rows per lookup), order_date on an append-only, insert-ordered table (BRIN is worth considering purely for its tiny footprint at very large scale), and a tags jsonb or a full-text description column (GIN).
Trade-offs & pitfalls
Do not default to "GIN because it can index anything": GIN's write overhead is real on a busy table, mitigated but not eliminated by fastupdate batching. Do not reach for hash indexes just because the workload is equality-only: unless you have a specific size or benchmark-driven reason, a B-tree does the same job and supports more query shapes if requirements change later. Do not assume BRIN is a free upgrade over B-tree for a big table: it is dramatically smaller and cheaper to maintain, but only useful when the indexed column's value order tracks physical row order (an id or created_at on an append-only table qualifies; a customer_id scattered across insert order does not).
You are given a query that runs slowly: it filters on LOWER(email) = 'abc@example.com'. Explain why this may prevent index usage and propose alternatives to make lookups case-insensitive while remaining sargable. Include SQL examples and index recommendations for PostgreSQL.
Sample Answer
Direct answer
LOWER(email) = 'abc@example.com' prevents index usage because a plain B-tree index on email stores entries sorted by the raw column value, not by LOWER(email); the database has no way to know a sorted-by-email structure also happens to be sorted by LOWER(email), so it falls back to scanning every row and computing LOWER() on each one to check the filter. The fix that stays sargable (able to use an index seek instead of a full scan) is to build the index on the same expression the query filters on: CREATE INDEX ON customers (LOWER(email)), and then always query through LOWER(email) = LOWER($1), or switch the column to Postgres's citext type so case-insensitive comparison is native and no function wrapping is needed at query time at all.
Why the function wrapper breaks the index
A B-tree index is a sorted structure over the exact value(s) you told it to index. An index on email lets Postgres binary-search for email = 'X' in roughly O(log n) steps (Big-O notation: the cost grows only with the logarithm of the row count n, a small, predictable number of steps, not one step per row) because the tree is sorted by that literal value. LOWER(email) = 'X' asks a different question, "find rows where the lowercased version of email equals X", and the plain index has no ordering with respect to that transformed value; the fact that the raw email value happens to be indexed doesn't help, because the transformation could scramble the sort order arbitrarily. Postgres's planner has no choice but to evaluate LOWER(email) for every row and check it against the literal, which means visiting every row: a sequential scan.
Worked example
CREATE TABLE customers (customer_id int PRIMARY KEY, country text NOT NULL, email text);
-- 50,000 rows, each email unique, e.g. 'customer12345@example.com'
CREATE INDEX idx_customers_email ON customers (email);
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, email FROM customers WHERE LOWER(email) = 'customer12345@example.com';
With only the plain index on email: Seq Scan on customers (cost=0.00..1157.00) actual time=10.045..22.073 rows=1, Filter: (lower(email) = ...), Rows Removed by Filter: 49999. The plain index on email exists and is valid, and the planner still ignores it completely for this query, exactly as the mechanism above predicts.
CREATE INDEX idx_customers_email_lower ON customers (LOWER(email));
After adding an expression index on LOWER(email): Index Scan using idx_customers_email_lower (cost=0.41..8.43) actual time=0.032..0.033 rows=1, Index Cond: (lower(email) = ...). Cost dropped from 1157 to 8.43, about 137x, because the index is now sorted by exactly the expression the query filters on.
An alternative that avoids needing an expression index or a LOWER() wrapper at query time at all: Postgres's citext extension (case-insensitive text), confirmed available and installable in a stock Postgres 16 instance with CREATE EXTENSION citext;. Changing the column's type to citext makes ordinary equality comparisons case-insensitive natively, so a plain index on that column works for email = 'Some@Example.com' without wrapping either side in a function.
Trade-offs and pitfalls
An expression index on LOWER(email) only helps queries that filter using the exact same expression; WHERE email ILIKE 'X' or WHERE UPPER(email) = 'X' will not use it, so every place in the codebase that does a case-insensitive email lookup needs to agree on the same normalized form, or you end up maintaining several expression indexes for the same underlying intent. citext avoids that coordination problem since the type itself is case-insensitive, but it changes the column's comparison semantics database-wide (sorting, grouping, and uniqueness constraints on that column all become case-insensitive too), which is usually what you want for an email column specifically, but is a real behavior change to review, not a drop-in swap to make casually on a column other logic depends on. Either fix also needs the application's write path updated: an expression index doesn't stop new rows being inserted with mixed-case email, it only makes lookups fast once you normalize the query side, so duplicate-prevention logic still needs to compare normalized values consistently.
Explain the difference between a clustered index and a nonclustered index. Use an orders table example where queries often filter by customer_id but the primary key is order_id. Discuss implications for physical layout, read performance, and insert/update cost, and name two databases with different clustered-index semantics.
Sample Answer
Direct answer
A clustered index determines the physical storage order of the table's own rows: the table IS the index, so there can be at most one per table. A non-clustered (secondary) index is a separate structure that stores sorted key values plus a pointer back to wherever the row physically lives, so a table can have many. On an orders table where queries commonly filter by customer_id but the primary key is order_id, this matters directly: if order_id is the clustering key, rows for a given customer are scattered across the table in insertion order, and a customer_id lookup (served by a non-clustered index) has to bounce around many unrelated physical pages to collect matching rows, even with an index in place.
Structured elaboration
Physical layout. Clustering means "rows near each other in the index key are near each other on disk." That locality is what makes range scans and ordered retrieval on the clustering key cheap: a query for a range of the clustering key reads a contiguous run of pages. A non-clustered index buys you a fast way to FIND the right rows, but each row it points to can still be an isolated, expensive random-access read if the table is not physically ordered by anything related to the query.
Read performance. For a query filtering on the clustering key, a clustered structure is close to optimal: locate the start, then read forward. For a query filtering on a non-clustered key, you pay for the index lookup (cheap) plus one scattered heap read per matching row (potentially expensive if there are many matches), because the matches are not adjacent on disk. A realistic BI (business-intelligence) style filter makes this concrete: a report querying WHERE customer_id = ? AND order_date >= ? AND status = ? on this same orders table needs all three predicates satisfied together. If order_id is the clustering key, none of the three helps locate a contiguous physical range, so the query leans entirely on a well-chosen non-clustered composite index (leading with whichever of the three is most selective, typically customer_id) to narrow down candidates before the scattered-row-fetch cost applies; clustering the table itself on order_id does nothing to help this specific filter combination.
Insert/update cost. A clustered table has to keep new rows in roughly the right physical position relative to the clustering key, which is more disruptive on write than simply appending. A non-clustered index only has to maintain its own separate, smaller structure; the base table can still grow by simple append if nothing forces reordering.
Cross-database semantics differ, and the terminology is not interchangeable:
- SQL Server: a table can have at most one clustered index (verified against Microsoft's current documentation). Defining a
PRIMARY KEYauto-creates a clustered index unless one already exists, in which case the primary key is enforced via a non-clustered index instead. A table with no clustered index at all is called a heap, and every non-clustered index's leaf entries store a "row locator": a direct pointer to the row on a heap, or the clustered index key itself if the table has a clustered index. - MySQL, on InnoDB (MySQL's default storage engine): the primary key IS always the clustered index; there is no option to have a table without one. If you don't define a primary key, InnoDB picks the first
NOT NULL UNIQUEindex it finds, or, failing that, silently generates a hidden synthetic row-ID column to cluster on (verified against MySQL's current documentation). Every secondary index in InnoDB stores the primary key value (not a raw disk pointer) as its row locator, which is why a long or wide primary key inflates the size of every secondary index on the table, not just the primary key's own storage. - Postgres: there is no persistently-maintained clustered index at all. Table storage (the "heap") is ordered by insertion/update history by default, independent of any index. Postgres does offer a one-time
CLUSTER table USING index_namecommand that physically rewrites the table in that index's order, but nothing keeps it that way afterward; new inserts and updates go back to being unordered relative to the clustering key until you runCLUSTERagain (and it takes an exclusive lock while it runs).
Alternative index structures worth naming here. Bitmap indexes (a real, persisted structure in engines like Oracle, distinct from Postgres's runtime bitmap SCAN strategy) target low-cardinality columns and trade concurrency for compactness. Inverted indexes (what Postgres's GIN, short for Generalized Inverted Index, implements) map each distinct value to the set of rows containing it, which is the right tool for multi-valued columns, not a substitute for the clustered/non-clustered choice on a single scalar column like customer_id.
Partitioned tables. When a table is partitioned (split into physically separate sub-tables, typically by date range or hash), clustering and secondary indexing both happen per-partition in Postgres and MySQL: each partition has its own local index copies, and a global index spanning all partitions is either unsupported or a distinct, heavier feature depending on engine and version. Practically: a CLUSTER-style physical reorg, or a clustered-index choice, has to be applied per partition, and a non-clustered index lookup that cannot be pruned to a single partition may have to probe several partitions' worth of local indexes.
Worked example
Demonstrating the physical-locality claim directly, using the orders(order_id, customer_id, ...) table: before any physical reordering, the two rows belonging to customer_id = 424242 sit on different heap pages, identified here by Postgres's internal row identifier (ctid, meaning "page number, row offset within page"):
SELECT customer_id, ctid, order_id FROM orders WHERE customer_id = 424242 ORDER BY order_id;
customer_id | ctid | order_id
-------------+------------+----------
424242 | (897,131) | 117921
424242 | (11994,76) | 1575279
Two different pages (897 and 11994) out of roughly 15,000 total. Then physically reordering the table by the customer_id index:
CLUSTER orders USING idx_orders_customer_id;
SELECT customer_id, ctid, order_id FROM orders WHERE customer_id = 424242 ORDER BY order_id;
customer_id | ctid | order_id
-------------+-----------+----------
424242 | (6454,47) | 117921
424242 | (6454,48) | 1575279
Both rows now sit on the same physical page, one row apart. That is what "clustered" means concretely: rows sharing a key value become physical neighbors, which is exactly the locality a customer_id-filtered query benefits from, at the cost of a one-time, exclusive-lock reorganization that Postgres will not maintain automatically going forward.
Trade-offs & pitfalls
Picking order_id as the clustering key (the common default, since it is usually also the primary key and the insert order) optimizes for the wrong access pattern if most real queries filter by customer_id instead; the insert-time convenience of clustering on a monotonically increasing key is not the same thing as clustering on the key your queries actually use. In SQL Server or InnoDB, prefer clustering on (or choosing as primary key) whatever column dominates your range/lookup queries, not necessarily the surrogate ID, when write patterns allow it. In Postgres, remember that CLUSTER is a snapshot, not a standing guarantee: if customer_id locality matters enough to justify a physical reorg, you also need a plan (a maintenance window, or pg_repack for an online rewrite) to redo it periodically as the table churns, or you are back to scattered storage within weeks.
Explain what a B-tree index is and why adding an index on customer_id in a large orders table might speed up lookups but slow down inserts. Include impact on storage, and how index choice changes read/write trade-offs for BI reporting vs OLTP.
Sample Answer
Direct answer
A B-tree index on orders.customer_id lets the database jump straight to the rows for a given customer instead of scanning the whole table, which is a large win for point lookups (WHERE customer_id = ?). The same index makes every INSERT, and every UPDATE that touches customer_id, more expensive, because the database must also insert a new entry into the B-tree (a sorted, self-balancing tree structure) in the correct sorted position, not just append to the table. It also costs storage: in a 2,000,000-row orders table, a single-column B-tree index on an integer column measured 24 MB against a 100 MB table, roughly a quarter of the table's own size again.
Structured elaboration
Read side. A B-tree keeps its keys sorted and organized into a shallow tree, so an equality lookup takes on the order of log(row count) comparisons to find the first matching entry, then follows pointers to the matching rows. Without the index, the database has no choice but to read every row (a sequential scan) and evaluate the filter against each one, a cost that grows linearly with table size.
Write side. An INSERT into an indexed table is not just "append a row." The database also has to locate the correct position in the B-tree for the new key and insert an entry there, which occasionally causes a page split (the tree rebalancing itself to make room). Each additional index on the table means one more structure to update, synchronously, inside the same transaction as the row write. This is real, measurable I/O (input/output, meaning disk or cache page reads and writes) and CPU work, not just a theoretical cost.
Storage side. Every index is a second on-disk copy of the indexed columns (plus row pointers), sized independently of the table. A narrow, high-cardinality (many distinct values) integer column indexes relatively cheaply; wider or lower-cardinality columns, or indexes covering multiple columns, cost more.
OLTP vs. BI/reporting trade-off. Online transaction processing (OLTP) workloads (the app's live traffic: creating orders, updating order status) are write-heavy and latency-sensitive on individual rows, so they are the ones that pay the write tax on every index. BI/reporting workloads are read-heavy over large ranges and usually tolerate more indexes, or even a separate, denormalized copy of the data purpose-built for scanning, because they are not the ones absorbing the insert cost. The practical implication: an index that makes a dashboard query fast is not free just because the dashboard is happy. Someone is paying for it on the write path, and for a high-throughput OLTP table that cost is real.
Worked example
Point lookup on orders.customer_id, 2,000,000-row orders table, before any index:
EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, order_date, total_amount FROM orders WHERE customer_id = 424242;
Gather (cost=1000.00..24156.07 rows=4 width=18) (actual time=10.296..22.292 rows=4 loops=1)
Workers Planned: 2
-> Parallel Seq Scan on orders (cost=0.00..23155.67 rows=2 width=18) (actual time=10.020..17.318 rows=1 loops=3)
Filter: (customer_id = 424242)
Rows Removed by Filter: 666665
Execution Time: 22.303 ms
After CREATE INDEX idx_orders_customer_id ON orders(customer_id); (measured: 24 MB, versus 100 MB for the table at that point):
Index Scan using idx_orders_customer_id on orders (cost=0.43..19.73 rows=4 width=18) (actual time=0.016..0.021 rows=4 loops=1)
Index Cond: (customer_id = 424242)
Execution Time: 0.025 ms
That is the read win: roughly 890x less execution time in this single run, driven by reading a handful of pages instead of scanning the whole table.
Now the write cost. Two identical staging tables were built, one with the same B-tree index on customer_id, one without, and 200,000 new rows were inserted into each with EXPLAIN (ANALYZE, BUFFERS) wrapped around the INSERT:
-- no index on customer_id:
Insert on orders_noidx (actual time=187.357..187.358 rows=0 loops=1)
Buffers: shared hit=405843 read=3 dirtied=1830 written=1822
Execution Time: 187.595 ms
-- same 200,000 rows, WITH the index on customer_id:
Insert on orders_idx (actual time=359.504..359.505 rows=0 loops=1)
Buffers: shared hit=1007046 read=1205 dirtied=4237 written=3024
Execution Time: 359.746 ms
The buffer count (pages touched) more than doubled (405,843 to 1,007,046, roughly 2.5x), the pages actually dirtied (modified, meaning they must eventually be written back to disk) also increased sharply (1,830 to 4,237, roughly 2.3x), and execution time rose by a comparable margin (187.6 ms to 359.7 ms, roughly 1.9x), because every one of the 200,000 inserts now had to write a table row AND maintain the B-tree. These three multiples are close but not identical (2.5x, 2.3x, 1.9x): "touched" counts every buffer access, including repeat visits to the same hot B-tree pages during the index insert, while "dirtied" only counts each page the first time it is modified in this statement, which is why it grows a little slower than the raw touch count. The buffer counts are the reliable signal here (they reflect real page-level work the engine did), and the timing, from a single, non-benchmarked run in one container, moved in the same direction, which is consistent, not a coincidence.
Trade-offs & pitfalls
The read win and the write cost are not symmetric with volume: the read win applies once per query, however many times it runs; the write cost applies to every single row written, forever, whether or not anyone ever runs the query the index was built for. For a high-throughput OLTP orders table, adding an index because "reporting wants it" is a decision that should weigh insert/update volume just as heavily as the reporting query's benefit; a common resolution is to serve reporting from a read replica or an OLAP (online analytical processing, the read-heavy, large-scan-oriented counterpart to OLTP) store instead of adding write-path cost to the primary. A related pitfall: indexing a column that changes frequently (as opposed to one that is only ever inserted and read) multiplies the write cost, since every UPDATE to that column means removing the old B-tree entry and inserting a new one.
Unlock Full Question Bank
Get access to all 14 Indexing Strategy and Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.