ReinDBby Bandlei

7. Tuning joins and WHERE clauses

Brett Rosenblatt · Database tuning guide v1.3 · PDF

Most slow statements are slow for a handful of reasons that repeat across every engine: predicates that hide columns from indexes, type mismatches, joins that multiply rows, and queries that ask for far more than they need. This chapter covers the patterns and their rewrites.

7.1Keep predicates sargable

A predicate is sargable (search-argument-able) when the engine can use an index to find the matching rows directly. The rule is simple: leave the indexed column bare and do the arithmetic on the other side.

-- Hides order_date from a normal index: a function wraps the column (each engine's version is in the note below)
WHERE TRUNC(order_date) = DATE '2026-10-31'

-- Index-friendly: a half-open range on the bare column
WHERE order_date >= DATE '2026-10-31'
  AND order_date <  DATE '2026-11-01'
Instead ofWrite
WHERE YEAR(order_date) = 2026WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'
WHERE total_amount * 1.1 > 100WHERE total_amount > 100 / 1.1
WHERE UPPER(email) = :emailStore a normalized copy, or create a function-based or expression index on UPPER(email)
WHERE COALESCE(discount, 0) = 0WHERE (discount = 0 OR discount IS NULL)
WHERE SUBSTR(sku, 1, 3) = 'ABC'WHERE sku LIKE 'ABC%'
WHERE order_id + 0 = :id (an old trick to disable an index)Remove it, and use a hint if you really must steer the plan

7.2Data type mismatches and implicit conversions

When the two sides of a comparison have different types, the engine converts one of them. If it converts the column, it has to do it for every row, and the index on that column is useless.

The usual sources are application drivers that bind every string as Unicode or every number as a decimal, and join columns that were declared differently in different tables.

Join keys should have identical types, lengths and collations on both sides. Mixed integer sizes are usually handled well, but Unicode against non-Unicode strings, or fixed-length against variable-length strings, cause real trouble. Fix it in the schema, not in every query.

7.3Patterns that hide rows from indexes

  • Leading wildcards. LIKE '%term' and LIKE '%term%' can't use a normal B-tree index. Use a trigram index where the engine offers one, or full-text search. Full-text search matches words, not arbitrary substrings, so check that the semantics fit.
  • OR across different columns. WHERE customer_id = :c OR referrer_id = :c may force a scan. Optimizers can sometimes combine two indexes, but not always. A UNION ALL of two indexed queries, written so it doesn't return duplicates, is the dependable rewrite.
  • NOT IN with a nullable subquery. If the subquery returns a single NULL, NOT IN returns no rows at all. It also blocks some anti-join optimizations. Use NOT EXISTS.
  • Negative predicates. <>, NOT LIKE and NOT IN rarely use indexes well, and they usually match most rows anyway.
  • Catch-all filters. WHERE (:status IS NULL OR status = :status) AND (:region IS NULL OR region = :region) gives one plan for every combination, usually a bad one. Build the statement dynamically with only the filters that were supplied, still using bind variables, or recompile on every call when calls are infrequent.

7.4Joins: get the shape right and the method follows

Optimizers pick between three join methods:

  • Nested loops: for each row from the outer input, look up matches in the inner input. Excellent when the outer input is small and the inner join column is indexed.
  • Hash join: build a hash table from the smaller input, probe it with the larger one. Excellent for large, unsorted inputs joined on equality. Needs memory, and spills to temp when it doesn't get enough.
  • Merge join: walk two inputs already sorted on the join key. Excellent when indexes or earlier steps provide the order.

When the "wrong" method shows up, the cause is nearly always a bad row estimate (Chapter 6) or a missing index, not the optimizer's taste. Give it accurate statistics and the right indexes, and it chooses well.

Index foreign keys. An unindexed foreign key forces a full scan of the child table whenever a parent row is deleted or its key changes, because the engine must check for children. Some engines also lock the whole child table during those operations, which shows up as blocking far from the statement that caused it.

More join guidance:

  • Filter early. Reduce rows before joining. Pre-aggregate in a derived table before joining a large detail table to a small dimension.
  • Mind the outer-join trap. A condition on the outer table's columns in the WHERE clause quietly turns a LEFT JOIN into an inner join. If you mean "keep unmatched rows", put the condition in the ON clause.
  • Don't join and then DISTINCT. If you only need to know that a match exists, use EXISTS (a semi-join). Joining and then removing duplicates does extra work and hides the intent.
  • Flatten deep view stacks. Optimizers search a limited number of join orders, and views built on views on views can push a query past those limits.

7.5Ask for less

  • Select only the columns you need. It enables covering indexes, cuts I/O and network traffic, and avoids reading LOBs nobody looks at.
  • Paginate with keysets, not offsets. OFFSET 100000 reads and throws away 100,000 rows on every page. Remember the last key and seek past it instead:
-- Keyset pagination: seek past the last row of the previous page
SELECT order_id, order_date, total_amount
FROM   orders
WHERE  order_date < :last_date
   OR (order_date = :last_date AND order_id < :last_id)
ORDER  BY order_date DESC, order_id DESC
FETCH  FIRST 50 ROWS ONLY;   -- standard SQL; each engine's top-N syntax is in the note below

An index on (order_date, order_id) makes every page as fast as the first.

  • Use the engine's top-N syntax, so the optimizer knows that only the first rows are needed and can stop early.
  • Replace per-row subqueries with set operations. A scalar subquery in the select list can run once per row:
-- Before: one subquery execution per customer row
SELECT c.customer_id, c.name,
       (SELECT MAX(o.order_date) FROM orders o WHERE o.customer_id = c.customer_id) AS last_order
FROM   customers c;

-- After: aggregate once, then join
SELECT c.customer_id, c.name, o.last_order
FROM   customers c
LEFT   JOIN (SELECT customer_id, MAX(order_date) AS last_order
             FROM   orders
             GROUP  BY customer_id) o
       ON o.customer_id = c.customer_id;

The rewrite wins when most customers are returned. When only a few are, the original with an index on (customer_id, order_date) can be faster, and many optimizers transform one into the other on their own. Check the plan rather than assuming.

  • Use window functions instead of self-joins for running totals, rankings and "latest row per group" (every current release of the four engines supports them; MySQL from 8.0):
SELECT *
FROM  (SELECT o.*,
              ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
       FROM   orders o) x
WHERE  rn = 1;

7.6Bind variables and parameterization

Literal values make every statement text unique, so the engine parses and optimizes each one from scratch and fills its plan cache with single-use plans. Use bind variables (parameters) in application code. They also protect against SQL injection.

Bind variables plus skewed data equals parameter sensitivity: one plan for very different values. Chapter 9 covers the remedies.

7.7Batch large data changes

One huge UPDATE or DELETE holds locks for its whole duration, generates large amounts of undo, redo, WAL or transaction log, and can stall replicas. Break it into batches with a commit after each (when the business rules allow), or better, design the table so old data leaves by dropping a partition (Chapter 10).

Make sure the column you filter on is indexed, or each batch rescans the table from the start.

This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.