Interview Prep/Shell Scripting/Scenarios: text processing and scheduling decisions

A MySQL slow log is 3 GB. You need the 10 slowest query patterns. What do you do?

IntermediateScenarioScenarios: text processing and scheduling decisions
Answer

Situation read → Raw greps show individual queries; you want patterns (normalized queries) with total and max time.

What I'd do →

  1. Use the right tool first: pt-query-digest /var/log/mysql/slow.log > report.txt (Percona Toolkit) or mysqldumpslow -s t -t 10 slow.log.
  2. If neither is installed, extract Query_time with awk:
    awk '/^# Query_time:/ {t = $3; next}
         /^(SELECT|UPDATE|DELETE|INSERT)/ {q = $0; gsub(/[0-9]+/, "N", q); gsub(/'"'"'[^'"'"']*'"'"'/, "S", q)
                                           sum[q] += t; n[q]++; if (t > max[q]) max[q] = t}
         END {for (q in sum) printf "%.1f\t%d\t%.2f\t%s\n", sum[q], n[q], max[q], substr(q, 1, 120)}' slow.log |
      sort -rn | head
    
  3. Run it on a copy or with nice, not on a busy database host's disk.

Why → Normalizing literals groups thousands of executions of the same query, which is what you optimize.

Interview tip → Lead with pt-query-digest; reaching for the right tool beats clever awk.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: text processing and scheduling decisions