SQL Interview Questions and Answers Part 9 - Performance and Indexes

SQL Interview Q&A · Part 9 of 10

In this post we are going to cover performance and indexes: what an index does to the execution plan, clustered and non-clustered indexes, sargable filters, composite and covering indexes, and how to read a plan. These are 7 real SQL interview questions, asked the way they come up on the job, and the last one is a scenario where a report that ran in 2 seconds suddenly takes 2 minutes.

Performance questions show if you can run SQL in production, not only write it. The interviewer wants to hear that you read the plan before you guess, and that you know why an index is or is not used.

Every query below is complete, so you can copy it, run it on the sample data and get exactly the output or the execution plan shown under it.

Part 9 of the SQL Server RealTime Questions Answers series on TechBrothersIT.

The short answer

Say this first

An index is a separate sorted structure that lets the database seek to the rows it needs instead of scanning the whole table, and EXPLAIN shows which one the optimizer chose. Keep filters sargable (bare column, date ranges), order composite indexes by the leading column rule, and cover hot queries instead of SELECT *. When a query suddenly slows down, compare estimated vs actual rows in the plan: stale statistics are the usual suspect.

Let's create some sample data

We use the TB Shop database: departments, employees, customers, products, orders, order items and payments. A plan on 12 orders tells us nothing, so this part adds two generated tables: big_customers with 2,000 customers and big_orders with 20,000 orders. The script ends with VACUUM ANALYZE, which cannot run inside a transaction, so run the script with psql -f, or run those two lines on their own.

Sample data - SQL script (PostgreSQL)
DROP TABLE IF EXISTS payments;
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS employees;
DROP TABLE IF EXISTS departments;

CREATE TABLE departments (dept_id INT PRIMARY KEY, dept_name VARCHAR(20));
INSERT INTO departments VALUES (10, 'Sales'), (20, 'Engineering'), (30, 'HR'), (40, 'Finance');

CREATE TABLE employees (
  emp_id     INT PRIMARY KEY,
  name       VARCHAR(20),
  dept_id    INT,            -- NULL = not assigned yet
  manager_id INT,            -- NULL = top of the company
  salary     INT,
  hire_date  DATE
);
INSERT INTO employees VALUES
  (1, 'Aisha',  NULL, NULL, 150000, '2018-03-01'),
  (2, 'Omar',   20,   1,    120000, '2019-06-15'),
  (3, 'Lina',   20,   2,     90000, '2021-01-10'),
  (4, 'Ravi',   20,   2,     90000, '2022-04-05'),
  (5, 'Mei',    20,   2,     75000, '2024-09-01'),
  (6, 'Sara',   10,   1,     95000, '2020-02-20'),
  (7, 'Daniel', 10,   6,    105000, '2021-07-01'),
  (8, 'Fatima', 10,   6,     60000, '2023-11-12'),
  (9, 'John',   30,   1,     70000, '2019-09-30'),
  (10,'Zara',   NULL, 9,     55000, '2026-01-05');

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(20),
  city        VARCHAR(20),
  region      VARCHAR(10),    -- NULL = unknown
  email       VARCHAR(40)
);
INSERT INTO customers VALUES
  (1, 'Sara Khan',  'Toronto', 'East', 'sara@mail.com'),
  (2, 'Omar Ali',   'Dallas',  'West', 'omar@mail.com'),
  (3, 'Lina Park',  'Seattle', 'West', 'lina@mail.com'),
  (4, 'Mei Chen',   'Boston',  'East', 'mei@mail.com'),
  (5, 'Ravi Patel', 'Austin',  NULL,   'ravi@mail.com'),
  (6, 'Chen Wu',    'Denver',  'West', 'chen@mail.com'),
  (7, 'Sara K.',    'Toronto', 'East', 'sara@mail.com');

CREATE TABLE products (product_id INT PRIMARY KEY, product VARCHAR(20), category VARCHAR(15), price DECIMAL(10,2));
INSERT INTO products VALUES
  (1, 'Laptop',   'Electronics', 1200.00),
  (2, 'Monitor',  'Electronics',  300.00),
  (3, 'Keyboard', 'Accessories',   50.00),
  (4, 'Mouse',    'Accessories',   25.00),
  (5, 'Desk',     'Furniture',    400.00),
  (6, 'Chair',    'Furniture',    250.00);

CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2)
);
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05', 'Delivered', 1250.00),
  (1002, 2, '2026-01-18', 'Delivered',  300.00),
  (1003, 4, '2026-02-02', 'Delivered',  650.00),
  (1004, 1, '2026-02-14', 'Cancelled',   50.00),
  (1005, 3, '2026-02-20', 'Delivered', 1200.00),
  (1006, 4, '2026-03-03', 'Shipped',    275.00),
  (1007, 5, '2026-03-15', 'Delivered',  400.00),
  (1008, 2, '2026-04-01', 'Delivered',   75.00),
  (1009, 4, '2026-04-22', 'Delivered',  250.00),
  (1010, 1, '2026-05-09', 'Shipped',    300.00),
  (1011, 3, '2026-05-30', 'Cancelled',  400.00),
  (1012, 7, '2026-06-11', 'Delivered',   50.00);

CREATE TABLE order_items (order_id INT, product_id INT, qty INT, unit_price DECIMAL(10,2));
INSERT INTO order_items VALUES
  (1001, 1, 1, 1200.00), (1001, 3, 1, 50.00),
  (1002, 2, 1, 300.00),
  (1003, 5, 1, 400.00), (1003, 6, 1, 250.00),
  (1004, 3, 1, 50.00),
  (1005, 1, 1, 1200.00),
  (1006, 6, 1, 250.00), (1006, 4, 1, 25.00),
  (1007, 5, 1, 400.00),
  (1008, 4, 3, 25.00),
  (1009, 6, 1, 250.00),
  (1010, 2, 1, 300.00),
  (1011, 5, 1, 400.00),
  (1012, 3, 1, 50.00);

CREATE TABLE payments (payment_id INT PRIMARY KEY, order_id INT, paid_amount DECIMAL(10,2));
INSERT INTO payments VALUES
  (1, 1001, 1250.00), (2, 1002, 300.00), (3, 1003, 400.00), (4, 1003, 250.00), (5, 1005, 1200.00);

DROP TABLE IF EXISTS big_orders;
DROP TABLE IF EXISTS big_customers;

CREATE TABLE big_customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(30),
  region      VARCHAR(10)
);
INSERT INTO big_customers
SELECT g.n,
       CONCAT('Customer ', g.n),
       CASE g.n % 4 WHEN 0 THEN 'East' WHEN 1 THEN 'West' WHEN 2 THEN 'North' ELSE 'South' END
FROM generate_series(1, 2000) AS g(n);

-- 20,000 orders from 2019-01-01 to 2026-06-30, loaded in date order; 10 orders per customer, spread over the years
CREATE TABLE big_orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2),
  notes       VARCHAR(200)
);
INSERT INTO big_orders
SELECT 100000 + g.n,
       1 + g.n % 2000,
       CAST('2019-01-01' AS DATE) + CAST(FLOOR(g.n * 2737.0 / 20000) AS INT),
       CASE WHEN g.n % 10 = 0 THEN 'Cancelled' WHEN g.n % 10 IN (1, 2) THEN 'Shipped' ELSE 'Delivered' END,
       CAST(20 + (g.n * 37) % 980 AS DECIMAL(10,2)),
       CONCAT('Order ', 100000 + g.n, ': leave the parcel at the front desk if nobody answers the door')
FROM generate_series(1, 20000) AS g(n);

-- fresh statistics and visibility map (SQL Server: UPDATE STATISTICS).
-- VACUUM cannot run inside a transaction: run the script with psql -f, or run these two lines on their own.
VACUUM ANALYZE big_customers;
VACUUM ANALYZE big_orders;

Here are the first rows of big_orders. Notice the notes column: it is a long text column, and it matters when we talk about SELECT *.

big_ordersfirst 8 of 20000 rows
order_idcustomer_idorder_datestatusamountnotes
10000122019-01-01Shipped57.00Order 100001: leave the parcel at the front desk if nobody answers the door
10000232019-01-01Shipped94.00Order 100002: leave the parcel at the front desk if nobody answers the door
10000342019-01-01Delivered131.00Order 100003: leave the parcel at the front desk if nobody answers the door
10000452019-01-01Delivered168.00Order 100004: leave the parcel at the front desk if nobody answers the door
10000562019-01-01Delivered205.00Order 100005: leave the parcel at the front desk if nobody answers the door
10000672019-01-01Delivered242.00Order 100006: leave the parcel at the front desk if nobody answers the door
10000782019-01-01Delivered279.00Order 100007: leave the parcel at the front desk if nobody answers the door
10000892019-01-02Delivered316.00Order 100008: leave the parcel at the front desk if nobody answers the door

And big_customers, with one of four regions per customer.

big_customersfirst 8 of 2000 rows
customer_idnameregion
1Customer 1West
2Customer 2North
3Customer 3South
4Customer 4East
5Customer 5West
6Customer 6North
7Customer 7South
8Customer 8East

Question 1: Customer service looks up one customer's orders in a 20,000-row table and the query reads every row. What is an index, and how does it change the execution plan?

An index is a separate, sorted structure, usually a B-tree, that maps column values to the rows that hold them. It works like the index at the back of a book: you go straight to the page instead of reading every page.

big_orders1 row
orderscustomers
200002000

Customer service looks up customer 42. EXPLAIN shows the plan without running the query, and there is no index on customer_id yet.

SQL - No index yet: the plan is a Seq Scan
EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;
Execution plan (PostgreSQL 16)EXPLAIN output
Seq Scan on big_orders
  Filter: (customer_id = 42)

