sqlANYindexesjoin-performance
sql
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_line_items_order_id ON line_items(order_id);Indexes on foreign keys and matching join columns reduce scans and nested-loop pain.
SQL join tuning with indexes, plan inspection, row reduction, and troubleshooting guidance.
Practical ways to speed up join-heavy queries.
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_line_items_order_id ON line_items(order_id);Indexes on foreign keys and matching join columns reduce scans and nested-loop pain.
Check whether the planner uses indexes, hash joins, merge joins, or nested loops.
EXPLAIN ANALYZE
SELECT c.customer_id, o.order_id
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.created_at >= CURRENT_DATE - INTERVAL '30 days';Plan inspection is the fastest way to validate whether a join is cheap or expensive.
WITH recent_orders AS (
SELECT order_id, customer_id
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT c.customer_id, ro.order_id
FROM customers c
JOIN recent_orders ro ON ro.customer_id = c.customer_id;Smaller intermediate sets usually mean faster join processing.
SELECT c.customer_id, c.name, o.order_id, o.total_amount
-- not SELECT *Narrow projections reduce memory, network transfer, and sort/hash costs.
A quick diagnostic flow for slow joins.
1. Are join keys indexed?
2. Are data types identical on both sides?
3. Is a one-to-many join inflating rows?
4. Can filters move earlier?
5. Does EXPLAIN show scans or huge estimates?
6. Can you pre-aggregate or split the query?A small checklist catches most real-world join issues quickly.