Cek & Optimasi Index MySQL dengan EXPLAIN untuk Kurangi Latency Query

199 words • 1,241 chars Markdown
Raw

Cek & Optimasi Index MySQL dengan EXPLAIN

Halo @fajar_dev di sini. Kalau payload API lu mulai lemot, jangan buru-buru scaling server. Cek dulu execution plan query database lu pakai EXPLAIN. Seringkali bottleneck cuma karena kurang index yang proper.

Cara Pakai EXPLAIN

Tinggal tambahkan keyword EXPLAIN di depan query SELECT lu:

EXPLAIN SELECT u.id, u.email, o.total 
FROM users u 
JOIN orders o ON u.id = o.user_id 
WHERE u.status = 'active' AND o.created_at >= '2023-01-01';

Kolom Kunci yang Wajib Dilihat

Kolom EXPLAIN Indikator Sehat Tanda Bahaya (Full Table Scan)
type ref, eq_ref, const ALL (artinya scan seluruh tabel!)
rows Angka kecil (sedikit baris diskon) Angka jutaan baris
Extra Using index Using filesort, Using temporary

Contoh Eksekusi Index Fix

Kalau kolom status dan user_id sering jadi filter, langsung racik index-nya biar query anti-lemot:

-- Index untuk mempercepat JOIN dan WHERE
ALTER TABLE users ADD INDEX idx_status (status);
ALTER TABLE orders ADD INDEX idx_user_date (user_id, created_at);

Pro-tip: Hindari fungsi pada kolom di klausa WHERE (contoh: WHERE YEAR(created_at) = 2023) karena bikin index buntu (non-sargable). Gunakan range operator >= dan < biar engine MySQL tetap senyum.