The plan is a Seq Scan with a Filter: read every row, then throw away the ones that don't match.

Now let's create an index on customer_id and ask again.

SQL - Create an index on customer_id, then look at the plan again
CREATE INDEX ix_big_orders_customer
  ON big_orders (customer_id);

EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;
Execution plan (PostgreSQL 16)EXPLAIN output
Bitmap Heap Scan on big_orders
  Recheck Cond: (customer_id = 42)
  ->  Bitmap Index Scan on ix_big_orders_customer
        Index Cond: (customer_id = 42)

Now the Bitmap Index Scan on ix_big_orders_customer finds the matching rows in the index, and the Bitmap Heap Scan reads only the table pages that hold them. For a lookup that returns a single row, you would see a plain Index Scan instead.

The trade-off

Every index takes storage and slows down every INSERT, UPDATE and DELETE. Index the columns you filter and join on, not every column.

Question 2: An interviewer asks about clustered and non-clustered indexes in SQL Server. What is the difference, and how is PostgreSQL different?

These are SQL Server terms. A clustered index is the table itself: its leaf level holds the data rows in key order, so there is only one per table, and by default it is the primary key. A table without one is a heap.

A non-clustered index is a separate structure: the key columns plus a pointer to the row, the clustering key or, on a heap, a RID (row identifier). Fetching other columns through it shows up as a Key Lookup or a RID Lookup.

PostgreSQL has no clustered index. Every table is a heap, and every index, even the primary key, is a secondary index that points to the row's physical address, the ctid. Let's look at it.

SQL - PostgreSQL tables are heaps: every row has a physical address (ctid)
SELECT ctid, order_id, customer_id
FROM big_orders
WHERE order_id <= 100003
ORDER BY order_id;
Output (PostgreSQL 16)3 rows
ctidorder_idcustomer_id
(0,1)1000012
(0,2)1000023
(0,3)1000034

The ctid is (page, item). Order 100001 is on page 0, item 1, and the next two orders sit right after it on the same page.

SQL ServerPostgreSQL
TABLE DATAin the clustered index (key order), or a heapalways a heap
CLUSTEREDone per table: its leaf level is the datanone (CLUSTER reorders once, not maintained)
PRIMARY KEYclustered by defaulta separate unique B-tree index
INDEX POINTS TOthe clustering key (a RID on a heap)the ctid: (page, item) in the heap
OTHER COLUMNSKey Lookup / RID Lookupheap fetch

PostgreSQL has a CLUSTER command, but it reorders the table once and is not maintained. In MySQL, every InnoDB table is clustered by the primary key.

Question 3: A report filters on the year of order_date and is slow even though order_date has an index. What is a sargable predicate, and how do you rewrite the filter?

Sargable means "search argument able": the database can use an index to seek. The rule is simple: leave the indexed column bare on one side of the comparison.

Let's create an index on order_date, then filter on EXTRACT(YEAR FROM order_date) = 2026.

SQL - Index on order_date, but the filter wraps the column in a function
CREATE INDEX ix_big_orders_date
  ON big_orders (order_date);

EXPLAIN (COSTS OFF)
SELECT COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE EXTRACT(YEAR FROM order_date) = 2026;
Execution plan (PostgreSQL 16)EXPLAIN output
Aggregate
  ->  Seq Scan on big_orders
        Filter: (EXTRACT(year FROM order_date) = '2026'::numeric)

Still a Seq Scan, under an Aggregate. The function has to be calculated for every row, and the index is sorted by date, not by year, so PostgreSQL cannot use it. In SQL Server, YEAR(order_date) has the same problem.

Now the same filter as a half-open range: from 2026-01-01, up to but not including 2027-01-01.

SQL - The same filter as a date range: Index Scan
EXPLAIN (COSTS OFF)
SELECT COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE order_date >= CAST('2026-01-01' AS DATE)
  AND order_date <  CAST('2027-01-01' AS DATE);
Execution plan (PostgreSQL 16)EXPLAIN output
Aggregate
  ->  Index Scan using ix_big_orders_date on big_orders
        Index Cond: ((order_date >= '2026-01-01'::date) AND (order_date < '2027-01-01'::date))

Now it is an Index Scan using ix_big_orders_date, with an Index Cond on both ends of the range, what SQL Server calls an Index Seek. Let's check the answer did not change.

SQL - Same answer either way
SELECT 'EXTRACT(YEAR) = 2026' AS filter,
       COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE EXTRACT(YEAR FROM order_date) = 2026
UNION ALL
SELECT 'half-open date range', COUNT(*), SUM(amount)
FROM big_orders
WHERE order_date >= CAST('2026-01-01' AS DATE)
  AND order_date <  CAST('2027-01-01' AS DATE)
ORDER BY filter;
Output (PostgreSQL 16)2 rows
filterordersrevenue
EXTRACT(YEAR) = 20261316671090.00
half-open date range1316671090.00

