SQL Code Optimization Tricks Reference Guide
Performance
Trick Name Use Case Impact Benefits When to Use
Index Frequent 10-1000x faster Query When
Creation WHERE time: 5s querying
clause → 0.05s non-primary
queries key columns
frequently
Composite Multi- 5-50x faster Uses When
Index column single filtering by
WHERE index scan multiple
conditions instead of columns
index together
merge
SELECT Large 2-10x faster, less Reduces Always,
Specific tables memory I/O, unless you
Columns with many network truly need all
columns transfer, columns
memory
usage
LIMIT Large Dramatically faster Loads When
with result sets response only displaying
Pagination needed paginated
data, results
better UX
EXISTS vs Subquery 2-5x faster for large Stops at When
IN conditions datasets first subquery
match, returns many
better for rows
large
subquery
results
JOIN vs Related 3-10x faster Better When
Subquery table data query relating
retrieval execution tables for
plan, uses filtering/data
indexes retrieval
efficiently
WHERE Filtering 5-20x faster Filters When
vs conditions before filtering on
HAVING grouping non-
vs after aggregate
grouping columns
1
Performance
Trick Name Use Case Impact Benefits When to Use
UNION Combining 2-3x faster Skips When
ALL vs result sets duplicate duplicates are
UNION removal acceptable or
step impossible
Avoid Conditional 10-100x faster Allows When
Functions filtering index filtering on
in usage, calcu-
WHERE avoids lated/transformed
function values
calcula-
tion per
row