Query Speed, Indexes and a Mock Interview Round

SQL Interview Problems: 12 Classic Questions Solved · Counting, Traps and Speed · 8 min read · Updated

Why a query is slow

  1. You have a slow query with a filter on a big table.
  2. Ask the database for its plan with EXPLAIN instead of guessing.
  3. If the plan says SCAN, every row of the table is being read.
  4. Create an index on the filtered column, and keep that column free of functions in the condition.
  5. Run the plan again. SEARCH USING INDEX means the database jumps straight to the rows.

Interviewers for backend and data roles often finish with: "This query is slow. What would you do?" You do not need to be a database administrator to answer well. You need a few ideas and a way to look at the facts instead of guessing. This lesson shows how to read a query plan, the most common reason an index is ignored, and then gives you a short mock round to practise everything in the course.

Ask the database how it will run a query

Most databases can show the plan they choose, with EXPLAIN (SQLite uses EXPLAIN QUERY PLAN). The word SCAN means that the database reads every row of the table. SEARCH ... USING INDEX means that it jumps straight to the matching rows. On a table of 14 rows the difference is invisible, but on millions of rows it is the difference between a quick answer and a timeout.

EXPLAIN QUERY PLAN
SELECT * FROM sales WHERE employee_id = 6;
plan
SCAN sales

There is no index on employee_id, so the database must scan the whole table. Add one and run the same query again.

CREATE INDEX idx_sales_employee ON sales (employee_id);

EXPLAIN QUERY PLAN
SELECT * FROM sales WHERE employee_id = 6;
plan
SEARCH sales USING INDEX idx_sales_employee (employee_id=?)

Now the plan says SEARCH sales USING INDEX idx_sales_employee (employee_id=?). An index is like the index of a book: a sorted list that points to the rows. The cost is that every insert and update must also update the index, and the index takes space. So you add indexes for the columns that you filter, join or sort by often, not for every column.

The classic reason an index is ignored

Suppose there is an index on sale_date and you want the sales of March 2024. A natural way is to wrap the date in a function.

CREATE INDEX idx_sales_date ON sales (sale_date);

EXPLAIN QUERY PLAN
SELECT * FROM sales
WHERE strftime('%Y-%m', sale_date) = '2024-03';
plan
SCAN sales

The plan says SCAN sales. The index exists, but it is sorted by the date, not by the result of strftime. To apply the function the database must read every row. Rewrite the condition as a range on the plain column:

CREATE INDEX idx_sales_date ON sales (sale_date);

EXPLAIN QUERY PLAN
SELECT * FROM sales
WHERE sale_date >= '2024-03-01' AND sale_date < '2024-04-01';
plan
SEARCH sales USING INDEX idx_sales_date (sale_date>? AND sale_date<?)

Now the index is used: SEARCH ... (sale_date>? AND sale_date<?). The rule to remember is simple: keep the column bare on one side of the comparison, and do the calculation on the other side. The same applies to WHERE YEAR(date) = 2024, WHERE LOWER(email) = ... and WHERE salary * 12 > 1000000 in other engines.

A short list of speed habits

  • Select only the columns you need. SELECT * moves more data and blocks some optimisations.
  • Filter early. Put conditions in WHERE instead of filtering after a big join.
  • Index the columns used in WHERE, JOIN ... ON and ORDER BY on big tables, and check the plan.
  • Avoid a leading wildcard in LIKE '%text', which cannot use a normal index.
  • Do not run a query in a loop from your program when one query with a join can do it.
  • Measure on realistic data. A query that is fast on 14 rows may be slow on 14 million.

Mock round: four problems

Set a timer for fifteen minutes. Try each problem before you read the answer. Use the practice database, and say your steps out loud, as in lesson 1.

Problem A. Which department has the highest average salary, and what is the average? Think: group, average, sort, one row.