Same answer both ways: 1316 orders and 671090.00 in revenue.

Same trap, other forms

LOWER(email) = ..., math on the column like amount * 1.1 > 100, LIKE '%son', and implicit conversions in SQL Server. If you can't rewrite the filter, index the expression: in PostgreSQL an expression index, in SQL Server an indexed computed column.

Question 4: You have an index on (customer_id, order_date). Why does it help a filter on customer_id but not a filter on order_date alone?

First, drop the indexes from questions 1 and 3, so they don't hide the effect.

SQL - Clean up: drop the single-column indexes from questions 1 and 3
DROP INDEX ix_big_orders_customer;
DROP INDEX ix_big_orders_date;

The statement runs without returning rows.

A composite index is sorted by the first column, and by the second only inside each value of the first. Think of a phone book: last name, then first name. Finding every Khan is easy. Finding every Sara means reading the whole book.

Let's create an index on (customer_id, order_date) and filter on customer 42 and orders since 2025-01-01.

SQL - Composite index (customer_id, order_date): filter on the leading column
CREATE INDEX ix_big_orders_cust_date
  ON big_orders (customer_id, order_date);

EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42
  AND order_date >= CAST('2025-01-01' AS DATE);
Execution plan (PostgreSQL 16)EXPLAIN output
Bitmap Heap Scan on big_orders
  Recheck Cond: ((customer_id = 42) AND (order_date >= '2025-01-01'::date))
  ->  Bitmap Index Scan on ix_big_orders_cust_date
        Index Cond: ((customer_id = 42) AND (order_date >= '2025-01-01'::date))

Both conditions are in the Index Cond of the Bitmap Index Scan on ix_big_orders_cust_date: seek to the customer, then to the date inside that customer.

Now filter on order_date alone.

SQL - Filter on the second column only: the index cannot seek
EXPLAIN (COSTS OFF)
SELECT order_id, customer_id, amount
FROM big_orders
WHERE order_date >= CAST('2026-06-01' AS DATE);
Execution plan (PostgreSQL 16)EXPLAIN output
Seq Scan on big_orders
  Filter: (order_date >= '2026-06-01'::date)

A Seq Scan. The June 2026 dates are scattered across every customer in the index, so there is nothing to seek to. That is the leading column rule: an index on (A, B) helps a filter on A, or on A and B, but not on B alone.

So put the equality columns first, then the range column. Oracle, MySQL 8 and PostgreSQL 18 can do a skip scan when the leading column has few distinct values, but in an interview, lead with the rule.

Question 5: A query returns 10 rows but still has to read the table. What is a covering index, and why does SELECT * hurt performance?

First, drop the composite index from question 4.

SQL - Clean up: drop the composite index from question 4
DROP INDEX ix_big_orders_cust_date;

The statement runs without returning rows.

A covering index holds every column the query needs, so the database never touches the table. Key columns are for searching. INCLUDE columns are only stored in the leaf level, to be returned.

Here the key is customer_id and order_date, and amount is included. We ask for exactly those columns, and EXPLAIN ANALYZE really runs the query.

SQL - Covering index with INCLUDE: Index Only Scan, zero heap fetches
CREATE INDEX ix_big_orders_cover
  ON big_orders (customer_id, order_date)
  INCLUDE (amount);

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;
Execution plan (PostgreSQL 16)EXPLAIN output
Index Only Scan using ix_big_orders_cover on big_orders (actual rows=10 loops=1)
  Index Cond: (customer_id = 42)
  Heap Fetches: 0

An Index Only Scan on ix_big_orders_cover, 10 actual rows, and Heap Fetches: 0. The table was never read. In SQL Server, this is the index that removes the Key Lookup.

Now SELECT * with the same filter.

SQL - SELECT * with the same index: back to the table
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT *
FROM big_orders
WHERE customer_id = 42;
Execution plan (PostgreSQL 16)EXPLAIN output
Bitmap Heap Scan on big_orders (actual rows=10 loops=1)
  Recheck Cond: (customer_id = 42)
  Heap Blocks: exact=10
  ->  Bitmap Index Scan on ix_big_orders_cover (actual rows=10 loops=1)
        Index Cond: (customer_id = 42)

order_id, status and notes are not in the index, so PostgreSQL goes back to the table: a Bitmap Index Scan and then a Bitmap Heap Scan with Heap Blocks: exact=10, ten table pages for ten rows. On a big report, those extra reads are most of the cost.

So SELECT * is almost never covered, drags wide columns like notes over the network, and breaks code when the table changes.

PostgreSQL detail

An index only scan relies on the visibility map, so the table must be vacuumed. That is why the setup script runs VACUUM ANALYZE.

Question 6: You are handed a slow query and its execution plan. How do you read the plan, and what are the first three things you look for?

First, drop the covering index from question 5, so we are back to just the primary keys.

SQL - Clean up: drop the covering index from question 5
DROP INDEX ix_big_orders_cover;

