Overview
SQL is written starting with SELECT, but SELECT is one of the last steps to run. This video follows two orders: the logical order that defines a query’s result, and the physical steps the database actually chooses, known as the execution plan. Knowing both explains why some queries fail and why others are slow.
Key Points
- The logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then TOP. Aliases are created in SELECT, so they can’t be used in WHERE but do work in ORDER BY. WHERE filters the original rows, while HAVING filters the grouped results.
- The database builds the execution plan itself, choosing the cheapest route based on statistics, and caches it. A mismatch between the estimated and actual plans is a sign of outdated statistics.
- Execution plans are read from right to left. From worst to best, tables are read by table scan, index scan or index seek; key lookups, join types (nested loops, merge, hash) and cost percentages help locate the bottleneck.
- Wrapping a column in a function inside WHERE stops the index from being used. Sargable conditions, such as comparing a date range instead of calling YEAR(), keep indexes usable. SQL hints can override the database’s choices, but only as a stopgap.
- A worked example follows 250,000 rows shrinking to 10, and the video also covers B-tree indexes, the leftmost-column rule for composite indexes, covering indexes and a routine for tackling slow queries.
Chapters
- 0:00 Intro: SQL doesn’t run in the order you write it
- 2:26 The order of execution
- 4:52 What is an execution plan?
- 6:07 How to read an execution plan
- 7:47 Fixing queries with the execution plan
- 8:41 Writing sargable queries
- 9:36 SQL hints
- 10:24 Walking through a real example
- 12:25 Inside an index
- 14:12 When you run into a slow query
- 15:02 Summary
概要
SQLはSELECTから書き始めますが、SELECTが実行されるのは最後の方です。この動画では2つの順序を追いかけます。クエリの結果を決める論理的な実行順序と、データベースが実際に選ぶ物理的な手順、つまり実行計画です。この2つを知ると、あるクエリがエラーになる理由や、別のクエリが遅い理由を説明できるようになります。
ポイント
- 論理的な実行順序は FROM、WHERE、GROUP BY、HAVING、SELECT、ORDER BY、TOP です。別名はSELECTで作られるため、WHEREでは使えず、ORDER BYでは使えます。WHEREは元の行に、HAVINGは集計後の行に条件をかけます。
- 実行計画はデータベース自身が作ります。統計情報をもとに最も安い経路を選び、キャッシュに保存します。推定プランと実際のプランが食い違うときは、統計情報が古くなっている合図です。
- 実行計画は右から左へ読みます。テーブルの読み方は、悪い順にテーブルスキャン、インデックススキャン、インデックスシークです。キールックアップ、結合の種類(ネステッドループ、マージ、ハッシュ)、コストの割合からボトルネックを探します。
- WHEREの中で列を関数で包むと、インデックスが使えなくなります。YEAR関数の代わりに日付の範囲で比べるようなサーガブルな書き方なら、インデックスを使えます。SQLヒントでデータベースの判断を上書きすることもできますが、あくまで応急処置です。
- 25万行が10行になるまでを実例で追い、B-treeインデックスの仕組み、複合インデックスは左端の列から使うというルール、カバーリングインデックス、遅いクエリに出会ったときの手順も解説します。