SQL Indexing and Performance

Query tuning patterns with EXPLAIN, indexing, keyset pagination, deduplication, and optimization-oriented SQL recipes.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Execution Plans
Explain a query
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;

# Inspect the execution plan for a SELECT statement.

Explain with runtime stats
EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE customer_id = 42;

# Run a query and collect timing or actual row information where supported.

Refresh optimizer statistics
ANALYZE orders;

# Update table statistics for better planning.

## Index Strategy
Index a common lookup column
CREATE INDEX idx_users_email
ON users (email);

# Speed up frequent equality or range predicates.

Use a covering index pattern
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at);

# Create an index that supports filtering and ordering efficiently.

Avoid wrapping indexed columns in functions
-- Less index-friendly
SELECT *
FROM users
WHERE LOWER(email) = 'a@example.com';

-- Prefer normalized storage or computed/indexed support where available
SELECT *
FROM users
WHERE email = 'a@example.com';

# Preserve index usability in predicates.

## Data Quality and Maintenance Queries
Find duplicate business keys
SELECT email, COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

# Detect repeated values that should be unique.

Find orphaned child rows
SELECT o.order_id
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;

# Detect child rows missing a valid parent.

Delete duplicate rows with a CTE
WITH ranked AS (
  SELECT user_id, email,
         ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at ASC) AS rn
  FROM users
)
DELETE FROM users
WHERE user_id IN (
  SELECT user_id
  FROM ranked
  WHERE rn > 1
);

# Keep one row per key and delete the extras.

Recommended next

No recommendations yet.