← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 11 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 11 of 26

Questions 201–220 of 501 · 0 of 20 on this page marked learned

201.sql-0201Hardsenior

How does Boyce-Codd normal form differ from 3NF? Give a case that is in 3NF but not BCNF.

BCNF requires that for every non-trivial functional dependency X → Y, X is a superkey. 3NF allows an exception when Y is part of a candidate key. A classic case: tutoring(student, subject, tutor), where each tutor teaches one subject (tutor → subject) and a student has one tutor per subject. It is in 3NF but not BCNF, because tutor is not a superkey.

Full answer

In tutoring(student, subject, tutor):

  • (student, subject) → tutor: each student has one tutor per subject.
  • tutor → subject: each tutor teaches only one subject.

Candidate keys are (student, subject) and (student, tutor). The dependency tutor → subject has a left side that is not a superkey, so BCNF fails. 3NF accepts it because subject is part of a candidate key.

The practical problem: a tutor's subject is repeated for each student, and if the tutor switches subject, many rows must change.

The BCNF decomposition is tutors(tutor, subject) and tutoring(student, tutor). The catch is that the rule "one tutor per student per subject" can no longer be enforced with a simple key, because subject and student are now in different tables. This loss of dependency preservation is why some designs stop at 3NF.

Key points

  • BCNF: every determinant is a superkey
  • 3NF allows dependencies into key attributes
  • Overlapping candidate keys create 3NF-but-not-BCNF cases
  • BCNF decomposition may not preserve all dependencies

Common mistakes

  • Saying 3NF and BCNF are the same
  • Ignoring the dependency-preservation trade-off

Follow-ups

  • How would you enforce the lost rule after decomposition?
  • What are 4NF and multivalued dependencies?

Tips

  • Name the determinant that breaks BCNF
202.sql-0202Mediummid

What is denormalization, and when is it a reasonable choice?

Denormalization stores redundant or precomputed data on purpose, such as an order_total column or a customer name copied onto invoices, to make reads faster or simpler. It is reasonable when reads greatly outnumber writes, when joins or aggregations are measurably slow, or when the copy is a historical snapshot. The cost is keeping copies consistent.

Full answer

Common, defensible forms:

  • Snapshot values: an invoice stores the customer's address and the price at the time of sale. This is not just a speed trick; the copy is the correct historical record.
  • Counters and totals: orders.total or posts.comment_count, maintained by the application, a trigger or a periodic job.
  • Reporting tables or materialized views that pre-join and pre-aggregate data for dashboards.

Before denormalizing, check that an index, a better query or a materialized view does not solve the problem. Then decide who keeps the copy correct and how drift is detected, for example a nightly check that recomputes totals and compares.

A useful interview framing: normalize the source of truth, then denormalize derived data where measurements justify it.

Key points

  • Denormalization adds deliberate redundancy
  • Historical snapshots are a legitimate copy
  • Counters and reporting tables speed reads
  • Someone must keep copies consistent

Common mistakes

  • Denormalizing before measuring
  • Copying live data without any way to detect drift

Follow-ups

  • How would you keep a comment_count accurate?
  • How does a materialized view compare with a denormalized column?

Tips

  • Separate snapshots from caches
203.sql-0203Easyfresher

Design tables for a many-to-many relationship between students and courses, including the mark for each enrolment.

Use a junction table, enrolments(student_id, course_id, marks), with foreign keys to both parents and a primary key on (student_id, course_id). Attributes of the relationship itself, such as marks or enrolment date, belong on the junction table, not on either parent.

Full answer
sql
PRAGMA foreign_keys = ON;
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrolments (
  student_id INTEGER NOT NULL REFERENCES students(id),
  course_id  INTEGER NOT NULL REFERENCES courses(id),
  marks      INTEGER CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, course_id)
);
CREATE INDEX enrolments_course ON enrolments(course_id);
INSERT INTO students VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO courses VALUES (10, 'Databases'), (20, 'Algorithms');
INSERT INTO enrolments VALUES (1, 10, 88), (1, 20, 92), (2, 10, 75);
SELECT c.title, COUNT(*) AS students FROM enrolments e JOIN courses c ON c.id = e.course_id GROUP BY c.id, c.title ORDER BY c.title;
titlestudents
Algorithms1
Databases2

Each enrolment is one row, so a student can take many courses and a course can have many students. The composite primary key stops a student enrolling twice in the same course. An extra index on course_id serves "who is in this course?", because the primary key index starts with student_id.

marks describes the pair, so it lives here. Putting it on students would only allow one mark per student, and on courses one mark per course.

If students may retake a course, the key must change, for example to (student_id, course_id, term). That requirement is worth asking about in an interview.

sql
PRAGMA foreign_keys = ON;
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrolments (
  student_id INTEGER NOT NULL REFERENCES students(id),
  course_id  INTEGER NOT NULL REFERENCES courses(id),
  marks      INTEGER CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, course_id)
);
CREATE INDEX enrolments_course ON enrolments(course_id);
INSERT INTO students VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO courses VALUES (10, 'Databases'), (20, 'Algorithms');
INSERT INTO enrolments VALUES (1, 10, 88), (1, 20, 92), (2, 10, 75);
SELECT c.title, COUNT(*) AS students FROM enrolments e JOIN courses c ON c.id = e.course_id GROUP BY c.id, c.title ORDER BY c.title;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Many-to-many needs a junction table
  • Foreign keys point to both parents
  • Composite primary key prevents duplicate pairs
  • Relationship attributes belong on the junction table

