okinawa

IT勉強メモ

SQLチューニングの一覧

早い段階で取得するデータ量を減らす

Where条件が複数ある場合、抽出する件数が少なくなる条件から先に行う。 JOINも同じ。

サブクエリを含むクエリの場合も最後にwhereで絞るのではなく、各サブクエリ内でレコード数を減らしていく。

インデックスが使われなくなる時

インデックス列を加工する

columnAにインデックスが貼ってある場合。

select * from tableA
where
columnA + 1 = columnB

select * from tableA
where
TRIM(columnA) = columnB
select * from tableA
where
columnA = columnB -1 // これならOK

否定形とOR

  • IS NULL
  • <>
  • NOT IN
  • OR

否定はINDEXが効かなくなる。
ただし、否定条件に当てはまるものが多い場合はINDEX検索よりフルスキャンの方が早くなることもあり。

・参考
SQLのチューニング方法【否定形(is not nullなど)】 | SE日記

暗黙の型変換

select * from tableA
where
columnA = 10
and columnA = '10'

複合インデックスは列の順番に注意

columnA, columnB, columnCにインデックスが張られている場合。

○ select * from tableA where columnA = 10 and columnB = 10 and columnC = 10
○ select * from tableA where columnA = 10 and columnB = 10 
✕ select * from tableA where columnA = 10 and columnC = 10
✕ select * from tableA where columnB = 10 and columnC = 10
✕ select * from tableA where columnB = 10 and columnA = 10

サブクエリを減らす

サブクエリはメモリを消費する。

select * from (
    select columnA, MAX(columnB) from tableA
    group by columnA) AS AA
where
AA.columnA > 10;

select columnA from tableA
group by clomunA
having MAX(columnB) > 10;

参考書籍