Index Condition Pushdown (ICP) 是 MySQL 5.6 引入的重要優化特性,針對使用二級索引查詢的場景,將部分 WHERE 條件下推至儲存引擎層過濾,大幅減少回表次數與網路交互。
未啟用 ICP 時:儲存引擎遍歷索引 → 定位基表讀取完整行 → 回傳 Server 層 → Server 評估 WHERE 條件 → 不滿足則丟棄。
啟用 ICP 後:Server 將可由索引欄位評估的條件下推 → 儲存引擎讀取索引項 → 直接用索引欄位判斷 → 僅滿足條件時才回表讀取完整行 → 回傳 Server。
使用官方 employees 測試資料庫,建立複合索引 index_bh (birth_date, hire_date):
ALTER TABLE employees ADD INDEX index_bh (birth_date, hire_date);
查詢條件:
SELECT * FROM employees
WHERE birth_date BETWEEN '1955-01-01' AND '1955-12-31'
AND DATEDIFF(hire_date, birth_date) > 12300
AND first_name LIKE 'S%b%';
EXPLAIN 對比:
Extra: Using where,耗時 0.123 秒Extra: Using index condition; Using where,耗時 0.074 秒效能提升約 40%,DATEDIFF(hire_date, birth_date) > 12300 可直接在索引層過濾,避免大量回表。
type 為 range、ref、eq_ref、ref_or_null-- 檢查狀態
SELECT @@optimizer_switch LIKE '%index_condition_pushdown%';
-- 動態開啟/關閉
SET optimizer_switch = 'index_condition_pushdown=on|off';
預設為開啟,建議生產環境保持開啟,除非特定場景經測試證明關閉更優。