The statement runs without returning rows.

Here is a real report: orders and revenue by region for 2026.

SQL - A report query: 2026 orders and revenue by region
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS revenue
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.order_date >= CAST('2026-01-01' AS DATE)
GROUP BY c.region
ORDER BY c.region;
Output (PostgreSQL 16)4 rows
regionordersrevenue
East329167979.00
North329168133.00
South329167566.00
West329167412.00

Now its plan. EXPLAIN ANALYZE runs the query, so every step shows the estimate, rows=, next to the actual rows.

SQL - Read its plan: EXPLAIN ANALYZE shows estimated and actual rows
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS revenue
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.order_date >= CAST('2026-01-01' AS DATE)
GROUP BY c.region
ORDER BY c.region;
Execution plan (PostgreSQL 16)EXPLAIN output
Sort  (cost=649.49..649.50 rows=4 width=45) (actual rows=4 loops=1)
  Sort Key: c.region
  Sort Method: quicksort  Memory: 25kB
  ->  HashAggregate  (cost=649.40..649.45 rows=4 width=45) (actual rows=4 loops=1)
        Group Key: c.region
        Batches: 1  Memory Usage: 24kB
        ->  Hash Join  (cost=58.00..639.48 rows=1322 width=10) (actual rows=1316 loops=1)
              Hash Cond: (o.customer_id = c.customer_id)
              ->  Seq Scan on big_orders o  (cost=0.00..578.00 rows=1322 width=9) (actual rows=1316 loops=1)
                    Filter: (order_date >= '2026-01-01'::date)
                    Rows Removed by Filter: 18684
              ->  Hash  (cost=33.00..33.00 rows=2000 width=9) (actual rows=2000 loops=1)
                    Buckets: 2048  Batches: 1  Memory Usage: 102kB
                    ->  Seq Scan on big_customers c  (cost=0.00..33.00 rows=2000 width=9) (actual rows=2000 loops=1)

These are the first three things to look for:

  • Read it inside out. The most indented steps run first: the two Seq Scans feed the Hash and the Hash Join, then the HashAggregate groups by region, and the Sort at the top runs last. In SQL Server's graphical plan, read right to left.
  • Compare estimated and actual rows. The Seq Scan on big_orders estimated 1322 rows and got 1316. That is healthy. Ten times apart or more means bad statistics, and often a bad plan. In SQL Server, compare Estimated and Actual Number of Rows in the actual execution plan.
  • Find work that is thrown away. Rows Removed by Filter: 18684, read only to be discarded. That is the step to fix, here with an index on order_date.

Then check the join types and loops: a Nested Loop running thousands of times is a red flag.

Scenario 7: A report query that ran in 2 seconds now takes 2 minutes, and nobody changed the code. What do you do, step by step?

Don't guess, and don't start adding indexes. Work through it in order:

  • Reproduce it with the same parameters, and check it isn't just blocked by a lock.
  • Ask what changed: a deployment, a dropped index, a big data load.
  • Get the actual plan and compare estimated and actual rows.
  • Find the expensive step: big scans, lookups, non-sargable filters, loops.
  • Fix one thing, prove it with the plan, and prevent it.

Let's build a real case. This first statement is for the demo only, not for production: it stops autovacuum from refreshing the statistics in the middle of the demo.

SQL - Demo only: stop autovacuum from refreshing the statistics in the middle of the demo
ALTER TABLE big_orders SET (autovacuum_enabled = false);

The statement runs without returning rows.

Last night a migration loaded 5,000 Pending orders, after the statistics were gathered, so the optimizer thinks there are none.

SQL - What changed: a migration loaded 5,000 Pending orders
-- last night: 5,000 orders migrated from the old system
INSERT INTO big_orders
SELECT 200000 + g.n, 1 + g.n % 2000, CAST('2026-06-30' AS DATE),
       'Pending', CAST(50 + g.n % 400 AS DECIMAL(10,2)), 'Migrated'
FROM generate_series(1, 5000) AS g(n);

The statement runs and changes the data. The check query below shows the result.

SQL - check the data after the change
SELECT status, COUNT(*) AS orders
FROM big_orders
GROUP BY status
ORDER BY status;
Output after the change4 rows
statusorders
Cancelled2000
Delivered14000
Pending5000
Shipped4000

Now the report on Pending orders by region.

SQL - The slow plan: estimated 1 row, actual 5,000, so a Nested Loop runs 5,000 index lookups
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;
Execution plan (PostgreSQL 16)EXPLAIN output
GroupAggregate  (cost=655.04..655.06 rows=1 width=45) (actual rows=4 loops=1)
  Group Key: c.region
  ->  Sort  (cost=655.04..655.04 rows=1 width=10) (actual rows=5000 loops=1)
        Sort Key: c.region
        Sort Method: quicksort  Memory: 388kB
        ->  Nested Loop  (cost=0.28..655.03 rows=1 width=10) (actual rows=5000 loops=1)
              ->  Seq Scan on big_orders o  (cost=0.00..646.73 rows=1 width=9) (actual rows=5000 loops=1)
                    Filter: ((status)::text = 'Pending'::text)
                    Rows Removed by Filter: 20000
              ->  Index Scan using big_customers_pkey on big_customers c  (cost=0.28..8.29 rows=1 width=9) (actual rows=1 loops=5000)
                    Index Cond: (customer_id = o.customer_id)

