Meningkatkan Performa Kueri di PostgreSQL
Amy McCarty
Instructor
-- 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
Aggregate ()
-> Hash Join ()
Hash Cond: (athletes.country = climate.country)
-> Seq Scan on athletes ()
-> Hash ()
-> Seq Scan on climate ()
Filter: (temp_annual > '22'::numeric)
-- 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
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 ()
SELECT country_code
, COUNT(athlete_id) as athletes
FROM athletes
WHERE year in (2014, 2010) -- Indexed column
GROUP BY country_code
SELECT country_code
, COUNT(athlete_id) as athletes
FROM athletes
WHERE year in (2014, 2010) -- Indexed column
GROUP BY country_code
| Tanpa Indeks | Dengan Indeks |
|---|---|
| Waktu Perencanaan: 3,370 ms | Waktu Perencanaan: 0,163 ms |
| Waktu Eksekusi: 0,143 ms | Waktu Eksekusi: 0,062 ms |
SELECT r.country
, COUNT(a.athlete_id) as athletes
FROM regions r -- tingkat negara
INNER JOIN athletes a -- tingkat atlet
ON r.country = a.country
GROUP BY r.country
WITH olympians AS ( -- tingkat negara
SELECT country
, COUNT(athlete_id) as athletes
FROM athletes -- tingkat atlet
GROUP BY country
)
SELECT country, athletes
FROM regions r -- tingkat negara
INNER JOIN olympians o
ON r.country = o.country
| Waktu Eksekusi | |
|---|---|
| Join lebih dulu | 0,267 ms |
| Agregasi lebih dulu | 0,192 ms |
Meningkatkan Performa Kueri di PostgreSQL