理解查询性能

Redshift 入门

Jason Myers

Principal Architect

查询优化流程

  1. 查看 STL_ALERT_EVENT_LOG
  2. 对查询运行 EXPLAIN
  3. 查看 SVL_QUERY_SUMMARYSVL_QUERY_REPORT
Redshift 入门

STL_ALERT_EVENT_LOG 表

包含查询触发的任何 Redshift 警报

SELECT * 
  FROM stl_alert_event_log 
 WHERE query = 1337;
 query |             event             |          solution       |     event_time      
=======+===============================+=========================+====================
  1337 | Missing query planner statist | Run the ANALYZE command | 2023-11-13 18:20:58
Redshift 入门

用 EXPLAIN 查看执行计划

  • 显示查询的所有步骤及其相对成本和扫描行数

  • 适用于所有数据操作语言(DML)语句:

    • SELECT
    • SELECT INTO
    • CREATE TABLE AS
    • INSERT
    • UPDATE
    • DELETE
Redshift 入门

EXPLAIN 示例

-- Running EXPLAIN on our top ten divisions by 
-- revenue query
EXPLAIN WITH top_ten_divisions_by_rev AS
(
  SELECT division_id,
         SUM(revenue) AS revenue_total
    FROM sales_data
   GROUP BY division_id
   ORDER BY revenue_total DESC
   LIMIT 10
),
division_names AS
(
  SELECT id AS division_id,
         name AS division_name
    FROM division_names
)
SELECT division_name,
       revenue_total
  FROM top_ten_divisions_by_rev
  JOIN division_names USING (DIVISION_ID)
 WHERE revenue_total > 100000;
Redshift 入门

解读结果

|QUERY PLAN                                                                                      |
+------------------------------------------------------------------------------------------------+
|Hash Join  (cost=47.11..58.89 rows=3 width=524)                                                 |
|  Hash Cond: (division_names.id = top_ten_divisions_by_rev.division_id)                         |

| -> Seq Scan on division_names (cost=0.00..11.40 rows=140 width=520) | | -> Hash (cost=47.07..47.07 rows=3 width=12) |
| -> Subquery Scan on top_ten_divisions_by_rev (cost=46.92..47.07 rows=3 width=12) | | Filter: (top_ten_divisions_by_rev.revenue_total > 100000) | | -> Limit (cost=46.92..46.95 rows=10 width=12) |
| -> Sort (cost=46.92..47.42 rows=200 width=12) | | Sort Key: (sum(sales_data.revenue)) DESC |
| -> HashAggregate (cost=40.60..42.60 rows=200 width=12) | | Group Key: sales_data.division_id | | -> Seq Scan on sales_data (cost=0.00..30.40 rows=2040 width=8)|
1 https://www.postgresql.org/docs/current/using-explain.html
Redshift 入门

Passons à la pratique !

Redshift 入门

Preparing Video For Download...