The Seq Scan on big_orders estimated rows=1, but the actual rows are 5000. Planned for one row, the optimizer chose a Nested Loop, so the Index Scan using big_customers_pkey runs with loops=5000. On millions of rows, that is how 2 seconds becomes 2 minutes.

The fix is to refresh the statistics: ANALYZE in PostgreSQL, UPDATE STATISTICS in SQL Server.

SQL - Refresh the statistics, and the plan fixes itself
ANALYZE big_orders;

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;
Execution plan (PostgreSQL 16)EXPLAIN output
Sort  (cost=788.24..788.25 rows=4 width=45) (actual rows=4 loops=1)
  Sort Key: c.region
  Sort Method: quicksort  Memory: 25kB
  ->  HashAggregate  (cost=788.15..788.20 rows=4 width=45) (actual rows=4 loops=1)
        Group Key: c.region
        Batches: 1  Memory Usage: 24kB
        ->  Hash Join  (cost=58.00..750.65 rows=5000 width=10) (actual rows=5000 loops=1)
              Hash Cond: (o.customer_id = c.customer_id)
              ->  Seq Scan on big_orders o  (cost=0.00..679.50 rows=5000 width=9) (actual rows=5000 loops=1)
                    Filter: ((status)::text = 'Pending'::text)
                    Rows Removed by Filter: 20000
              ->  Hash  (cost=33.00..33.00 rows=2000 width=9) (actual rows=2000 loops=1)
                    Buckets: 2048  Batches: 1  Memory Usage: 102kB
                    ->  Seq Scan on big_customers c  (cost=0.00..33.00 rows=2000 width=9) (actual rows=2000 loops=1)

Now the estimate is 5000, and the optimizer switches to a Hash Join, with a HashAggregate and a Sort on top. The result itself never changed, only the plan:

SQL - The report result (unchanged by the plan)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;
Output (PostgreSQL 16)4 rows
regionorderspending_amount
East1250308750.00
North1250306250.00
South1250307500.00
West1250305200.00
Prevent it

Run ANALYZE as the last step of every big load. In SQL Server, use UPDATE STATISTICS, and Query Store to see when the plan changed.

Key points to remember

  • An index turns a full scan into a seek; EXPLAIN shows which you got
  • SQL Server: clustered = the table, one per table; PostgreSQL: every table is a heap
  • Sargable: keep the column bare; use a date range, not EXTRACT(YEAR)
  • Composite: leading column first; covering + INCLUDE beats SELECT *
  • Slow query: compare estimated vs actual rows, then fix stale statistics

The full SQL script

Here is everything in one script: the sample data and every query from this post, in order. Copy it and run it top to bottom.

Show the full SQL script (sample data and every query)
Full script - copy and run top to bottom
-- ========================================================================
-- SQL Interview Q&A #9 - Performance and indexes
-- TechBrothersIT. Sample data is invented for teaching.
-- Standard SQL, tested on PostgreSQL 16 (and cross-checked on DuckDB). Runs top to bottom in one go.
-- Run it in an empty database or schema: other videos reuse table names
-- like dim_customer, and their leftover tables can block the DROPs below.
-- PostgreSQL example:  CREATE SCHEMA sql_q09;  SET search_path TO sql_q09;
-- ========================================================================

-- Step 0: create and load the sample data
DROP TABLE IF EXISTS payments;
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS employees;
DROP TABLE IF EXISTS departments;

CREATE TABLE departments (dept_id INT PRIMARY KEY, dept_name VARCHAR(20));
INSERT INTO departments VALUES (10, 'Sales'), (20, 'Engineering'), (30, 'HR'), (40, 'Finance');

