Loading
Portfolio
Rayden Li
MySQL
Slow database queries are the single most common bottleneck in backend applications. Fixing them follows a two-step workflow: isolate the exact queries consuming excessive time or resources, then analyze and rewrite how the database executes them.
Before changing any code or adding indexes, gather telemetry to pinpoint which queries are actually degrading performance.
Most relational databases include a built-in logger that records queries exceeding a specific execution threshold (e.g., 500ms or 1 second).
postgresql.conf to log statements taking longer than 500 milliseconds:log_min_duration_statement = 500
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.5;
Logs show individual slow events, while system views aggregate statistics to reveal queries that run slightly slow millions of times—often causing more total load than a single 10-second query.
pg_stat_statements):SELECT
calls,
round(total_exec_time::numeric, 2) AS total_time_ms,
round(mean_exec_time::numeric, 2) AS avg_time_ms,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
performance_schema):SELECT
COUNT_STAR AS exec_count,
ROUND(SUM_TIMER_WAIT / 1000000000, 2) AS total_ms,
ROUND(AVG_TIMER_WAIT / 1000000000, 2) AS avg_ms,
DIGEST_TEXT
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 10;
Once you identify a culprit, run EXPLAIN ANALYZE (PostgreSQL/MySQL 8.0+) to see the exact path the database engine took to fetch the data.
EXPLAIN ANALYZE
SELECT id, status, created_at
FROM orders
WHERE customer_id = 4092 AND status = 'pending';
Red flags to look for in the output:
Sort Method: external merge Disk): The query ran out of working memory (work_mem) during sorting or grouping and had to write temporary files to disk.estimated rows and actual rows, indicating stale table statistics.Once you know why a query is slow from its execution plan, apply the targeted optimizations below.
Indexes allow the database to jump directly to matching rows rather than scanning the entire table.
WHERE, JOIN ON, and ORDER BY clauses.=) first, followed by range conditions (>, <, BETWEEN).-- Optimal for: WHERE customer_id = 4092 AND created_at > '2026-01-01'
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);
CREATE INDEX idx_orders_covering ON orders (customer_id, status) INCLUDE (total_amount);
A query is SARGable when the indexed column sits cleanly on one side of a comparison operator. Wrapping an indexed column in a function or math operation forces a full table scan.
| Anti-Pattern (Breaks Index) | Tuned Version (Uses Index) |
|---|---|
WHERE YEAR(created_at) = 2026 | WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01' |
WHERE LOWER(email) = '[email protected]' | WHERE email = '[email protected]' (with a functional/case-insensitive index) |
WHERE price * 1.1 > 100 | WHERE price > 100 / 1.1 |
SELECT * and Over-FetchingFetching every column in a wide table increases network payload, saturates memory buffers, and prevents the database from using fast Index-Only Scans.
LIMIT when paginating results, and prefer keyset (cursor) pagination (WHERE id > last_seen_id LIMIT 50) over OFFSET (OFFSET 50000 LIMIT 50), because OFFSET still forces the database to read and discard all skipped rows.An N+1 problem happens when application code executes 1 query to fetch a list of parent records, and then loops through them to execute N separate queries for child records.
JOIN or use batch fetching (WHERE user_id IN (1, 2, 3, ...)).Query planners rely on metadata statistics to choose between a table scan and an index scan. If a table undergoes massive inserts, updates, or deletes, those statistics become inaccurate.
VACUUM ANALYZE table_name; to reclaim dead row space and refresh planner statistics.ANALYZE TABLE table_name; to update index cardinality distributions.