Struttura ed esecuzione delle query

Migliorare le prestazioni delle query in PostgreSQL

Amy McCarty

Instructor

Subquery e join

-- 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
Migliorare le prestazioni delle query in PostgreSQL

Piano di esecuzione

Aggregate  ()
  ->  Hash Join  ()
        Hash Cond: (athletes.country = climate.country)
        ->  Seq Scan on athletes  ()
        ->  Hash  ()
              ->  Seq Scan on climate  ()
                    Filter: (temp_annual > '22'::numeric)
Migliorare le prestazioni delle query in PostgreSQL

CTE e tabelle temporanee

-- 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
Migliorare le prestazioni delle query in PostgreSQL

Piano di esecuzione

  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  ()
Migliorare le prestazioni delle query in PostgreSQL

Limitare i dati

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
Migliorare le prestazioni delle query in PostgreSQL

Limitare i dati

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
No Index Indice
Planning Time: 3.370 ms Planning Time: 0.163 ms
Execution Time: 0.143 ms Execution Time: 0.062 ms
Migliorare le prestazioni delle query in PostgreSQL

Aggregazioni - granularità diverse

 

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

 

 

  • Execution Time : 0.267 ms
Migliorare le prestazioni delle query in PostgreSQL

Aggregazioni - cambiare la granularità

WITH olympians AS ( -- livello paese
  SELECT country
  , COUNT(athlete_id) as athletes
  FROM athletes -- livello atleti
  GROUP BY country
)
SELECT country, athletes
FROM regions r -- livello paese
INNER JOIN olympians o
  ON r.country = o.country
Execution Time
Join prima 0.267 ms
Aggrega prima 0.192 ms
Migliorare le prestazioni delle query in PostgreSQL

Passiamo alla pratica !

Migliorare le prestazioni delle query in PostgreSQL

Preparing Video For Download...