Prompt Engineering SQL Joins

Optimize SQL Query — Joins, Cardinality, and Wasted Work

A five-table join that got slow as data grew: establish cardinality first, check each join strategy against the data shape, and hunt the fan-out doing wasted work.

Overview

Join-heavy queries degrade in a specific way: the join order and strategies that fit yesterday's table sizes stop fitting today's. This prompt uses the join optimization goal — establish cardinality first (which side is small, what each join multiplies or filters), check every join strategy against the data shape (nested loops, hash, merge — each has a shape it serves), hunt fan-out that explodes rows only to collapse them again, and verify join columns are typed identically, because an implicit conversion silently disables index use. The loaded setup provides real row counts (12M orders, 48M items, 40 warehouses) — the cardinality context that join advice is worthless without.

Workflow

  1. State the sizes

    Row counts per table — join analysis without cardinality is guesswork, and the contract says so.

  2. Match strategy to shape

    Each join checked: loops for few rows with an index, hash for large unordered sets, merge for sorted inputs.

  3. Hunt the waste

    Fan-out, repeated lookups, joined-but-unused tables, implicit conversions — the work that adds rows but not results.

Why This Works

  • Cardinality-first ordering mirrors how the optimizer itself decides
  • Shape-matching turns join advice from folklore into a checkable claim
  • The implicit-conversion check catches the silent index killer on joins

Best for

  • Queries joining tables of wildly different sizes
  • Joins that were fast until one table grew
  • Order-detail, reporting, and catalog join patterns

Not for

  • Single-table filter problems — that's the Query Speed goal, a different contract
  • Restructuring the application code that builds the query — that's the Refactor Prompt Builder

Use cases

  • Diagnosing the multi-table join that slowed as data grew
  • Checking join order against actual table sizes
  • Finding the join that fans out and collapses again

Tip: Save time by exploring related resources and tools that integrate with this workflow.

Explore all resources