LoginSignup
0
1

More than 3 years have passed since last update.

MySQL はWHERE 句の検索条件をあまりに多く指定するとインデックスを使わずフルスキャンしてしまう

Posted at

表題通り,WHERE 句にあまりにたくさんの検索条件を指定するとフルスキャンしちゃうので SELECT のクエリは細切れに出しましょう.

公式ドキュメントいわく,

Each table index is queried, and the best index is used unless the optimizer believes that it is more efficient to use a table scan. At one time, a scan was used based on whether the best index spanned more than 30% of the table, but a fixed percentage no longer determines the choice between using an index or a scan. The optimizer now is more complex and bases its estimate on additional factors such as table size, number of rows, and I/O block size.

とのことです.
大事なのは最後の文で,ざっくり言うと「クエリオプティマイザはテーブルサイズとか列数とか IO のブロックサイズとかを見てインデックスを使うかフルスキャンするか決めます」ということです.
昔はテーブル全体の 30% 以上を舐めそうだったらフルスキャンするようにしてたみたいでググるとその手の解説も出てくるけど,今は上のようにもっと色々考えてるみたいです.

問い合わせ数を多くするコストよりもフルスキャンをさせてしまうコストの方が大きい場合が多いと思うので,オプティマイザのお気持ちを忖度してクエリを作ると良いみたいです.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1