Optimale queries schrijven

Introductie tot Redshift

Jason Myers

Principal Engineer

Beperk kolommen

  • Vermijd SELECT *
  • Selecteer geen kolommen die je niet nodig hebt in het resultaat
    • Redshift is kolom-georiënteerd en haalt per kolom op
Introductie tot Redshift

Gebruik DISTKEY en SORTKEYs

Gebruik waar mogelijk in de volgende clausules

  • JOIN
  • WHERE
  • GROUP BY

 

Gebruik SORTKEYs in volgorde in ORDER BY

  • Sterk geoptimaliseerd: sortkey_1, sortkey_2, sortkey_3
  • Niet geoptimaliseerd: sort_key_1, sort_key_3

Gedistribueerde queries

Introductie tot Redshift

Goede predicaten bouwen

  • Gebruik DISTKEY en SORTKEY
  • Dicht bij de table join
  • Vermijd functies erin
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;
Introductie tot Redshift

Wees consistent in kolomvolgorde

Bij gebruik van:

  • GROUP BY
  • ORDER BY

Slecht

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

Goed

GROUP BY col_two, col_three, col_one
ORDER BY col_two, col_three, col_one
Introductie tot Redshift

Gebruik subqueries verstandig

  • Gebruik passende join-strategieën i.p.v. zomaar een subquery
  • Gebruik EXISTS in je predicaten als je alleen wilt controleren of een subquery iets oplevert
    SELECT column_name
    FROM table_name
    WHERE EXISTS
      (SELECT column_name 
       FROM table_name 
       WHERE active is True);
    
  • Hergebruik je subqueries met CTE’s om caching te benutten
Introductie tot Redshift

Laten we oefenen!

Introductie tot Redshift

Preparing Video For Download...