最適なクエリの作成

Redshift入門

Jason Myers

Principal Engineer

列を絞る

  • SELECT *は避ける
  • 結果に不要な列は選択しない
    • Redshiftはカラムナで、列単位でデータを取得
Redshift入門

DISTKEY と SORTKEY の活用

可能な限り次の句で使用

  • JOIN
  • WHERE
  • GROUP BY

 

ORDER BYではSORTKEYの順に並べる

  • 高速: sortkey_1, sortkey_2, sortkey_3
  • 非最適: sort_key_1, sort_key_3

分散クエリ

Redshift入門

良い述語の作り方

  • DISTKEYSORTKEY を使用
  • テーブル結合に近い条件にする
  • それらで関数の使用は避ける
SELECT receipts.cookie_id, 
       sum(receipts.total)
FROM receipts
JOIN cookies ON receipts.cookie_id = cookies.cookie_id
  -- Keep cookies predicates in the join to push down to nodes holding the records for cookies
 AND cookies.available_on < '2023-11-14'
 AND cookies.end_of_sale IS null
-- Predicates that are not part of the join or on the joined table stay in the WHERE clause
WHERE receipts.order_time > '2023-11-13'
GROUP BY 1 ORDER BY 1;
Redshift入門

列順は一貫させる

次を使うとき:

  • GROUP BY
  • ORDER BY

悪い例

GROUP BY col_one, col_two, col_three
ORDER BY col_two, col_three, col_one

良い例

GROUP BY col_two, col_three, col_one
ORDER BY col_two, col_three, col_one
Redshift入門

サブクエリは賢く使う

  • 単なるサブクエリではなく適切な結合戦略を使う
  • サブクエリの真偽だけを確認するなら述語にEXISTSを使用
    SELECT column_name
    FROM table_name
    WHERE EXISTS
      (SELECT column_name 
       FROM table_name 
       WHERE active is True);
    
  • サブクエリを再利用するなら、キャッシュ活用のためにCTEを使用
Redshift入門

実践してみましょう!

Redshift入門

Preparing Video For Download...