Sub topic 14
Performance Considerations and Reading Query Plans
Assume you already understand SELECT, joins, aggregates, GROUP BY, NULL, and three-valued logic. This chapter focuses on how subqueries affect execution and how to inspect a database's chosen plan.
A subquery describes a result. The database optimizer decides how to produce that result. It may execute the subquery separately, turn it into a join, or use an index to avoid reading unnecessary rows. Therefore, the written shape of a query does not always predict its runtime.
The main performance risks
A non-correlated subquery often runs once, or is transformed into an equivalent operation. A correlated subquery can be considered for each row from the outer query. For example, if the outer query finds 100,000 employees, a correlated lookup might be attempted 100,000 times.
That does not automatically make a correlated subquery slow. An index on the correlated column can make each lookup cheap. Without a useful index, the database might repeatedly scan a large table.
These forms often express similar questions:
| Question | Possible form | Important concern |
|---|---|---|
| Does a customer have an order? | `EXISTS` | An index on `orders.customer_id` helps |
| Find customers with orders over 100 | `IN` or a join | Check duplicate and `NULL` behavior |
| Compare each employee with a department average | Correlated subquery or join | Aggregation and repeated work |
| Build an intermediate result | Derived table or CTE | Check whether it is materialized |
EXISTS is useful when you only need to know whether a matching row exists. The database can often stop searching after the first match:
SELECT c.id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.total > 100
);An index such as orders(customer_id, total) may help this query. The best index depends on the database, data distribution, and other queries.
Reading an execution plan
Use EXPLAIN to request a plan without running the statement. PostgreSQL syntax is shown here:
EXPLAIN
SELECT c.id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.total > 100
);EXPLAIN ANALYZE runs the statement and reports actual timing and row counts:
EXPLAIN ANALYZE
SELECT c.id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.total > 100
);Other systems use different options. For example, MySQL commonly uses EXPLAIN ANALYZE in modern versions, while SQL Server uses graphical or textual execution plans.
Look first at these details:
- Scan type: an index scan usually reads selected entries, while a sequential scan reads the table.
- Estimated rows and actual rows: large differences suggest stale statistics or assumptions that do not match the data.
- Loops: a node executed many times may belong to a correlated lookup.
- Join type: nested-loop joins can be efficient for a small outer input and indexed inner lookups, but expensive for two large inputs.
- Filter position: filtering earlier usually reduces later work.
- Total time: in an analyzed plan, focus on the nodes responsible for most actual time.
A practical tuning process
- Write the clearest correct query.
- Run
EXPLAINor the database's equivalent. - Compare estimated and actual rows.
- Check whether correlated work repeats unexpectedly.
- Test a suitable index, join, CTE, or rewritten subquery.
- Measure again with representative data.
Do not rewrite every subquery into a join automatically. A join can create duplicate rows, while EXISTS expresses a presence test directly. Choose the form that preserves the intended result, then verify performance with a plan.
Exercise
Why should you inspect actual rows and loop counts when a correlated subquery is slow?
Show answer
They show whether the inner operation runs many times and whether the optimizer's estimates match the data. This helps distinguish missing indexes from inaccurate statistics or an unsuitable query shape.