⚡

Query Optimization

Write faster, more efficient SQL queries.

Section 1 of 3: Query Optimization Principles0%

Query Optimization Principles

Study Material

The Three Laws of Query Optimization:

1. Reduce Data Scanned 📉

The fastest query reads the least data.

Tactics:

  • Use selective WHERE clauses early
  • Leverage partitioning (only read relevant partitions)
  • Use covering indexes (avoid table access)
  • Filter before joining

2. Minimize Data Movement 🚚

Moving data between nodes/processes is expensive.

Tactics:

  • Push predicates down (filter at source)
  • Avoid SELECT * (only select needed columns)
  • Aggregate before joining when possible
  • Use broadcast joins for small tables

3. Optimize Operations ⚙️

Some operations are more expensive than others.

Cost hierarchy (most to least expensive):

  1. 1Cartesian product (CROSS JOIN)
  2. 2Sorting large datasets (ORDER BY)
  3. 3Hash joins on large tables
  4. 4Full table scans
  5. 5Index range scans
  6. 6Index point lookups

Common Anti-Patterns to Avoid:

❌ Functions on indexed columns:

WHERE YEAR(order_date) = 2024

-- Can't use index on order_date!

✅ Sargable alternative:

WHERE order_date >= '2024-01-01' AND order_date < '2025-01-01'

-- Uses index!

❌ Leading wildcards:

WHERE name LIKE '%Smith'

-- Full scan required

✅ Trailing wildcard:

WHERE name LIKE 'Smith%'

-- Can use index

❌ Implicit type conversion:

WHERE customer_id = '100' -- customer_id is INT

-- May prevent index use

✅ Matching types:

WHERE customer_id = 100

❌ OR across different columns:

WHERE customer_id = 100 OR product_id = 200

-- Often can't use indexes efficiently

✅ UNION alternative:

SELECT * FROM orders WHERE customer_id = 100

UNION ALL

SELECT * FROM orders WHERE product_id = 200 AND customer_id != 100