SELECT d.name, ROUND(AVG(e.salary)) AS avg_salary
FROM departments d
JOIN employees e ON e.dept_id = d.id
GROUP BY d.id
ORDER BY avg_salary DESC
LIMIT 1;
name        | avg_salary
Engineering | 123000

Problem B. Show the second highest salary in each department, with the person or people who earn it. Think: rank inside a department, and the tie in Sales.

WITH r AS (
  SELECT dept_id, name, salary,
         DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rk
  FROM employees
  WHERE salary IS NOT NULL
)
SELECT d.name AS dept, r.name, r.salary
FROM r
JOIN departments d ON d.id = r.dept_id
WHERE r.rk = 2
ORDER BY d.name, r.name;
dept        | name       | salary
Engineering | Nia Okoye  | 130000
Finance     | Chloe Wu   | 72000
HR          | Ella Stone | 55000
Sales       | Priya Nair | 70000
Sales       | Tom Hill   | 70000

Two people appear for Sales because Priya and Tom tie at 70000, and DENSE_RANK treats them equally. Jack Reed's missing salary is removed before ranking.

Problem C. Which employees sold more than the average total of a seller? Think: a total per employee first, then the average of those totals, then compare.

SELECT employee_id, SUM(amount) AS total
FROM sales
GROUP BY employee_id
HAVING SUM(amount) > (
  SELECT AVG(t) FROM (
    SELECT SUM(amount) AS t FROM sales GROUP BY employee_id
  )
)
ORDER BY total DESC;
employee_id | total
6           | 6900

The three totals are 6900, 3600 and 2800, and their average is 4433. Only employee 6 is above it. The inner SELECT AVG(t) FROM (...) needs the inner totals as a table, which is why there are two levels. Zoe Park has no sales, so she is not in the average. If she were counted as zero, the average would be lower, and employee 7 would be above it too. That is worth saying aloud.

Problem D. For the Sales department, show how far each person's salary is below the top salary of the department. Think: a window MAX over the department, minus the person's salary.

SELECT name, salary,
       MAX(salary) OVER (PARTITION BY dept_id) - salary AS gap_to_top
FROM employees
WHERE dept_id = 2
ORDER BY salary DESC, name;
name       | salary | gap_to_top
Omar Ali   | 110000 | 0
Priya Nair | 70000  | 40000
Tom Hill   | 70000  | 40000
Zoe Park   | 65000  | 45000

How to use these problems

  • Cover the answer, write your query, run it, and compare the output, not the exact text. Different queries can be equally correct.
  • Redo a problem after two days without looking. The goal is to recognise the shape, not to memorise the words.
  • Then change the data. Add a tie, a NULL or an empty group and see whether your query still works.

This course cannot promise you a job, because hiring depends on much more than SQL. But if you can explain these twelve families of problems clearly, you will have the skills that most SQL rounds actually test. For more practice, read the SQL interview questions with model answers and keep your resume ready with the free ATS checker.

Your task

  1. Run EXPLAIN QUERY PLAN for a query that joins employees and departments. Write down what you see for each table.
  2. Rewrite WHERE strftime('%Y', hired) = '2022' so that an index on hired could be used.
  3. Solve problem B again for the second lowest salary in each department.
  4. Invent your own fifth problem with a tie and a NULL, and solve it.

How to check it worked

  • Your plan for the filter on employee_id changes from SCAN to SEARCH after you add the index.
  • The date range version of the March query uses the index and the function version does not.
  • Problem A returns Engineering with 123000.

Frequently asked questions

Does an index always make a query faster?

No. It helps filters, joins and sorts on large tables, but it slows down inserts and updates and uses space. Very small tables do not need one.

Why did my index not get used?

Common reasons are a function on the column in the WHERE, a leading wildcard in LIKE, a type mismatch between the column and the value, or a table so small that scanning is cheaper.

What should I say when asked how to speed up a query?

Say you would look at the plan with EXPLAIN, check the indexes for the filter and join columns, select fewer columns, and test on realistic data. Then explain the change you would try first.