Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SQLチューニングの基礎~基礎から振り返るExplainコマンド~/chugokudb26-s...

 SQLチューニングの基礎~基礎から振り返るExplainコマンド~/chugokudb26-sql-tuning

2019-02-02 に開催された 第26回中国地方DB勉強会でのスライドです。

SQLチューニングの基礎として Explain文のご説明をさせて頂きました。

# 概要

SQLのチューニングにあたって、そもそも遅いQueryとは何か、なぜ遅くなるのか。
遅いクエリを分析するのに役立つExplainコマンドについて改めて振り返ってみたいと思います。

Takahashi Ikki

January 31, 2019
Tweet

More Decks by Takahashi Ikki

Other Decks in Programming

Transcript

  1. ஫ҙࣄ߲ • εϥΠυ͸ެ։͍ͯ͠·͢ɻ • ࣭໰ͱ͔͝ࢦఠͱ͔ॾʑͷϑΟʔυόοΫ͕͍͟͝·ͨ͠Β #ChugokuDB ΁ ͓ئ͍க͠·͢ɻ • தࠃ஍ํDBษڧձ͸

    ໺࣍ ηογϣϯதͰ΋ؾܰʹ࣭໰ͯ͠ྑ͍ͷͰ ෼͔Βͳ͍ॴ͸ηογϣϯதʹݴͬͯ௖͍ͯ΋ߏ͍·ͤΜɻ • PostgreSQLʹׂͱ࠷దԽ͞Εͨ࿩ʹͳͬͪΌ͍ͬͯ·͢ɻ • ࣮ફతͳSQLνϡʔχϯάํ๏͸ग़ͯ͜ͳ͍Ͱ͢ɺ͢Έ·ͤΜm(_ _)m 2
  2. 5

  3. Explainจ EXPLAIN SELECT * FROM companies JOIN reviews ON (companies.id

    = reviews.company_id) WHERE companies.created_at < '2019-01-30 22:10:00'; ------------------------------------------------------- Nested Loop (cost=0.28..145.39 rows=24 width=1387) -> Seq Scan on reviews (cost=0.00..2.24 rows=24 width=558) -> Index Scan using c_pkey on companies (cost=0.28..5.96 rows=1 width=829) Index Cond: (id = reviews.company_id) Filter: (created_at < '2019-01-30 22:10:00+00'::timestamp with time zone) 30
  4. Explainจ EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM companies JOIN reviews

    ON (companies.id = reviews.company_id) WHERE companies.created_at < '2019-01-30 22:10:00'; ------------------------------------------------------- Nested Loop (cost=0.28..145.39 rows=24 width=1387) (actual time=1.049..1.095 rows=24 loops=1) Buffers: shared hit=72 read=2 -> Seq Scan on reviews (cost=0.00..2.24 rows=24 width=558) (actual time=0.008..0.012 rows=24 loops=1) Buffers: shared hit=2 -> Index Scan using c_pkey on companies (cost=0.28..5.96 rows=1 width=829) (actual time=0.044..0.044 rows=1 loops=24) Index Cond: (id = reviews.company_id) Filter: (created_at < '2019-01-30 22:10:00+00'::timestamp with time zone) Buffers: shared hit=70 read=2 Planning time: 0.152 ms Execution time: 1.125 ms 33
  5. ओͳॲཧϊʔυ ॲཧϊʔυ ෼ྨ Seq Scan εΩϟϯ Nested Loop ݁߹ Index

    Scan εΩϟϯ Hash Join ݁߹ Index Only Scan εΩϟϯ Marge Join ݁߹ Bitmap Index Scan εΩϟϯ Limit Ϧϛοτ Sort ιʔτ Aggregate άϧʔϐϯάܥ 37
  6. εΩϟϯॲཧϊʔυͷҧ͍ Index Only Scan • IndexͷσʔλͷΈΛݺͼग़͍ͯ͘͠ɻ Bitmap Index Scan •

    IndexΛ࢖ͬͯ৚݅ʹ߹க͢Δ 1 or 0 ͷϏοτϚοϓΛੜ੒͠ ͦͷ಺1ͷ΋ͷ͚ͩΛॱ൪ʹݺͼग़͍ͯ͘͠ɻ 42
  7. ֤ॲཧͷ௕ॴͱτϨʔυΦϑ Index Only Scan • Index͕షΒΕͨσʔλͷΈ͕ඞཁͳ৔߹͸଎͍ɻ 10.0͔ΒɺύϥϨϧΫΤϦͷαϙʔτ Bitmap Index Scan

    • 2஋ͷ಺ɺยํͷΈΛൺֱ͢Ε͹͍͍͔Β଎͍ɻ ͨͩ͠ɺBitmapΛߏங͢Δॳظίετֻ͕͔Δɻ 44
  8. ֤ۦಈͷ௕ॴͱτϨʔυΦϑ Nested Loop Join • େ͖͍ςʔϒϧͱେ͖͍ςʔϒϧ Λ݁߹͢Δͱ n × m

    ճॲཧΛ͠ͳ͚Ε͹͍͚ͳ͍ͷͰ஗͍ɻ • ۦಈද͕খ͘͞಺෦දͷ݁߹ΩʔʹIndex͕͋Δ৔߹଎͍ɻ • 9.6͔ΒύϥϨϧΫΤϦͷαϙʔτ 49
  9. ͓͢͢Ί PostgreSQL Conference Japan 2018 ͷ νϡʔτϦΞϧτϥοΫ [T3] SQL νϡʔχϯάͷجૅ

    https://www.slideshare.net/ HarukaTakatsuka/t3-pg- sqltuningbasic20181122 https://www.youtube.com/watch? v=Bc0kIGHqjFk 57