Slow query

2 snippets in SQL

Also written as slow or query

SQLSQL

EXPLAIN / Query Plan

SQL · Indexes & Performance
syntax
-- PostgreSQL
EXPLAIN ANALYZE SELECT ...;
-- MySQL
EXPLAIN SELECT ...;
example
EXPLAIN ANALYZE
SELECT u.first_name, COUNT(*) AS order_count
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.is_active = true
GROUP BY u.first_name;
output
-- Shows execution plan with actual timing and row counts
-- Look for: Seq Scan (bad on big tables), Index Scan (good), Hash Join vs Nested Loop

Note EXPLAIN shows the plan; EXPLAIN ANALYZE actually runs the query and shows real timings. Use EXPLAIN (FORMAT JSON) in PostgreSQL for machine-parseable output. Never run EXPLAIN ANALYZE on destructive queries (DELETE/UPDATE) without wrapping in a transaction and rolling back.

OR Conditions and Index Usage

SQL · Common Mistakes
syntax
-- Often slow (index may not be used):
WHERE city = 'Seattle' OR state = 'WA'

-- Faster alternative:
SELECT ... WHERE city = 'Seattle'
UNION
SELECT ... WHERE state = 'WA';
example
-- May not use either index effectively:
SELECT * FROM users
WHERE email = '[email protected]'
   OR phone = '2065551234';

-- Better with UNION (each query uses its own index):
SELECT * FROM users WHERE email = '[email protected]'
UNION
SELECT * FROM users WHERE phone = '2065551234';
output
-- UNION lets each branch use its optimal index

Note OR conditions on different columns often prevent the optimizer from using indexes efficiently. Rewriting as UNION (or UNION ALL if you know there are no duplicates) lets each branch use its own index. Check with EXPLAIN to verify.