Common mistakes

  • Storing a list of course ids on the student row
  • Forgetting the index for lookups by the second column

Follow-ups

  • How would you support retakes?
  • How would you list courses with no students?

Tips

  • Ask about retakes before fixing the key
204.sql-0204Mediummid

How would you store the price of a product so that past orders still show what the customer actually paid?

Copy the unit price onto each order line at purchase time, and keep the current price on the product. Optionally keep a price history table with valid_from and valid_to dates for analysis. Joining old orders to the current product price would rewrite history whenever the price changes.

Full answer
sql
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER);
CREATE TABLE order_lines (order_id INTEGER, product_id INTEGER, qty INTEGER, unit_price INTEGER);
INSERT INTO products VALUES (1, 'Notebook', 4);
INSERT INTO order_lines VALUES (1, 1, 2, 4);
UPDATE products SET price = 5 WHERE id = 1;
SELECT ol.order_id, ol.unit_price AS paid, p.price AS current_price FROM order_lines ol JOIN products p ON p.id = ol.product_id;
order_idpaidcurrent_price
145

The product now costs 5, yet order 1 still shows 4, because the line stored the price it was sold at. A report that joined to products.price would claim the customer paid 5.

A price history table answers "what was the list price on a given date?":

sql
CREATE TABLE price_history (product_id INTEGER, price INTEGER, valid_from TEXT, valid_to TEXT);
INSERT INTO price_history VALUES (1, 4, '2026-01-01', '2026-03-01'), (1, 5, '2026-03-01', NULL);
SELECT price FROM price_history
WHERE product_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');
price
4

The same pattern applies to tax rates, currency conversion rates, addresses and discounts: anything that can change after the transaction and must be reported as it was.

sql
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER);
CREATE TABLE order_lines (order_id INTEGER, product_id INTEGER, qty INTEGER, unit_price INTEGER);
INSERT INTO products VALUES (1, 'Notebook', 4);
INSERT INTO order_lines VALUES (1, 1, 2, 4);
UPDATE products SET price = 5 WHERE id = 1;
SELECT ol.order_id, ol.unit_price AS paid, p.price AS current_price FROM order_lines ol JOIN products p ON p.id = ol.product_id;

CREATE TABLE price_history (product_id INTEGER, price INTEGER, valid_from TEXT, valid_to TEXT);
INSERT INTO price_history VALUES (1, 4, '2026-01-01', '2026-03-01'), (1, 5, '2026-03-01', NULL);
SELECT price FROM price_history
WHERE product_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Store the price paid on the order line
  • Keep the current price on the product
  • A history table with validity dates supports as-of queries
  • Applies to taxes, rates and addresses too

Common mistakes

  • Joining historical orders to current prices
  • Overlapping validity ranges in the history table

Follow-ups

  • How would you prevent overlapping price periods?
  • How would you show revenue at list price versus paid price?

Tips

  • Call it a snapshot, not duplication
205.sql-0205Mediummid

Design a schema for a blog where posts have many comments, comments can reply to other comments, and posts have many tags.

Use posts, comments with post_id and a nullable parent_id referencing comments, tags, and a post_tags junction table. parent_id NULL means a top-level comment. Index comments(post_id) and comments(parent_id), and read threads with a recursive CTE.

Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE comments (
  id        INTEGER PRIMARY KEY,
  post_id   INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  parent_id INTEGER REFERENCES comments(id),
  body      TEXT NOT NULL
);
CREATE INDEX comments_post ON comments(post_id);
CREATE INDEX comments_parent ON comments(parent_id);
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
CREATE TABLE post_tags (post_id INTEGER REFERENCES posts(id), tag_id INTEGER REFERENCES tags(id), PRIMARY KEY (post_id, tag_id));
INSERT INTO posts VALUES (1, 'Window functions');
INSERT INTO comments VALUES (1, 1, NULL, 'Great post'), (2, 1, 1, 'Agreed'), (3, 1, 2, 'Same');
WITH RECURSIVE t(id, depth) AS (
  SELECT id, 0 FROM comments WHERE post_id = 1 AND parent_id IS NULL
  UNION ALL SELECT c.id, t.depth + 1 FROM comments c JOIN t ON c.parent_id = t.id
)
SELECT id, depth FROM t ORDER BY id;
iddepth
10
21
32

Design notes:

  • comments.parent_id references the same table, which models any depth of replies. A recursive CTE reads a thread, as in the hierarchy questions in this bank.
  • post_id is stored on every comment, including replies, so "all comments on a post" needs no recursion.
  • tags.name is UNIQUE, and post_tags uses a composite primary key.
  • ON DELETE CASCADE from posts to comments fits, because comments mean nothing without the post. For replies, many products keep the reply and show "comment deleted" instead, which suggests a soft delete flag rather than a cascade.

Questions worth asking: are comments moderated (a status column), can authors edit (an edited_at column or history), and how deep can threads go in the interface?

sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE comments (
  id        INTEGER PRIMARY KEY,
  post_id   INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  parent_id INTEGER REFERENCES comments(id),
  body      TEXT NOT NULL
);
CREATE INDEX comments_post ON comments(post_id);
CREATE INDEX comments_parent ON comments(parent_id);
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
CREATE TABLE post_tags (post_id INTEGER REFERENCES posts(id), tag_id INTEGER REFERENCES tags(id), PRIMARY KEY (post_id, tag_id));
INSERT INTO posts VALUES (1, 'Window functions');
INSERT INTO comments VALUES (1, 1, NULL, 'Great post'), (2, 1, 1, 'Agreed'), (3, 1, 2, 'Same');
WITH RECURSIVE t(id, depth) AS (
  SELECT id, 0 FROM comments WHERE post_id = 1 AND parent_id IS NULL
  UNION ALL SELECT c.id, t.depth + 1 FROM comments c JOIN t ON c.parent_id = t.id
)
SELECT id, depth FROM t ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Self-referencing parent_id models reply trees
  • Store post_id on every comment for flat reads
  • Tags use a junction table
  • Decide between cascade and soft delete for replies

Common mistakes

  • Storing replies in a separate table per level
  • Comma-separated tags on the post

Follow-ups

  • How would you fetch a thread in display order?
  • How would you count comments per post efficiently?

Tips

  • State the delete behaviour you chose and why
206.sql-0206Hardsenior

How would you model an entity that can belong to one of several parent types, such as comments on either posts or photos?

A polymorphic column pair (parent_type, parent_id) is easy but cannot have a foreign key, so orphans are possible. Better options are separate nullable foreign keys with a CHECK that exactly one is set, separate comment tables per parent, or a shared supertype table that both posts and photos reference.

Full answer

Option A, polymorphic pair: comments(parent_type, parent_id). Simple and common in ORMs, but no foreign key can point to two tables, so deleting a photo leaves comments pointing at nothing.