CREATE TABLE employees (
  emp_id     INT PRIMARY KEY,
  name       VARCHAR(20),
  dept_id    INT,            -- NULL = not assigned yet
  manager_id INT,            -- NULL = top of the company
  salary     INT,
  hire_date  DATE
);
INSERT INTO employees VALUES
  (1, 'Aisha',  NULL, NULL, 150000, '2018-03-01'),
  (2, 'Omar',   20,   1,    120000, '2019-06-15'),
  (3, 'Lina',   20,   2,     90000, '2021-01-10'),
  (4, 'Ravi',   20,   2,     90000, '2022-04-05'),
  (5, 'Mei',    20,   2,     75000, '2024-09-01'),
  (6, 'Sara',   10,   1,     95000, '2020-02-20'),
  (7, 'Daniel', 10,   6,    105000, '2021-07-01'),
  (8, 'Fatima', 10,   6,     60000, '2023-11-12'),
  (9, 'John',   30,   1,     70000, '2019-09-30'),
  (10,'Zara',   NULL, 9,     55000, '2026-01-05');

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(20),
  city        VARCHAR(20),
  region      VARCHAR(10),    -- NULL = unknown
  email       VARCHAR(40)
);
INSERT INTO customers VALUES
  (1, 'Sara Khan',  'Toronto', 'East', 'sara@mail.com'),
  (2, 'Omar Ali',   'Dallas',  'West', 'omar@mail.com'),
  (3, 'Lina Park',  'Seattle', 'West', 'lina@mail.com'),
  (4, 'Mei Chen',   'Boston',  'East', 'mei@mail.com'),
  (5, 'Ravi Patel', 'Austin',  NULL,   'ravi@mail.com'),
  (6, 'Chen Wu',    'Denver',  'West', 'chen@mail.com'),
  (7, 'Sara K.',    'Toronto', 'East', 'sara@mail.com');

CREATE TABLE products (product_id INT PRIMARY KEY, product VARCHAR(20), category VARCHAR(15), price DECIMAL(10,2));
INSERT INTO products VALUES
  (1, 'Laptop',   'Electronics', 1200.00),
  (2, 'Monitor',  'Electronics',  300.00),
  (3, 'Keyboard', 'Accessories',   50.00),
  (4, 'Mouse',    'Accessories',   25.00),
  (5, 'Desk',     'Furniture',    400.00),
  (6, 'Chair',    'Furniture',    250.00);

CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2)
);
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05', 'Delivered', 1250.00),
  (1002, 2, '2026-01-18', 'Delivered',  300.00),
  (1003, 4, '2026-02-02', 'Delivered',  650.00),
  (1004, 1, '2026-02-14', 'Cancelled',   50.00),
  (1005, 3, '2026-02-20', 'Delivered', 1200.00),
  (1006, 4, '2026-03-03', 'Shipped',    275.00),
  (1007, 5, '2026-03-15', 'Delivered',  400.00),
  (1008, 2, '2026-04-01', 'Delivered',   75.00),
  (1009, 4, '2026-04-22', 'Delivered',  250.00),
  (1010, 1, '2026-05-09', 'Shipped',    300.00),
  (1011, 3, '2026-05-30', 'Cancelled',  400.00),
  (1012, 7, '2026-06-11', 'Delivered',   50.00);

CREATE TABLE order_items (order_id INT, product_id INT, qty INT, unit_price DECIMAL(10,2));
INSERT INTO order_items VALUES
  (1001, 1, 1, 1200.00), (1001, 3, 1, 50.00),
  (1002, 2, 1, 300.00),
  (1003, 5, 1, 400.00), (1003, 6, 1, 250.00),
  (1004, 3, 1, 50.00),
  (1005, 1, 1, 1200.00),
  (1006, 6, 1, 250.00), (1006, 4, 1, 25.00),
  (1007, 5, 1, 400.00),
  (1008, 4, 3, 25.00),
  (1009, 6, 1, 250.00),
  (1010, 2, 1, 300.00),
  (1011, 5, 1, 400.00),
  (1012, 3, 1, 50.00);

CREATE TABLE payments (payment_id INT PRIMARY KEY, order_id INT, paid_amount DECIMAL(10,2));
INSERT INTO payments VALUES
  (1, 1001, 1250.00), (2, 1002, 300.00), (3, 1003, 400.00), (4, 1003, 250.00), (5, 1005, 1200.00);

DROP TABLE IF EXISTS big_orders;
DROP TABLE IF EXISTS big_customers;

CREATE TABLE big_customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(30),
  region      VARCHAR(10)
);
INSERT INTO big_customers
SELECT g.n,
       CONCAT('Customer ', g.n),
       CASE g.n % 4 WHEN 0 THEN 'East' WHEN 1 THEN 'West' WHEN 2 THEN 'North' ELSE 'South' END
FROM generate_series(1, 2000) AS g(n);

-- 20,000 orders from 2019-01-01 to 2026-06-30, loaded in date order; 10 orders per customer, spread over the years
CREATE TABLE big_orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2),
  notes       VARCHAR(200)
);
INSERT INTO big_orders
SELECT 100000 + g.n,
       1 + g.n % 2000,
       CAST('2019-01-01' AS DATE) + CAST(FLOOR(g.n * 2737.0 / 20000) AS INT),
       CASE WHEN g.n % 10 = 0 THEN 'Cancelled' WHEN g.n % 10 IN (1, 2) THEN 'Shipped' ELSE 'Delivered' END,
       CAST(20 + (g.n * 37) % 980 AS DECIMAL(10,2)),
       CONCAT('Order ', 100000 + g.n, ': leave the parcel at the front desk if nobody answers the door')
FROM generate_series(1, 20000) AS g(n);

