// Performance Tuning
MySQL Performance Tuning
เพิ่มประสิทธิภาพฐานข้อมูลของคุณในทุกระดับ — ตั้งแต่ Server Configuration ไปจนถึง Query Optimization
// Tuning Areas
2 ระดับของ MySQL Performance Tuning
Server Level Tuning
ปรับแต่ง MySQL Server Configuration เพื่อใช้ Resources ของเครื่องให้เกิดประโยชน์สูงสุด
Query Level Tuning
วิเคราะห์และปรับปรุง SQL Query ให้ทำงานเร็วขึ้น ลด Full Table Scan และใช้ Index อย่างมีประสิทธิภาพ
// Key Areas
ส่วนสำคัญในการ Tune
Query Cache
Query Cache เก็บผลลัพธ์ของ SELECT Query ไว้ใน Memory ทำให้ Query ซ้ำๆ ทำงานได้เร็วขึ้นมาก ต้องตั้งค่า query_cache_size, query_cache_type ให้เหมาะสม
Table Indexing
Index ที่ออกแบบดีสามารถเพิ่มความเร็ว Query ได้หลายร้อยเท่า ใช้ EXPLAIN เพื่อวิเคราะห์ Query Execution Plan และตรวจสอบว่า Index ถูกใช้งานหรือไม่
Storage Engine Config
InnoDB Buffer Pool, Log File Size และ Transaction Isolation Level ล้วนมีผลต่อประสิทธิภาพอย่างมาก ควร Set ให้เหมาะกับ Workload
Server Hardware
RAM ขนาดใหญ่ช่วยให้ InnoDB Buffer Pool รองรับข้อมูลได้มากขึ้น SSD ช่วยลด I/O Latency และ CPU Cores หลายตัวช่วย Parallel Query
EXPLAIN & Profile
ใช้ EXPLAIN เพื่อดู Query Plan และ SHOW PROFILE เพื่อวิเคราะห์เวลาที่ใช้ในแต่ละส่วนของ Query Execution
Connection Pooling
บริหาร Database Connection อย่างมีประสิทธิภาพด้วย Connection Pool ลด Overhead ของการสร้าง Connection ใหม่ทุกครั้ง
// Quick Wins
Configuration ที่ควรปรับทันที
# /etc/mysql/my.cnf — Key Performance Settings
[mysqld]
innodb_buffer_pool_size = 2G # 70-80% of RAM
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2 # 1=safe, 2=fast
innodb_flush_method = O_DIRECT
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M
max_connections = 200
thread_cache_size = 50
table_open_cache = 2000
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
// Indexing Tips
Best Practices สำหรับ Index
-- วิเคราะห์ Query Plan
EXPLAIN SELECT * FROM orders
WHERE customer_id = 123
AND status = 'pending';
-- สร้าง Composite Index
CREATE INDEX idx_cust_status
ON orders(customer_id, status);
-- ตรวจสอบ Index ที่ไม่ได้ใช้
SELECT * FROM sys.schema_unused_indexes;
// Slow Query
วิเคราะห์ Slow Queries
-- ดู Slow Queries ด้วย mysqldumpslow
$ mysqldumpslow -s t -t 10 \
/var/log/mysql/slow.log
-- Performance Schema
SELECT query, exec_count,
avg_latency
FROM sys.statement_analysis
ORDER BY avg_latency DESC
LIMIT 10;
ต้องการ Tune MySQL ของคุณ?
ทีมผู้เชี่ยวชาญของเราพร้อม Audit และ Tune ระบบฐานข้อมูลของคุณให้ทำงานได้อย่างเต็มประสิทธิภาพ