Option B, exclusive foreign keys:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE posts (id INTEGER PRIMARY KEY);
CREATE TABLE photos (id INTEGER PRIMARY KEY);
CREATE TABLE comments (
  id       INTEGER PRIMARY KEY,
  post_id  INTEGER REFERENCES posts(id),
  photo_id INTEGER REFERENCES photos(id),
  body     TEXT,
  CHECK ((post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1)
);
INSERT INTO posts VALUES (1);
INSERT INTO photos VALUES (1);
INSERT INTO comments VALUES (1, 1, NULL, 'ok');
INSERT INTO comments VALUES (2, 1, 1, 'both parents');
-- error on purpose
text
Error: CHECK constraint failed: (post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1

The CHECK requires exactly one parent. Each column has a real foreign key, so the database protects integrity. Adding a third parent type means adding a column.

Option C, separate tables (post_comments, photo_comments) keeps each simple but duplicates logic.

Option D, a supertype: a commentable(id) table that posts and photos each reference one-to-one, and comments reference commentable. It scales to many types with full integrity, at the cost of an extra join.

Choose B for a few stable parent types, D for many.

sql
-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE posts (id INTEGER PRIMARY KEY);
CREATE TABLE photos (id INTEGER PRIMARY KEY);
CREATE TABLE comments (
  id       INTEGER PRIMARY KEY,
  post_id  INTEGER REFERENCES posts(id),
  photo_id INTEGER REFERENCES photos(id),
  body     TEXT,
  CHECK ((post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1)
);
INSERT INTO posts VALUES (1);
INSERT INTO photos VALUES (1);
INSERT INTO comments VALUES (1, 1, NULL, 'ok');
INSERT INTO comments VALUES (2, 1, 1, 'both parents');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • (type, id) pairs cannot have foreign keys
  • Exclusive nullable foreign keys plus a CHECK keep integrity
  • A supertype table scales to many parent types
  • Pick by number and stability of parent types

Common mistakes

  • Using polymorphic pairs and never cleaning orphans
  • Forgetting the exactly-one CHECK with nullable foreign keys

Follow-ups

  • How would you query all comments with their parent titles?
  • How do ORMs usually implement polymorphic relations?

Tips

  • Name the integrity trade-off of each option
207.sql-0207Mediummid

A product team wants to track every change to a customer's address over time. How would you model it?

Keep address history in its own table with customer_id, the address fields, valid_from and valid_to (NULL for the current one). The current address is the row with valid_to IS NULL, which a partial unique index can limit to one per customer. This is the Type 2 slowly changing dimension pattern from data warehousing.

Full answer
sql
CREATE TABLE addresses (customer_id INTEGER, city TEXT, valid_from TEXT NOT NULL, valid_to TEXT);
CREATE UNIQUE INDEX one_current ON addresses(customer_id) WHERE valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Madrid', '2025-01-01', NULL);
BEGIN;
UPDATE addresses SET valid_to = '2026-03-01' WHERE customer_id = 1 AND valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Lisbon', '2026-03-01', NULL);
COMMIT;
SELECT city FROM addresses WHERE customer_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');
city
Madrid

Changing an address closes the current row and inserts a new one, ideally in one transaction. The partial unique index rejects a second open row for the same customer.

"Where did this customer live on 15 February?" becomes a range query: valid_from <= d AND (valid_to IS NULL OR valid_to > d). Half-open ranges, where valid_to is exclusive, avoid double-counting on the switch day.

Alternatives include an audit log table filled by triggers (good for "who changed what", weaker for as-of queries) and PostgreSQL range types with an exclusion constraint that forbids overlapping periods (not run here).

sql
CREATE TABLE addresses (customer_id INTEGER, city TEXT, valid_from TEXT NOT NULL, valid_to TEXT);
CREATE UNIQUE INDEX one_current ON addresses(customer_id) WHERE valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Madrid', '2025-01-01', NULL);
BEGIN;
UPDATE addresses SET valid_to = '2026-03-01' WHERE customer_id = 1 AND valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Lisbon', '2026-03-01', NULL);
COMMIT;
SELECT city FROM addresses WHERE customer_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Store history rows with valid_from and valid_to
  • Current row has valid_to IS NULL
  • A partial unique index allows one current row
  • Use half-open ranges for as-of queries

Common mistakes

  • Overwriting the address and losing history
  • Inclusive end dates that overlap on the change day

Follow-ups

  • How would you prevent overlapping periods?
  • How does an audit log differ from a history table?

Tips

  • Mention the Type 2 SCD name
208.sql-0208Mediummid

When would you use a star schema, and how does it differ from a normalized OLTP schema?

A star schema has a central fact table of measurable events (sales lines with quantity and amount) surrounded by denormalized dimension tables (date, product, customer, store). It suits analytical queries that filter and group by many attributes. OLTP schemas are normalized for consistent, concurrent writes; star schemas trade that for simple, fast reads.

Full answer

Fact table: one row per event at a chosen grain, such as "one row per order line". It holds foreign keys to dimensions and numeric measures.

Dimension tables: descriptive attributes, often flattened. A product dimension might carry category and brand directly instead of separate tables, so a report needs one join per dimension, not a chain.

A date dimension (one row per day with year, quarter, week, holiday flag) makes calendar grouping a simple join and keeps business definitions such as fiscal quarters in one place.

The design steps commonly taught:

  1. Choose the business process.
  2. Declare the grain.
  3. Pick dimensions.
  4. Pick facts (measures).

Getting the grain wrong is the classic mistake. Mixing order-level and line-level facts in one table double-counts order shipping fees.

Key points

  • Fact tables hold events and measures at a declared grain
  • Dimension tables hold descriptive, often denormalized attributes
  • A date dimension simplifies calendar logic
  • OLTP favours normalized writes; star schemas favour reads

Common mistakes

  • Mixing grains in one fact table
  • Snowflaking dimensions without need and adding joins

Follow-ups

  • What is a slowly changing dimension?
  • How would you model shipping fees charged per order?

Tips

  • Declare the grain first
209.sql-0209Easyfresher

Why might storing an age column instead of a birth date be a modeling mistake?

Age changes every year, so a stored age becomes wrong without any update, while a birth date stays true. Store the stable fact and compute the derived value at query time, or in a view. The same applies to 'days since signup' or 'is overdue' flags that depend on the current date.

Full answer

A stored age is correct only on the day it was written. A year later, every row is off by one unless a job rewrites them, and that job is one more thing to fail.

Store birth_date and compute age when needed, as shown in the date questions in this bank. A view can expose it as if it were a column:

sql
CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, birth_date TEXT);
INSERT INTO people VALUES (1, 'Asha', '1996-12-01'), (2, 'Ben', '2001-06-15');
CREATE VIEW people_with_age AS
SELECT id, name, birth_date,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', birth_date) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', birth_date)) AS age
FROM people;
SELECT name, age FROM people_with_age ORDER BY id;
nameage
Asha30
Ben25

The view uses a fixed reference date here so the output is stable; in practice it would use date('now').

Values that depend on "now" cannot be generated columns either, because generated columns must be deterministic. Values derived only from the row itself, such as qty * unit_price, are fine to generate or store.

sql
CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, birth_date TEXT);
INSERT INTO people VALUES (1, 'Asha', '1996-12-01'), (2, 'Ben', '2001-06-15');
CREATE VIEW people_with_age AS
SELECT id, name, birth_date,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', birth_date) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', birth_date)) AS age
FROM people;
SELECT name, age FROM people_with_age ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Store stable facts, derive time-dependent values
  • A stored age silently becomes wrong
  • Views can expose computed values like columns
  • Generated columns cannot depend on the current date

Common mistakes

  • Storing age, tenure or overdue flags that depend on today
  • Running nightly jobs to refresh values that could be computed

Follow-ups

  • How would you index a query for people turning 18 this month?
  • Which derived values are safe to store?

Tips

  • Ask whether the value depends on the current date
210.sql-0210Hardsenior

What is the entity-attribute-value (EAV) pattern, and what problems does it cause?

