Lab 06: Query Profiling & Slow Log

Time: 45 minutes | Level: Advanced | DB: MySQL 8.0, PostgreSQL 15

Overview

Find your worst queries before they find you. This lab covers MySQL's slow query log, SHOW PROFILES, performance_schema, and PostgreSQL's pg_stat_statements and auto_explain — your complete toolkit for query performance analysis.


Step 1: MySQL — Enable Slow Query Log

docker run -d --name mysql-lab \
  -e MYSQL_ROOT_PASSWORD=rootpass \
  mysql:8.0 \
  --slow_query_log=ON \
  --long_query_time=0 \
  --log_queries_not_using_indexes=ON \
  --slow_query_log_file=/var/log/mysql/slow.log \
  --general_log=ON

for i in $(seq 1 30); do docker exec mysql-lab mysql -uroot -prootpass -e "SELECT 1" 2>/dev/null && break || sleep 2; done

docker exec mysql-lab mysql -uroot -prootpass -e "
SHOW VARIABLES LIKE 'slow_query_log%';
SHOW VARIABLES LIKE 'long_query_time';
SHOW VARIABLES LIKE 'log_queries_not_using_indexes';
"

📸 Verified Output:

💡 Setting long_query_time=0 logs ALL queries — useful for finding slow patterns in development. In production, use 1 or 2 (seconds).


Step 2: Create Test Data and Run Queries

📸 Verified Output:


Step 3: SHOW PROFILES and SHOW PROFILE FOR QUERY

📸 Verified Output:

💡 "Sending data" taking most time = full table scan. Time to add an index!


Step 4: performance_schema — Statement Statistics

📸 Verified Output:


Step 5: Fix Queries with Indexes and Measure Improvement

📸 Verified Output:


Step 6: PostgreSQL — pg_stat_statements

📸 Verified Output:


Step 7: Query pg_stat_statements

📸 Verified Output:


Step 8: Capstone — Build a Query Performance Report

📸 Verified Output:


Summary

Tool
DB
Purpose

slow_query_log

MySQL

Log queries exceeding long_query_time

log_queries_not_using_indexes

MySQL

Catch full-table scans

SHOW PROFILES

MySQL

Per-query timing breakdown

SHOW PROFILE FOR QUERY N

MySQL

Detailed stage-by-stage timing

performance_schema.events_statements_summary_by_digest

MySQL

Aggregate stats across all executions

pg_stat_statements

PostgreSQL

Aggregate query statistics extension

auto_explain

PostgreSQL

Log query plans for slow queries

log_min_duration_statement

PostgreSQL

Equivalent to MySQL's slow query log

Key Takeaways

  • SHOW PROFILES is quick for session-level debugging; performance_schema scales to production monitoring

  • pg_stat_statements is essential for PostgreSQL — install it immediately on new servers

  • SUM_NO_INDEX_USED > 0 in performance_schema = queries needing indexes

  • Before adding indexes, profile to confirm the problem; after, re-profile to confirm the fix

  • log_queries_not_using_indexes=ON in MySQL + log_min_duration_statement=1000 in PostgreSQL = your baseline production logging

Last updated