Querystructuur en -uitvoering

Queryprestaties verbeteren in PostgreSQL

Amy McCarty

Instructor

Subqueries en joins

-- SUBQUERY
SELECT COUNT(athlete_id)
FROM athletes
WHERE country IN 
  (SELECT country FROM climate 
    WHERE temp_annual > 22)
-- JOIN
SELECT COUNT(athlete_id)
FROM athletes a
INNER JOIN climate c
  ON a.country = c.country
  AND c.temp_annual > 22
Queryprestaties verbeteren in PostgreSQL

Queryplan

Aggregate  ()
  ->  Hash Join  ()
        Hash Cond: (athletes.country = climate.country)
        ->  Seq Scan on athletes  ()
        ->  Hash  ()
              ->  Seq Scan on climate  ()
                    Filter: (temp_annual > '22'::numeric)
Queryprestaties verbeteren in PostgreSQL

CTE's en tijdelijke tabellen

-- CTE
WITH celsius AS 
(
  SELECT country 
  FROM climate 
  WHERE temp_annual > 22 -- Celsius
)
SELECT count(athlete_id)
FROM athletes a
INNER JOIN celsius c
  ON a.country = c.country
-- TEMP TABLE
CREATE TEMPORARY TABLE celsius AS 
  SELECT country 
  FROM climate 
  WHERE temp_annual > 22; -- Celsius

SELECT count(athlete_id)
FROM athletes a
INNER JOIN celsius c
  ON a.country = c.country
Queryprestaties verbeteren in PostgreSQL

Queryplan

  Aggregate  ()
  CTE celsius
    ->  Seq Scan on climate  ()
          Filter: (temp_annual > '22'::numeric)
  ->  Hash Join  ()
        Hash Cond: (a.country_code = c.country_code)
        ->  Seq Scan on athletes a  ()
        ->  Hash  ()
              ->  CTE Scan on celsius c  ()
Queryprestaties verbeteren in PostgreSQL

Gegevens beperken

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
Queryprestaties verbeteren in PostgreSQL

Gegevens beperken

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
Geen index Index
Planningstijd: 3,370 ms Planningstijd: 0,163 ms
Uitvoeringstijd: 0,143 ms Uitvoeringstijd: 0,062 ms
Queryprestaties verbeteren in PostgreSQL

Aggregaties - verschillende granulariteiten

 

SELECT r.country
  , COUNT(a.athlete_id) as athletes
FROM regions r -- country level
INNER JOIN athletes a -- athletes level
  ON r.country = a.country
GROUP BY r.country

 

 

  • Uitvoeringstijd: 0,267 ms
Queryprestaties verbeteren in PostgreSQL

Aggregaties - granulariteit wijzigen

WITH olympians AS ( -- country level
  SELECT country
  , COUNT(athlete_id) as athletes
  FROM athletes -- athletes level
  GROUP BY country
)
SELECT country, athletes
FROM regions r -- country level
INNER JOIN olympians o
  ON r.country = o.country
Uitvoeringstijd
Eerst join 0,267 ms
Eerst aggregeren 0,192 ms
Queryprestaties verbeteren in PostgreSQL

Laten we oefenen!

Queryprestaties verbeteren in PostgreSQL

Preparing Video For Download...