dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/mysql/#28
Script #28
mysql
Monitoringread-onlyMin Version: 5.7

MySQL Connection Usage vs max_connections

Shows current connections, the peak seen and the breakdown by user and host. Used to catch 'Too many connections' errors early.

#connections#max_connections#threads
mysql · sql
SELECT
  (SELECT variable_value FROM performance_schema.global_status    WHERE variable_name='Threads_connected')   AS connected,
  (SELECT variable_value FROM performance_schema.global_status    WHERE variable_name='Max_used_connections') AS max_used,
  (SELECT variable_value FROM performance_schema.global_variables WHERE variable_name='max_connections')     AS max_connections,
  (SELECT variable_value FROM performance_schema.global_status    WHERE variable_name='Aborted_connects')    AS aborted_connects;

SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client_host, COUNT(*) AS sessions
FROM information_schema.processlist
GROUP BY user, SUBSTRING_INDEX(host, ':', 1)
ORDER BY sessions DESC
LIMIT 20;
Operational Notes & Remediation Guidance

Verify in a staging environment prior to running in production. This is a read-only diagnostic query; it does not acquire exclusive locks.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 5.7).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.