编写高效查询

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 入门

Passons à la pratique !

Redshift 入门

Preparing Video For Download...