-- fresh statistics and visibility map (SQL Server: UPDATE STATISTICS).
-- VACUUM cannot run inside a transaction: run the script with psql -f, or run these two lines on their own.
VACUUM ANALYZE big_customers;
VACUUM ANALYZE big_orders;


-- Step 1: No index yet: the plan is a Seq Scan
EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;

-- Step 2: Create an index on customer_id, then look at the plan again
CREATE INDEX ix_big_orders_customer
  ON big_orders (customer_id);

EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;

-- Step 3: PostgreSQL tables are heaps: every row has a physical address (ctid)
SELECT ctid, order_id, customer_id
FROM big_orders
WHERE order_id <= 100003
ORDER BY order_id;

-- Step 4: Index on order_date, but the filter wraps the column in a function
CREATE INDEX ix_big_orders_date
  ON big_orders (order_date);

EXPLAIN (COSTS OFF)
SELECT COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE EXTRACT(YEAR FROM order_date) = 2026;

-- Step 5: The same filter as a date range: Index Scan
EXPLAIN (COSTS OFF)
SELECT COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE order_date >= CAST('2026-01-01' AS DATE)
  AND order_date <  CAST('2027-01-01' AS DATE);

-- Step 6: Same answer either way
SELECT 'EXTRACT(YEAR) = 2026' AS filter,
       COUNT(*) AS orders, SUM(amount) AS revenue
FROM big_orders
WHERE EXTRACT(YEAR FROM order_date) = 2026
UNION ALL
SELECT 'half-open date range', COUNT(*), SUM(amount)
FROM big_orders
WHERE order_date >= CAST('2026-01-01' AS DATE)
  AND order_date <  CAST('2027-01-01' AS DATE)
ORDER BY filter;

-- Step 7: Clean up: drop the single-column indexes from questions 1 and 3
DROP INDEX ix_big_orders_customer;
DROP INDEX ix_big_orders_date;

-- Step 8: Composite index (customer_id, order_date): filter on the leading column
CREATE INDEX ix_big_orders_cust_date
  ON big_orders (customer_id, order_date);

EXPLAIN (COSTS OFF)
SELECT order_id, order_date, amount
FROM big_orders
WHERE customer_id = 42
  AND order_date >= CAST('2025-01-01' AS DATE);

-- Step 9: Filter on the second column only: the index cannot seek
EXPLAIN (COSTS OFF)
SELECT order_id, customer_id, amount
FROM big_orders
WHERE order_date >= CAST('2026-06-01' AS DATE);

-- Step 10: Clean up: drop the composite index from question 4
DROP INDEX ix_big_orders_cust_date;

-- Step 11: Covering index with INCLUDE: Index Only Scan, zero heap fetches
CREATE INDEX ix_big_orders_cover
  ON big_orders (customer_id, order_date)
  INCLUDE (amount);

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT customer_id, order_date, amount
FROM big_orders
WHERE customer_id = 42;

-- Step 12: SELECT * with the same index: back to the table
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT *
FROM big_orders
WHERE customer_id = 42;

-- Step 13: Clean up: drop the covering index from question 5
DROP INDEX ix_big_orders_cover;

-- Step 14: A report query: 2026 orders and revenue by region
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS revenue
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.order_date >= CAST('2026-01-01' AS DATE)
GROUP BY c.region
ORDER BY c.region;

-- Step 15: Read its plan: EXPLAIN ANALYZE shows estimated and actual rows
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS revenue
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.order_date >= CAST('2026-01-01' AS DATE)
GROUP BY c.region
ORDER BY c.region;

-- Step 16: Demo only: stop autovacuum from refreshing the statistics in the middle of the demo
ALTER TABLE big_orders SET (autovacuum_enabled = false);

-- Step 17: What changed: a migration loaded 5,000 Pending orders
-- last night: 5,000 orders migrated from the old system
INSERT INTO big_orders
SELECT 200000 + g.n, 1 + g.n % 2000, CAST('2026-06-30' AS DATE),
       'Pending', CAST(50 + g.n % 400 AS DECIMAL(10,2)), 'Migrated'
FROM generate_series(1, 5000) AS g(n);

-- check the result
SELECT status, COUNT(*) AS orders
FROM big_orders
GROUP BY status
ORDER BY status;

-- Step 18: The slow plan: estimated 1 row, actual 5,000, so a Nested Loop runs 5,000 index lookups
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;

-- Step 19: Refresh the statistics, and the plan fixes itself
ANALYZE big_orders;

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;

-- Step 20: The report result (unchanged by the plan)
SELECT c.region, COUNT(*) AS orders, SUM(o.amount) AS pending_amount
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Pending'
GROUP BY c.region
ORDER BY c.region;
Next in this series

Part 10: Real-World Manager Scenarios

The sample data on this page is invented for teaching. Every output table is the real result of the query above it, run on PostgreSQL 16 over that sample data, and the portable queries were also checked on a second engine. Where SQL Server syntax is different, the post says so.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.