การเขียนคิวรีให้มีประสิทธิภาพ

Introduction to Redshift

Jason Myers

Principal Engineer

จำกัดจำนวนคอลัมน์

  • หลีกเลี่ยง SELECT *
  • อย่าเลือกคอลัมน์ที่ไม่ต้องการในผลลัพธ์
    • Redshift เป็นฐานข้อมูลแบบคอลัมน์ ดึงข้อมูลทีละคอลัมน์
Introduction to Redshift

ใช้ DISTKEY และ SORTKEYs

ใช้ในส่วนคำสั่งต่อไปนี้เมื่อทำได้

  • JOIN
  • WHERE
  • GROUP BY

 

ใช้ SORTKEYs ตามลำดับใน ORDER BY

  • ปรับแต่งแล้ว sortkey_1, sortkey_2, sortkey_3
  • ยังไม่ได้ปรับแต่ง sort_key_1, sort_key_3

คิวรีแบบกระจาย

Introduction to Redshift

การสร้างเพรดิเคตที่ดี

  • ใช้ DISTKEY และ SORTKEY
  • ให้อยู่ใกล้กับส่วน JOIN ของตาราง
  • หลีกเลี่ยงการใช้ฟังก์ชันในเพรดิเคต
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;
Introduction to 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
Introduction to Redshift

ใช้ subquery อย่างชาญฉลาด

  • ใช้กลยุทธ์การ JOIN ที่เหมาะสม แทนการใช้ subquery เพียงอย่างเดียว
  • ใช้ EXISTS ในเพรดิเคตเมื่อต้องการตรวจสอบเพียงว่า subquery มีผลลัพธ์หรือไม่
    SELECT column_name
    FROM table_name
    WHERE EXISTS
      (SELECT column_name 
       FROM table_name 
       WHERE active is True);
    
  • หากใช้ subquery ซ้ำ ให้ใช้ CTE เพื่อประโยชน์จากการแคช
Introduction to Redshift

มาฝึกกันเถอะ!

Introduction to Redshift

Preparing Video For Download...