撰寫高效查詢

Redshift 入門

Jason Myers

Principal Engineer

限制欄位

  • 避免使用 SELECT *
  • 不要選取結果中不需要的欄位
    • 記住 Redshift 為欄式資料庫,會依欄位抓資料
Redshift 入門

使用 DISTKEY 與 SORTKEYs

盡量在以下子句中使用

  • JOIN
  • WHERE
  • GROUP BY

 

ORDER BY 中依序使用 SORTKEYs

  • 高度最佳化 sortkey_1, sortkey_2, sortkey_3
  • 未最佳化 sort_key_1, sort_key_3

分散式查詢

Redshift 入門

建立良好條件式(predicates)

  • 使用 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...