EAV stores attributes as rows: entity_id, attribute name, value. It allows any attribute without schema changes, but loses types, NOT NULL and CHECK constraints, and foreign keys on values, and simple questions need one join or pivot per attribute. A JSON column, or real columns for common attributes plus JSON for the rare ones, is usually a better trade-off.

Full answer
sql
CREATE TABLE attrs (entity_id INTEGER, name TEXT, value TEXT);
INSERT INTO attrs VALUES (1, 'colour', 'red'), (1, 'weight', '12'), (2, 'colour', 'blue'), (2, 'weight', '9');
SELECT entity_id,
       MAX(CASE WHEN name = 'colour' THEN value END) AS colour,
       MAX(CASE WHEN name = 'weight' THEN value END) AS weight,
       typeof(MAX(CASE WHEN name = 'weight' THEN value END)) AS weight_type
FROM attrs GROUP BY entity_id ORDER BY entity_id;
entity_idcolourweightweight_type
1red12text
2blue9text

Reading two attributes already needs a pivot, every value is text, and nothing stops 'weight' being spelled 'wieght' or stored as 'heavy'.

Problems in larger systems:

  • No types: numbers compare as text unless cast on every query.
  • No constraints: required attributes cannot be enforced.
  • Query cost: each attribute in a filter is another self join or aggregation.

EAV can fit truly sparse, user-defined attributes, such as custom fields in a SaaS form builder, when the system mostly stores and displays them. For product catalogues with mostly known attributes, typed columns for the common ones plus a JSON column for the rest keep integrity where it matters.

sql
CREATE TABLE attrs (entity_id INTEGER, name TEXT, value TEXT);
INSERT INTO attrs VALUES (1, 'colour', 'red'), (1, 'weight', '12'), (2, 'colour', 'blue'), (2, 'weight', '9');
SELECT entity_id,
       MAX(CASE WHEN name = 'colour' THEN value END) AS colour,
       MAX(CASE WHEN name = 'weight' THEN value END) AS weight,
       typeof(MAX(CASE WHEN name = 'weight' THEN value END)) AS weight_type
FROM attrs GROUP BY entity_id ORDER BY entity_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • EAV stores attributes as rows
  • It loses types and constraints
  • Each attribute in a query adds a join or pivot
  • JSON plus typed common columns is often better

Common mistakes

  • Choosing EAV to avoid migrations and paying for it in every query
  • Comparing numeric EAV values as text

Follow-ups

  • How would you index a JSON attribute?
  • When is EAV acceptable?

Tips

  • Show the pivot needed to read two attributes
211.sql-0211Easyfresher

What is an index, and how can you tell whether a query uses one in SQLite?

An index is a separate sorted structure, usually a B-tree, that maps column values to rows so the engine can find matches without reading the whole table. In SQLite, EXPLAIN QUERY PLAN shows SCAN for a full table read and SEARCH ... USING INDEX when an index narrows the lookup.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

Without an index on user_id, the engine must read every row:

sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
text
QUERY PLAN
SCAN events

After creating one, the plan changes to a search:

sql
CREATE INDEX events_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
text
QUERY PLAN
SEARCH events USING INDEX events_user (user_id=?)

The table is a heap of 2,000 rows; the index keeps user_id values sorted with pointers back to each row, so finding user 7 takes a few page reads instead of 2,000 row checks.

Indexes cost disk space and slow down every INSERT, UPDATE and DELETE that touches the indexed columns, because the index must be updated too. Add them for real query patterns, not for every column.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;

CREATE INDEX events_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • An index is a sorted lookup structure, usually a B-tree
  • EXPLAIN QUERY PLAN shows SCAN or SEARCH
  • Indexes speed reads and slow writes
  • Create indexes for actual query patterns

Common mistakes

  • Indexing every column 'just in case'
  • Assuming an index is used without checking the plan

Follow-ups

  • Why might an index not be used even when it exists?
  • What is a covering index?

Tips

  • Show a plan before and after
212.sql-0212Mediummid

An index exists on (user_id, created). Which of these filters can use it: user_id = 7, created > '2026-03-01', or both together?

A composite index is sorted by its first column, then by the second within each first value. user_id = 7 can use it, and user_id = 7 AND created > '2026-03-01' can use both columns. A filter on created alone cannot seek into it, because created values are scattered across all user_id groups.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX events_user_created ON events(user_id, created);
sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;
text
QUERY PLAN
SEARCH events USING INDEX events_user_created (user_id=?)
sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7 AND created > '2026-03-01';
text
QUERY PLAN
SEARCH events USING INDEX events_user_created (user_id=? AND created>?)
sql
EXPLAIN QUERY PLAN SELECT * FROM events WHERE created > '2026-03-01';
text
QUERY PLAN
SCAN events

The first two plans search the index; the second uses both columns (user_id=? AND created>?). The third falls back to a scan, because the index offers no shortcut to a range of created values.

The rule of thumb is "equality columns first, then the range column". An index on (created, user_id) would serve the date filter alone, but for "user 7 after 1 March" it would scan every date after 1 March and check users.

SQLite can sometimes use a skip-scan on the second column when the first has very few distinct values and statistics from ANALYZE exist; do not rely on it for design.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX events_user_created ON events(user_id, created);

EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7;

