Skip to content

Instantly share code, notes, and snippets.

@pointybeard
Created March 9, 2025 01:15
Show Gist options
  • Save pointybeard/8966f81820b693694f0564d6e68ce610 to your computer and use it in GitHub Desktop.
Save pointybeard/8966f81820b693694f0564d6e68ce610 to your computer and use it in GitHub Desktop.
MariaDB Index Maintenance & Performance Cheatsheet

MariaDB Index Maintenance & Performance Cheatsheet 🛠️🚀

1️⃣ Check for Long-Running Queries

SHOW FULL PROCESSLIST;
  • Look for queries with high Time values (e.g., >5s).
  • Identify queries stuck in "Sending data", "Copying to tmp table", or "Waiting for table lock".
SELECT * FROM information_schema.PROCESSLIST WHERE TIME > 5;
  • Shows queries running for longer than 5 seconds.

2️⃣ Check for Index Fragmentation

SELECT table_name, data_length, index_length, data_free
FROM information_schema.tables
WHERE table_schema = 'your_database_name';
  • If data_free is large, the table may be fragmented.

3️⃣ Rebuild & Optimize Indexes

OPTIMIZE TABLE tbl_entries, tbl_entries_data_411, tbl_entries_data_409, tbl_entries_data_412;
  • Reclaims unused space & defragments indexes.
  • Run periodically if tables experience frequent updates/deletes.

4️⃣ Update Query Optimizer Statistics

ANALYZE TABLE tbl_entries, tbl_entries_data_411, tbl_entries_data_409, tbl_entries_data_412;
  • Ensures MariaDB selects the best index for queries.

5️⃣ Automate Index Optimization (Optional)

📌 Run weekly via cron job

crontab -e

Add:

0 0 * * 0 mysql -u root -p'password' -e "OPTIMIZE TABLE tbl_entries, tbl_entries_data_411, tbl_entries_data_409, tbl_entries_data_412;"
  • Runs every Sunday at midnight.
  • Only enable if tables change frequently.

6️⃣ Find the Most Expensive Queries

SELECT query, total_latency, exec_count 
FROM sys.statement_analysis 
ORDER BY total_latency DESC 
LIMIT 5;
  • Shows queries consuming the most resources.

7️⃣ Check for Locking Issues

SHOW ENGINE INNODB STATUS;
  • Look for "Waiting for table lock" or "Pending writes".

8️⃣ Kill a Stuck Query

KILL <ID>;
  • Get the query ID from SHOW FULL PROCESSLIST; and terminate it.

🛠️ Best Practices

✅ Run SHOW FULL PROCESSLIST; to monitor live queries.
✅ Use OPTIMIZE TABLE if performance degrades.
Don't overuse OPTIMIZE TABLE—only when necessary.
✅ Consider Redis caching for frequently run queries.
✅ Monitor data_free to check if indexes need rebuilding.


🚀 TL;DR

  1. Queries slow?SHOW FULL PROCESSLIST;
  2. Index fragmentation?SELECT table_name, data_free FROM information_schema.tables;
  3. Fix fragmentation?OPTIMIZE TABLE tbl_name;
  4. MariaDB picking wrong indexes?ANALYZE TABLE tbl_name;
  5. Recurring optimization? → Use a cron job if needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment