Useful Data Tips

Reading SQL Execution Plans

⏱️ 30 sec read 📊 SQL

Execution plans show how the database executes your query. Reading them helps identify bottlenecks, missing indexes, and inefficient operations for optimization.

Viewing Execution Plans

PostgreSQL

EXPLAIN ANALYZE
SELECT * FROM orders
WHERE customer_id = 123;

MySQL

EXPLAIN
SELECT * FROM orders
WHERE customer_id = 123;

SQL Server

SET SHOWPLAN_TEXT ON;
GO
SELECT * FROM orders
WHERE customer_id = 123;
GO

Key Operations to Look For

Table Scan (Bad - Slow)

Seq Scan on orders (cost=0.00..1500.00 rows=100000)
-- Reading every row - missing index!

Index Seek (Good - Fast)

Index Seek on idx_customer (cost=0.29..8.31 rows=1)
-- Using index - efficient!

Nested Loop Join

Nested Loop (cost=0.58..24.75 rows=5)
-- Good for small datasets, slow for large ones

Hash Join

Hash Join (cost=15.50..45.25 rows=500)
-- Good for large datasets with equality conditions

Common Performance Issues

Missing Index

-- Before (Table Scan)
EXPLAIN SELECT * FROM orders WHERE customer_id = 123;
-- Seq Scan on orders (cost=0.00..1500.00)

-- Add index
CREATE INDEX idx_customer ON orders(customer_id);

-- After (Index Seek)
EXPLAIN SELECT * FROM orders WHERE customer_id = 123;
-- Index Scan using idx_customer (cost=0.29..8.31)

SELECT * Instead of Specific Columns

-- Bad (more data to read)
SELECT * FROM orders WHERE status = 'shipped';

-- Good (only needed columns)
SELECT order_id, customer_id, total FROM orders WHERE status = 'shipped';

What to Watch For

Pro Tip: Run EXPLAIN ANALYZE regularly on slow queries. Focus on operations with the highest cost first. Adding the right index can reduce query time from minutes to milliseconds.

← Back to SQL Tips