SQL Interview Questions

Practice relational query design, indexes, transactions, pagination, and database troubleshooting with practical SQL examples.

Explained SQL questions

How do joins, common table expressions, and window functions help analyze related rows?

A join combines rows using a relationship; a common table expression names a query result for a single statement; a window function computes across a related set of rows without collapsing them like GROUP BY. Choose the operation that matches whether you need detail rows, grouped rows, or a calculation beside each row.

Example

WITH customer_totals AS (
  SELECT customer_id, SUM(amount) AS total_spend
  FROM orders
  WHERE status = 'paid'
  GROUP BY customer_id
)
SELECT customer_id, total_spend,
       RANK() OVER (ORDER BY total_spend DESC) AS spend_rank
FROM customer_totals;

Why it works

The CTE isolates the paid-order aggregation. RANK adds an ordering over those customer totals while retaining one row per customer.

Common mistakes

  • Turning a LEFT JOIN into an accidental inner join by filtering the nullable side in WHERE.
  • Selecting non-aggregated columns that are not valid for the database's grouping rules.
  • Assuming a CTE is always materialized or always faster; inspect the database's optimizer behavior.

Follow-up questions

  • How do RANK, DENSE_RANK, and ROW_NUMBER differ?
  • When can a join multiply rows unexpectedly?

Real-world use

Use these tools for reporting and ranking while checking join cardinality and validating results against known cases.

Further reading: MySQL: JOIN clauses · MySQL: Window functions

How do indexes and execution plans guide SQL query optimization?

An index can reduce the rows or pages a query must examine, but it consumes storage and adds work to inserts and updates. Use EXPLAIN (and, where safe and supported, an execution-analysis command) to inspect access paths, estimated rows, join order, and sort or temporary work. A composite index is most useful when its leading columns align with the query's predicates and ordering; verify this against the real workload.

Example

CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at);

EXPLAIN
SELECT id, created_at, status
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Why it works

The index begins with the equality predicate and then the ordering column, which may allow a narrower ordered lookup. The optimizer's plan and representative data determine whether it actually helps.

Common mistakes

  • Adding an index for every filtered column without considering write load and selectivity.
  • Assuming a query is fast because it uses an index.
  • Running a costly analyze command on production without checking its impact.

Follow-up questions

  • What is a covering index?
  • Why might a query optimizer choose a table scan?

Real-world use

Compare plans and latency before and after changes on representative data, and keep pagination bounded for large tables.

Further reading: MySQL: EXPLAIN · MySQL: Multiple-column indexes

How do transactions, isolation levels, and deadlocks affect concurrent SQL updates?

A transaction groups changes into a unit that can commit or roll back. Isolation controls which concurrent changes a transaction may observe; stronger isolation can reduce anomalies but may increase contention. Deadlocks occur when transactions hold locks that each other needs. Keep transactions short, access rows in a consistent order where practical, and make retry behavior safe for the operation.

Example

START TRANSACTION;
UPDATE accounts SET balance = balance - 25 WHERE id = 1;
UPDATE accounts SET balance = balance + 25 WHERE id = 2;
COMMIT;

-- If a deadlock is reported, roll back and retry the whole
-- idempotent transfer operation with a bounded retry policy.

Why it works

The transaction ensures both balance changes succeed or neither does. A retry starts from a clean transaction state; it must not repeat an externally visible side effect.

Common mistakes

  • Assuming every database uses the same isolation defaults or anomaly definitions.
  • Retrying only the last statement after a deadlock.
  • Keeping a transaction open while waiting on unrelated network calls.

Follow-up questions

  • What consistency anomalies can occur at your database's default isolation?
  • How do you make a payment or transfer retry-safe?

Real-world use

Review lock waits and deadlock reports during incidents; minimize transaction scope and define idempotency at the application boundary.

Further reading: MySQL: InnoDB transaction model · MySQL: Deadlocks

How would you model a relational schema and paginate a large result set?

Normalize data to avoid update anomalies and represent relationships with keys and constraints; denormalize only for a measured access pattern with a consistency plan. Offset pagination is simple, but deep offsets can require scanning and discarding many rows. Keyset pagination uses a stable ordered cursor, such as the last created_at and id pair, and works best with a matching index.

Example

SELECT id, created_at, status
FROM orders
WHERE customer_id = ?
  AND (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT 25;

Why it works

The unique id breaks timestamp ties, creating a deterministic cursor. A composite index beginning with customer_id and then the cursor/order columns can support the access pattern.

Common mistakes

  • Ordering only by a non-unique timestamp, which can skip or repeat rows.
  • Denormalizing without defining how duplicate values stay consistent.
  • Using unvalidated values to construct SQL identifiers or sort clauses.

Follow-up questions

  • What do you trade away with keyset pagination?
  • Which constraints should be enforced by the database?

Real-world use

Use parameterized values and a deterministic cursor for large feeds; confirm index order and null-handling against the target database.

Further reading: MySQL: InnoDB indexes · OWASP: SQL Injection Prevention

How can you return the top three paid orders for each customer?

A window function can rank rows within each customer partition while retaining each order's columns. Filter the ranked rows in an outer query because the window result is computed after the WHERE clause at the same query level. Use ROW_NUMBER for at most three rows per customer; choose RANK or DENSE_RANK if ties should share a rank and may return more rows.

Example

WITH ranked_orders AS (
  SELECT id, customer_id, total,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id
           ORDER BY total DESC, id
         ) AS position
  FROM orders
  WHERE status = 'paid'
)
SELECT id, customer_id, total
FROM ranked_orders
WHERE position <= 3
ORDER BY customer_id, position;

Why it works

PARTITION BY restarts the row numbering for each customer, and the unique id makes tie ordering deterministic. The outer query filters the calculated position without collapsing order rows.

Common mistakes

  • Using GROUP BY when the result must retain individual order columns.
  • Filtering the window alias in the same query block's WHERE clause.
  • Leaving the ORDER BY incomplete when deterministic tie handling matters.

Follow-up questions

  • When would RANK return more than three rows for a customer?
  • Which index could support filtering paid orders and grouping by customer?

Real-world use

Per-group ranking is useful for leaderboards, top products by category, and latest records per account; verify plans and indexes against the target database.

Further reading: MySQL: Window functions · MySQL: WITH (CTE) syntax