EXPLAIN QUERY PLAN SELECT * FROM events WHERE user_id = 7 AND created > '2026-03-01';

EXPLAIN QUERY PLAN SELECT * FROM events WHERE created > '2026-03-01';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Composite indexes sort by the first column, then the next
  • Filters must use a leading prefix of the columns
  • Put equality columns before range columns
  • A filter on the second column alone usually cannot seek

Common mistakes

  • Creating (a, b) and expecting it to serve WHERE b = ?
  • Putting the range column first

Follow-ups

  • Would you create a second index on created alone?
  • How does ORDER BY interact with a composite index?

Tips

  • Use the phone-book analogy: last name, then first name
213.sql-0213Mediummid

What is a covering index, and how does it show up in a SQLite query plan?

A covering index contains every column a query needs, so the engine answers from the index alone without visiting the table rows. SQLite reports USING COVERING INDEX. Adding a frequently selected column to the end of an index can turn a lookup plus table reads into an index-only read.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

The index has user_id only, so fetching amount requires a trip to the table for each match:

sql
CREATE INDEX ev_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;
text
QUERY PLAN
SEARCH events USING INDEX ev_user (user_id=?)

With amount added to the index, the query is satisfied from the index:

sql
CREATE INDEX ev_user_amount ON events(user_id, amount);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;
text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_user_amount (user_id=?)

The saving is largest when many rows match, since each table visit is a random read. PostgreSQL calls this an index-only scan and lets you add non-key payload columns with INCLUDE (amount); it also depends on the visibility map being current, which VACUUM maintains (not run here).

Covering indexes are wider, so they cost more space and write work. Use them for hot queries, not as a default.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

CREATE INDEX ev_user ON events(user_id);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;

CREATE INDEX ev_user_amount ON events(user_id, amount);
EXPLAIN QUERY PLAN SELECT user_id, amount FROM events WHERE user_id = 7;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A covering index contains all columns the query uses
  • SQLite shows USING COVERING INDEX
  • It avoids reading the table rows
  • PostgreSQL supports INCLUDE columns for this

Common mistakes

  • Adding many columns to every index
  • Selecting * and wondering why the index is not covering

Follow-ups

  • How would you cover SELECT SUM(amount) WHERE user_id = ?
  • What does INCLUDE add over a longer key?

Tips

  • Compare the two plans side by side
214.sql-0214Mediummid

A query filters WHERE substr(created, 1, 7) = '2026-02' and is slow even though created is indexed. Why, and how do you rewrite it?

Wrapping the indexed column in a function hides it from the index, so the engine must compute the expression for every row. Rewrite the filter as a range on the bare column: created >= '2026-02-01' AND created < '2026-03-01'. Conditions the index can use are called sargable.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX ev_created ON events(created);
sql
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02';
text
QUERY PLAN
SCAN events USING COVERING INDEX ev_created

The plan is a SCAN. SQLite does read the index, because it covers COUNT(*), but it reads every entry and evaluates substr on each one. Rewritten as a half-open range, the plan becomes a SEARCH that touches only February:

sql
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01';
text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_created (created>? AND created<?)

Other common non-sargable shapes:

  • WHERE amount + 10 > 50 (write amount > 40)
  • WHERE lower(email) = ? (use an expression index, or store normalized values)
  • WHERE date(created) = ? on timestamps (use a range)

Both versions return the same rows here; only the work differs.

