揮発性のメモ2

最近知った知識を さも昔から知ってた風にメモ書きしていく

MariaDBで、カバリングインデックスを

SELECT hiduke, jikoku, namae FROM sampleTable
    WHERE kamoku='156' 
    AND (hiduke, jikoku) >= ('2025-09-10', '18:30:00') 
    AND (hiduke, jikoku) < ('2025-09-11', '06:30:00');

こういうクエリのとき、インデックスをちゃんと張っていても 遅くなるパターンと速いパターンがあったのでメモ

MariaDB [test]> explain SELECT hiduke, jikoku, namae FROM sampleTable
    -> WHERE kamoku='156'
    -> AND (hiduke, jikoku) >= ('2025-09-10', '18:30:00')
    -> AND (hiduke, jikoku) < ('2025-09-11', '06:30:00') \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: sampleTable
         type: ref
possible_keys: kamokuIndex
          key: kamokuIndex
      key_len: 69
          ref: const,const
         rows: 620
        Extra: Using index condition; Using where

hiduke, jikoku, kamoku で複合インデックスを張っている。
何もしないよりは10倍速いんだけどそれでもちょっと遅かった。

MariaDB [test]> explain SELECT hiduke, jikoku FROM sampleTable
    -> WHERE kamoku='156'
    -> AND (hiduke, jikoku) >= ('2025-09-10', '18:30:00')
    -> AND (hiduke, jikoku) < ('2025-09-11', '06:30:00') \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: sampleTable
         type: ref
possible_keys: kamokuIndex
          key: kamokuIndex
      key_len: 69
          ref: const,const
         rows: 620
        Extra: Using where; Using index

検索結果から namae を除外したら さらに10倍速くなった。
Using index condition が Using index になったところ。


ようするに、インデックスが張ってあれば検索は早いけど 結局DBから値を取り出す(lookup)時間はかかる。
それが、全部インデックス内だけで済めば DBにアクセスしないから超速いです という理屈だった。
mariadb.com
zenn.dev