12 questions on indexes & performance, tagged easy, medium or hard, each with a worked answer in runnable SQL.
One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
No questions at this difficulty on this page. Pick another filter.
1
What is an index, and what does it cost?
Easy
An index is a separate structure, usually a B-tree, that maps column values to row locations so lookups avoid scanning the whole table. It speeds reads and slows writes: every INSERT, UPDATE or DELETE on indexed columns must update each index too, and every index consumes storage.
CREATE INDEX idx_orders_customer ON orders (customer_id);
-- Now a point lookup probes a few tree levels instead of scanning orders:
SELECT * FROM orders WHERE customer_id = 42;
The complete answer names both sides: an index pays for itself only if queries use it often enough to cover the extra cost on every write. Indexes also help ORDER BY (rows come out of the index already sorted), joins (the inner side of a nested loop can seek) and uniqueness checks, not just WHERE filters.
2
You have an index on (city, signup_date). Which queries can use it?
중간
A composite B-tree index works on filters and sorts that use a leftmost prefix of its columns. The (city, signup_date) index serves city, city plus a signup_date range, and equality on city plus a sort on signup_date, but not signup_date alone.
CREATE INDEX idx_customers_city_date ON customers (city, signup_date);
-- Uses the index:
SELECT * FROM customers WHERE city = 'Berlin';
SELECT * FROM customers WHERE city = 'Berlin' AND signup_date >= '2025-01-01';
SELECT * FROM customers WHERE city = 'Berlin' ORDER BY signup_date;
-- Cannot seek (only a full scan or index scan):
SELECT * FROM customers WHERE signup_date >= '2025-01-01';
The design rule that follows: equality columns first, then the range or sort column. A gap in the middle stops the seek; WHERE city = ? AND name = ? with index (city, signup_date, name) can seek on city but must check name on every entry for that city. The modern caveat: Oracle, MySQL 8.0.13+, PostgreSQL 18 and SQLite (once ANALYZE has gathered statistics) have skip scans, which can use the index for signup_date alone by probing once per distinct city. That only pays off when the leading column has few distinct values.
3
What does sargable mean? Why does WHERE LOWER(email) = ? ignore the index?
중간
Sargable (from Search ARGument ABLE) describes predicates the engine can answer with an index seek. The index on email is sorted by email, not by LOWER(email), so once the column is wrapped in a function the engine has to compute LOWER for every row and compare.
-- Not sargable: function applied to the column
SELECT * FROM users WHERE LOWER(email) = '[email protected]';
-- Sargable, if emails are stored lowercased: normalize the parameter
SELECT * FROM users WHERE email = '[email protected]';
-- If stored case varies, index the expression (PostgreSQL, SQLite, Oracle;
-- MySQL 8.0.13+ needs ((LOWER(email))), SQL Server an indexed computed column):
CREATE INDEX idx_users_email_lower ON users (LOWER(email));
The same rule kills leading-wildcard LIKE: WHERE name LIKE '%son' cannot seek because any value could end in son, while LIKE 'son%' seeks fine. Other common violations: arithmetic on the column (WHERE total * 1.2 > 100 instead of total > 100 / 1.2) and date functions (WHERE YEAR(order_date) = 2025 instead of a half-open date range). On SQL Server and MySQL a case-insensitive collation often makes LOWER unnecessary in the first place.
4
What is a covering index, and what is an index-only scan?
중간
A covering index contains every column a query needs, so the engine answers it from the index alone and never visits the table. PostgreSQL shows it in EXPLAIN as Index Only Scan; SQL Server shows an index seek with no Key Lookup. The INCLUDE clause adds columns to the leaf level without making them part of the key.
-- Query: SELECT order_id, order_date FROM orders WHERE customer_id = 42
-- SQL Server and PostgreSQL 11+:
CREATE INDEX idx_orders_covering ON orders (customer_id) INCLUDE (order_id, order_date);
-- MySQL and SQLite have no INCLUDE: put the columns in the key instead
CREATE INDEX idx_orders_covering ON orders (customer_id, order_date, order_id);
The tradeoff to state: wide indexes cost more on writes and in storage, so cover the hot queries, not every query. On InnoDB, and on SQL Server when the primary key is clustered, every secondary index already carries the primary key, so order_id is covered for free there. PostgreSQL has its own caveat: an index-only scan still checks the visibility map and visits the table for recently changed pages, so it works best on tables VACUUM keeps up with.
5
What is the difference between a clustered and a non-clustered index?
Easy
A clustered index dictates the physical order of the table's rows; the table is the index. SQL Server gives each table one clustered index (the primary key by default) and non-clustered indexes point to the clustered key. MySQL InnoDB similarly stores rows in primary-key order. PostgreSQL has no clustered indexes: the table is a heap and every index points into it. Its CLUSTER command reorders the table once but does not maintain that order afterwards.
-- SQL Server: non-clustered index pointing into the clustered table
CREATE NONCLUSTERED INDEX idx_orders_date ON orders (order_date)
INCLUDE (customer_id, total);
The practical consequences: in SQL Server and InnoDB, insert patterns that append to the clustered key (an identity PK) are cheap, while random keys (a UUIDv4 PK) cause page splits; and a secondary-index lookup that needs other columns pays a second seek through the clustered key. In PostgreSQL, any index access that is not an index-only scan fetches the row from the heap, so covering indexes matter there too.
6
Why can LIKE '%term' not use a B-tree index, and what are the alternatives?
중간
A B-tree orders values lexicographically from the left. A predicate on the prefix (LIKE 'term%') narrows a contiguous range; a leading wildcard (%term) could match anywhere, so no range seek is possible.
-- Uses the index:
SELECT * FROM products WHERE name LIKE 'steel%';
-- Cannot seek: full scan
SELECT * FROM products WHERE name LIKE '%steel%';
-- PostgreSQL alternative: trigram index for contains-search
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_name_trgm ON products USING gin (name gin_trgm_ops);
A PostgreSQL detail that catches people: under a non-C collation, a plain B-tree index does not serve LIKE 'steel%' at all; you need the index created with text_pattern_ops (or a C collation). The general answer: suffix searches can use an index on the reversed string, contains-searches want full-text or trigram indexes, and on a small table the scan may simply be faster than any index.
7
When does an index hurt, and how do you decide whether to keep one?
중간
Indexes cost write throughput: every write touches each index, plus storage and planner overhead from statistics. An index that no query seeks on is pure cost.
-- A low-selectivity column rarely helps on its own:
CREATE INDEX idx_orders_status ON orders (status); -- 3 distinct values over 10M rows
-- PostgreSQL: indexes that have never been scanned since stats were reset
SELECT relname, indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0;
An index on status is worth it only for the rare value: if 1% of orders are 'open' and queries look for those, a partial index on just the open rows beats a full one. The decision framework: check actual usage (pg_stat_user_indexes on PostgreSQL, sys.dm_db_index_usage_stats on SQL Server, sys.schema_unused_indexes on MySQL), weigh read patterns against write volume, and prefer a few composite indexes that serve several queries over many single-column ones. Check usage on every replica before dropping: an index unused on the primary may serve the reports on a read replica.
8
What is a partial index, and when is it the right choice?
Hard
A partial (filtered) index covers only the rows matching a predicate. It is smaller and cheaper to maintain, and it can serve the hot slice of data precisely.
-- Almost every query only looks at open orders, which are 2% of rows:
CREATE INDEX idx_orders_open ON orders (customer_id)
WHERE status = 'open';
-- A partial unique index enforces a rule a plain UNIQUE cannot:
-- at most one open cart per customer, any number of closed ones.
CREATE UNIQUE INDEX ux_carts_one_open ON carts (customer_id)
WHERE status = 'open';
The same syntax works on PostgreSQL, SQLite and SQL Server (where it is called a filtered index); MySQL and Oracle have no partial indexes. The planner uses one only when the query's WHERE clause implies the index predicate, so WHERE customer_id = ? AND status = 'open' matches. On SQL Server that has to be provable at compile time: a parameterized status = @s will not use the filtered index unless the plan is compiled for the literal value.
9
How do you read an EXPLAIN plan? What are the red flags?
중간
Read it from the deepest nodes up: each node is an operation, the numbers are estimated rows and cost, and the top node is the final step. The first question is always access method: index seek or scan versus a sequential scan of the whole table.
EXPLAIN ANALYZE
SELECT c.name, SUM(o.total)
FROM customers c JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_date >= '2025-01-01'
GROUP BY c.customer_id, c.name;
-- Red flags: Seq Scan on orders with a highly selective filter,
-- estimated rows far off from actual rows (stale statistics),
-- Nested Loop over millions of rows, and Sort spilling to disk.
EXPLAIN ANALYZE (PostgreSQL, MySQL 8.0.18+) actually runs the query, so wrap data-changing statements in a transaction you roll back. It shows real rows next to the estimates, and a gap of 10x or more points at stale statistics or correlated columns the planner treats as independent. SQL Server's equivalent is the actual execution plan. Then say what you would do: ANALYZE (or UPDATE STATISTICS) the table, add or widen an index for the filter, or rewrite the query.
10
The optimizer is ignoring your index. What are the likely causes?
Hard
Usual suspects, roughly in order: the predicate is not sargable (function or leading wildcard on the column); the query matches too many rows for a seek to beat a scan (low selectivity); statistics are stale so the estimates lie; type mismatch or implicit conversion (comparing varchar column to an int parameter); OR branches on different columns with no composite index; and optimizer hints or settings forcing another plan.
-- Type mismatch: customers.phone is VARCHAR, the value is a number.
-- MySQL converts every phone to a number to compare, so no index seek:
SELECT * FROM customers WHERE phone = 5551234;
-- Compare like with like:
SELECT * FROM customers WHERE phone = '5551234';
The direction of the mismatch matters: the column is what gets converted, so a string column compared to a number loses its index, while a number column compared to a quoted literal is usually fine because the literal is converted once. SQL Server's version is a VARCHAR column compared to an NVARCHAR parameter, which most .NET drivers send by default; under a SQL_ collation the column is converted row by row and the seek becomes a scan. Structure the answer as checklist then measurement: check sargability and types, check selectivity, refresh statistics, and compare the plan before and after.
11
Why do foreign keys need their own indexes, and what breaks without them?
중간
A foreign key constraint checks the parent on writes, but deleting or updating a parent row must find referencing children, and without an index on the child column that is a full scan per parent write.
-- The FK enforces integrity but creates no index on most engines
-- (SQL Server, PostgreSQL, Oracle and SQLite do not auto-index the child side):
CREATE TABLE orders (
order_id BIGINT PRIMARY KEY,
customer_id BIGINT REFERENCES customers(customer_id)
);
-- Add it yourself:
CREATE INDEX idx_orders_customer ON orders (customer_id);
The cascading failure story: DELETE on customers slows to a scan of orders per row, the delete transaction holds locks longer, and everything behind it queues. MySQL InnoDB is the exception: it requires an index on the foreign key column and creates one if none exists. On Oracle an unindexed foreign key is worse still, because a parent delete or key update locks the whole child table. Join performance on the FK column is the second benefit, but the delete-path check is the reason that surprises people.
12
Why is SELECT * discouraged, beyond style?
중간
Three concrete costs: it defeats covering indexes, because the engine must fetch every column from the table; it ships bytes you discard, such as wide TEXT or JSON columns sent over the network; and it couples code to the schema, so adding, dropping or reordering a column changes every result set that consumed it.
-- Needs customer_id, order_id and order_date, which a covering index can hold:
SELECT order_id, order_date FROM orders WHERE customer_id = 42;
-- SELECT * forces a heap fetch for every column, every time:
SELECT * FROM orders WHERE customer_id = 42;
The caveat: SELECT * is fine for ad-hoc exploration and inside EXISTS. The discipline belongs in application code, views and reports. In a view it has a specific trap: on SQL Server and PostgreSQL the * is expanded when the view is created, so columns added to the table later do not appear in the view until it is recreated.
Indexes & performance interview FAQ
Do I need to know a specific database for these?
No. The reasoning is engine-agnostic: B-trees, selectivity and the leftmost-prefix rule work the same on SQL Server, PostgreSQL, MySQL and SQLite, and the answers note engine-specific names where they differ.
What does sargable mean, and is it covered?
Yes, with the two classic violations: wrapping an indexed column in a function, and leading-wildcard LIKE searches. Both show the rewrite that lets the index work again.
Are EXPLAIN plans covered?
One question walks through reading a plan: spotting sequential scans, checking which index was chosen and why, and what estimated row counts tell you about stale statistics.
Is there a question about when indexes hurt?
Yes: write amplification on insert-heavy tables, indexes that never get used, and why every index is a bet that some query is worth slowing writes down for.
SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your
schema, a formatter, guardrails for risky queries, and every engine in one app.