sql
SELECT (SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02') AS by_substr,
       (SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01') AS by_range;
by_substrby_range
616616
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX ev_created ON events(created);

EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02';

EXPLAIN QUERY PLAN SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01';

SELECT (SELECT COUNT(*) FROM events WHERE substr(created, 1, 7) = '2026-02') AS by_substr,
       (SELECT COUNT(*) FROM events WHERE created >= '2026-02-01' AND created < '2026-03-01') AS by_range;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Functions on an indexed column usually block index use
  • Rewrite as a range on the bare column
  • Sargable means the predicate can use an index
  • Expression indexes help when the function is unavoidable

Common mistakes

  • Formatting dates in WHERE clauses
  • Doing arithmetic on the column instead of the constant

Follow-ups

  • How would you index lower(email)?
  • Is created LIKE '2026-02%' sargable in SQLite?

Tips

  • Show the plan for both forms
215.sql-0215Mediummid

How do you make a case-insensitive email lookup use an index?

Create an index on the expression itself, CREATE INDEX ... ON users(lower(email)), and query with exactly the same expression, WHERE lower(email) = lower(?). SQLite and PostgreSQL both support expression indexes. Alternatives are storing emails already lowercased or, in SQLite, declaring the column COLLATE NOCASE.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email_lower ON users(lower(email));
EXPLAIN QUERY PLAN SELECT id FROM users WHERE lower(email) = lower('Ana@X.com');
text
QUERY PLAN
SEARCH users USING INDEX users_email_lower (<expr>=?)

The plan uses the expression index because the WHERE clause matches the indexed expression exactly. A slightly different expression, such as upper(email), would not match.

Making it unique also prevents 'Ana@x.com' and 'ana@x.com' from both being registered:

sql
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
CREATE UNIQUE INDEX u2_email ON u2(lower(email));
INSERT INTO u2 (email) VALUES ('Ana@x.com');
INSERT INTO u2 (email) VALUES ('ana@x.com');
-- error on purpose
text
Error: UNIQUE constraint failed: index 'u2_email'

PostgreSQL supports the same index form, and the citext extension offers a case-insensitive text type (not run here).

Whichever option you choose, apply it everywhere emails are compared: sign-up, login, password reset and admin search. A lookup path that skips the lowercasing will miss existing accounts or allow duplicates through another door.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email_lower ON users(lower(email));
EXPLAIN QUERY PLAN SELECT id FROM users WHERE lower(email) = lower('Ana@X.com');

-- error on purpose
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
CREATE UNIQUE INDEX u2_email ON u2(lower(email));
INSERT INTO u2 (email) VALUES ('Ana@x.com');
INSERT INTO u2 (email) VALUES ('ana@x.com');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Index the expression the query uses
  • The WHERE expression must match the index expression
  • A unique expression index enforces case-insensitive uniqueness
  • Storing normalized values is an alternative

Common mistakes

  • Indexing email and querying lower(email)
  • Normalizing case in the app for inserts but not for lookups

Follow-ups

  • How would COLLATE NOCASE on the column compare?
  • Can a generated column replace the expression index?

Tips

  • Mention the uniqueness benefit
216.sql-0216Mediummid

How can a partial index help a queue table where only a few rows are pending?

Index only the rows the hot query reads: CREATE INDEX ... ON jobs(created) WHERE status = 'pending'. The index stays tiny while the table grows with finished jobs, and queries with the same WHERE condition can use it. Both SQLite and PostgreSQL support partial indexes.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

Only 40 of 2,000 rows are refunds here, standing in for pending jobs:

sql
CREATE INDEX ev_refunds ON events(created) WHERE kind = 'refund';
EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'refund' ORDER BY created LIMIT 5;
text
QUERY PLAN
SCAN events USING COVERING INDEX ev_refunds

The plan reads the partial index, which holds only the 40 refund rows, so even a full pass over it is cheap. The query's WHERE includes the index's condition, so the planner can use the small index and read rows already in created order. A query without kind = 'refund' cannot use it, because the index does not contain other rows.

Size matters: a full index on created would hold 2,000 entries; this one holds 40. For queue tables where most rows are 'done', that keeps inserts and lookups cheap.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

CREATE INDEX ev_refunds ON events(created) WHERE kind = 'refund';
EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'refund' ORDER BY created LIMIT 5;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A partial index covers only rows matching its WHERE
  • Queries must imply the same condition to use it
  • Ideal for small hot subsets such as pending work
  • Smaller indexes are cheaper to maintain

Common mistakes

  • Writing the query condition differently from the index condition
  • Using a partial index for queries that need all rows

Follow-ups

  • How would you pick the next job safely with several workers?
  • What other columns might the partial index include?

Tips

  • Mention the size benefit
217.sql-0217Mediummid

Should you index a boolean column such as is_active where 95 percent of rows are true?

Usually not for the common value: a query for is_active = true would read most of the table through the index, which is slower than a plain scan. An index helps only for the rare value, and then a partial index on that value is better. Selectivity, the fraction of rows a predicate returns, decides whether an index pays off.

Full answer

An index lookup costs a jump into the index plus a read of each matching table row. When a predicate matches most rows, those reads are scattered and add up to more work than scanning the table once in order. Planners estimate this from statistics and often choose a scan anyway.

Good candidates are selective predicates: ids, emails, foreign keys with many distinct values, and rare statuses.

For the rare 5 percent:

text
CREATE INDEX users_inactive ON users(id) WHERE NOT is_active;

A low-cardinality column can still be useful as the first column of a composite index when every query filters on it, for example (tenant_id, created) in a multi-tenant table.

Measure with real data volumes; a plan on a 10-row test table says little about production.

Key points

  • Selectivity decides whether an index helps
  • Indexes on common values are often ignored
  • Partial indexes suit rare values
  • Low-cardinality columns can lead a composite index

Common mistakes

  • Indexing booleans and status columns by reflex
  • Judging plans on tiny test tables

Follow-ups

  • How does the planner estimate selectivity?
  • When would a bitmap index help (in engines that have one)?

Tips

  • Explain the random-read cost
218.sql-0218Mediummid

How can an index remove the sort step for ORDER BY ... LIMIT, and how does the plan show it?

If an index is sorted the same way as the ORDER BY, the engine can read the index in order and stop after LIMIT rows. Without it, the engine must read all matching rows and sort them, which SQLite reports as USE TEMP B-TREE FOR ORDER BY. An index on (user_id, created) serves WHERE user_id = ? ORDER BY created DESC LIMIT 10.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

Without a suitable index, every row is read and sorted:

sql
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;
text
QUERY PLAN
SCAN events
USE TEMP B-TREE FOR ORDER BY

With an index on (user_id, created), the rows for user 7 are already in date order:

sql
CREATE INDEX ev_user_created ON events(user_id, created);
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;
text
QUERY PLAN
SEARCH events USING COVERING INDEX ev_user_created (user_id=?)

The temp B-tree line is gone. The engine walks the index backwards from the latest date for user 7 and stops after 10 rows. For "latest N items per user" pages, this index shape is the standard answer.

The index must match the filter and sort: (created, user_id) would not avoid the sort for one user, because its rows are scattered through the index.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;

CREATE INDEX ev_user_created ON events(user_id, created);
EXPLAIN QUERY PLAN SELECT id, created FROM events WHERE user_id = 7 ORDER BY created DESC LIMIT 10;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • An index in ORDER BY order avoids sorting
  • SQLite shows USE TEMP B-TREE FOR ORDER BY when it sorts
  • With LIMIT, the engine can stop early
  • Put the equality filter first, then the sort column

Common mistakes

  • Indexing the sort column alone when a filter comes first
  • Ignoring sort cost on pages that show 'latest' items

Follow-ups

  • Can the same index serve ORDER BY created ASC?
  • How does this relate to keyset pagination?

Tips

  • Point out the missing temp B-tree line
219.sql-0219Hardsenior

Can SQLite use indexes for WHERE user_id = 7 OR kind = 'refund' when each column has its own index?

Yes: SQLite can run a MULTI-INDEX OR plan, searching each index separately and combining the row ids, but only when every OR branch has a usable index. PostgreSQL does the same with a BitmapOr of bitmap index scans. Rewriting as UNION is the manual equivalent.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX ev_user ON events(user_id);
CREATE INDEX ev_kind ON events(kind);
sql
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 7 OR kind = 'refund';
text
QUERY PLAN
MULTI-INDEX OR
  INDEX 1
    SEARCH events USING INDEX ev_user (user_id=?)
  INDEX 2
    SEARCH events USING INDEX ev_kind (kind=?)

The plan shows a MULTI-INDEX OR with one index search per branch. Dropping the index on kind forces a full scan, because the second branch cannot be answered from an index:

sql
DROP INDEX ev_kind;
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 8 OR kind = 'refund';
text
QUERY PLAN
SCAN events

A UNION rewrite does the same job by hand and is sometimes clearer or faster on engines that handle OR poorly:

text
SELECT id FROM events WHERE user_id = 7
UNION
SELECT id FROM events WHERE kind = 'refund';

The general lesson: an OR is only as indexable as its least indexable branch.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
CREATE INDEX ev_user ON events(user_id);
CREATE INDEX ev_kind ON events(kind);

EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 7 OR kind = 'refund';

DROP INDEX ev_kind;
EXPLAIN QUERY PLAN SELECT id FROM events WHERE user_id = 8 OR kind = 'refund';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SQLite can combine indexes for OR (MULTI-INDEX OR)
  • Every branch needs a usable index
  • PostgreSQL uses BitmapOr for the same idea
  • UNION is a manual alternative

Common mistakes

  • Expecting an index on one OR branch to help
  • Rewriting with UNION ALL and getting duplicates

Follow-ups

  • How would a composite index help an AND instead?
  • When is UNION faster than OR?

Tips

  • State the least-indexable-branch rule
220.sql-0220Mediummid

In PostgreSQL, what is the difference in purpose between EXPLAIN and EXPLAIN ANALYZE?

EXPLAIN shows the planner's chosen plan with estimated costs and row counts, without running the query. EXPLAIN ANALYZE runs the query and adds actual row counts and timings for each node. Big gaps between estimated and actual rows point to stale or missing statistics. Because ANALYZE executes the statement, wrap data-changing statements in a transaction and roll back.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;
sql
EXPLAIN (COSTS OFF) SELECT id FROM events WHERE kind = 'refund';
text
Seq Scan on events
  Filter: (kind = 'refund'::text)
sql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT id FROM events WHERE kind = 'refund';
text
Seq Scan on events (actual rows=40 loops=1)
  Filter: (kind = 'refund'::text)
  Rows Removed by Filter: 1960

The ANALYZE output adds actual rows for each node (timing is turned off here so the output is stable). Estimates and actuals that differ by orders of magnitude often explain a bad plan: the planner picked a nested loop for "10 rows" that turned out to be 100,000.

For an UPDATE or DELETE:

text
BEGIN;
EXPLAIN ANALYZE DELETE FROM events WHERE kind = 'refund';
ROLLBACK;

BUFFERS adds page reads, which show whether data came from cache. SQLite's EXPLAIN QUERY PLAN is closer to plain EXPLAIN: it shows the plan without running it.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INTEGER, kind TEXT, created TEXT, amount INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
INSERT INTO events SELECT i, i % 100, CASE WHEN i % 50 = 0 THEN 'refund' ELSE 'purchase' END,
       date('2026-01-01', '+' || (i % 90) || ' days'), i % 37 FROM n;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • EXPLAIN shows estimates without running
  • EXPLAIN ANALYZE runs the query and shows actuals
  • Compare estimated and actual rows
  • Roll back when analyzing data-changing statements

Common mistakes

  • Running EXPLAIN ANALYZE on a DELETE outside a transaction
  • Reading costs as milliseconds

Follow-ups

  • What does ANALYZE (the command) do?
  • What does BUFFERS show?

Tips

  • Mention the estimate-versus-actual check