SQLiteのJOIN順序を変えたら、処理が173秒から1秒になった話

田中博悠 / tanahiro2010

田中博悠 / tanahiro2010

  • 三田学園高等学校 1年
  • ghusage を作ってる

tanahiro2010

今日話すこと

ghusage

npm install -g ghusage
ghusage sync
ghusage

こういうのが出る

::wide::

ghusage の実行結果

草だけじゃわからない

仕組み

イベントとアカウント

ある日の CI

ログを見る

macos-15 03:12:50 Testing cached 7-day aggregation (load + overview)
macos-15 03:15:43 Success
macos-15 03:15:43 Testing cached 30-day aggregation (load + overview)
macos-15 03:19:43 Success

173 秒

どの OS でも遅い

10 万イベント・デバッグビルド・7 日分を 1 回

何をしてる?

犯人のクエリ

SELECT ... FROM activity_events e
JOIN account_events ae ON ae.event_id = e.event_id
WHERE ae.account_id = ?1 AND e.parent_pr_id = ?2

インデックスもある

EXPLAIN QUERY PLAN

|--SEARCH ae USING PRIMARY KEY (account_id=?)
`--SEARCH e USING INDEX sqlite_autoindex_activity_events_1 (event_id=?)

SEARCH って出てる

外側と内側が逆だった

::wide::

JOIN の順序

なぜ?

統計がなかった

公式に名前がついてる

A low-quality index (...) is one where there are more than 10 or 20 rows in the table that have the same value for the left-most column of the index.

https://www.sqlite.org/queryplanner-ng.html

直し方

SELECT ... FROM activity_events e
CROSS JOIN account_events ae ON ae.event_id = e.event_id
WHERE e.parent_pr_id = ?2 AND ae.account_id = ?1

CROSS JOIN は並べ替えない

SQLite chooses to never reorder tables in a CROSS JOIN.

https://www.sqlite.org/optoverview.html

修正後の実行計画

|--SEARCH e USING INDEX activity_events_parent_pr (parent_pr_id=?)
`--SEARCH ae USING COVERING INDEX account_events_event (event_id=? AND account_id=?)

テストにした

#[test]
fn pull_request_events_are_found_through_the_parent_index() {
    let plan: Vec<String> = query_list(
        &store.conn,
        &format!("EXPLAIN QUERY PLAN {}", pr_events_sql()),
        params![1, "PR_x"],
        |r| Ok(r.get::<_, String>(3)?),
    )
    .unwrap();
    assert!(plan[0].contains("activity_events_parent_pr"));
}

手元で再現してみた

macOS 26.5 / Apple M4 / SQLite 3.51.0

ANALYZE すると?

公式もそう言ってる

Update 2024: The query planner has been improved so much over the years that you should never need to use any of the hacks described below.

https://www.sqlite.org/queryplanner-ng.html

じゃあ CROSS JOIN はダメ?

CI も速くなった

まとめ

ghusage を使ってみて

  • npm install -g ghusage
  • Docs: https://ghusage.under18.dev
  • GitHub: https://github.com/tanahiro2010/ghusage
https://ghusage.under18.dev
← → 移動 ・ f フルスクリーン ・ o 一覧 ・ p 発表者
記事版を読む →