Sub topic 10
How the Database Runs These Queries and Which Indexes Help
This chapter assumes you know SELECT, WHERE, ORDER BY, INNER JOIN, LEFT JOIN, aggregate functions, table aliases, and NULL. The examples use customers, orders, and order_items.
The logical execution model
A correlated subquery refers to a column from the outer query. Logically, the database considers one outer row at a time and evaluates the inner query using that row's values.
For example:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);For each customer, the inner query searches for an order with the same customer_id. EXISTS becomes true when the database finds one matching row. It does not need to find the customer's other orders.
This is the logical model, not necessarily the physical procedure. A database optimizer can transform the query into a semi-join, rearrange operations, or choose another equivalent plan. A semi-join returns rows from the first input when at least one match exists. It does not return one copy for every matching row.
Why the correlation column needs an index
Without a useful index, the database may scan orders repeatedly. If there are many customers, this can require a large amount of work.
An index on the correlation column supports fast lookups:
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);With this index, the database can search directly for orders belonging to the current customer. For EXISTS, it can often stop after the first match. For NOT EXISTS, it must establish that no match exists, so it may inspect all matching index entries for that customer.
The index is most useful when the condition begins with its leading column. For example, this composite index can support a query that filters by customer and date:
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, order_date);The order of columns matters. An index beginning with order_date is usually less useful for a lookup whose main condition is customer_id = ....
| Query condition | Potentially useful index |
|---|---|
| `o.customer_id = c.customer_id` | `(customer_id)` |
| Customer and date range | `(customer_id, order_date)` |
| Order item lookup by order and product | `(order_id, product_id)` |
Inspecting the chosen plan
Use your database's plan command to see whether it uses an index. Many systems support EXPLAIN:
EXPLAIN
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);Look for an index scan, index lookup, or a semi-join. Exact names differ between PostgreSQL, MySQL, SQL Server, and other systems. The plan can also show a sequential scan, which reads many or all table rows.
A sequential scan is not automatically wrong. If most customers have orders, or if orders is small, scanning the table may cost less than repeated index operations. The optimizer estimates this using table statistics. Refresh statistics according to your database system after large data changes.
Correlated aggregates and indexes
A correlated scalar subquery often benefits from the same index:
SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);An index on orders(customer_id) groups each customer's rows for the aggregate lookup. However, this query may still be expensive because it computes an average for many outer rows. The optimizer might rewrite it, but an explicit grouped query can sometimes make the intended work clearer:
SELECT o.order_id, o.customer_id, o.total
FROM orders o
JOIN (
SELECT customer_id, AVG(total) AS average_total
FROM orders
GROUP BY customer_id
) a ON a.customer_id = o.customer_id
WHERE o.total > a.average_total;Compare both plans before choosing one. Readability, data size, and the database optimizer all affect the result.
Exercise
Which index best supports WHERE o.customer_id = c.customer_id AND o.order_date >= DATE '2026-01-01'?
Show answer
An index beginning with (customer_id, order_date) is a strong candidate because it supports the equality lookup first and then the date range.