쿼리 구조와 실행

PostgreSQL에서 쿼리 성능 개선하기

Amy McCarty

Instructor

서브쿼리와 조인

-- 서브쿼리
SELECT COUNT(athlete_id)
FROM athletes
WHERE country IN 
  (SELECT country FROM climate 
    WHERE temp_annual > 22)
-- 조인
SELECT COUNT(athlete_id)
FROM athletes a
INNER JOIN climate c
  ON a.country = c.country
  AND c.temp_annual > 22
PostgreSQL에서 쿼리 성능 개선하기

쿼리 계획

Aggregate  ()
  ->  Hash Join  ()
        Hash Cond: (athletes.country = climate.country)
        ->  Seq Scan on athletes  ()
        ->  Hash  ()
              ->  Seq Scan on climate  ()
                    Filter: (temp_annual > '22'::numeric)
PostgreSQL에서 쿼리 성능 개선하기

CTE와 임시 테이블

-- 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
-- 임시 테이블
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
PostgreSQL에서 쿼리 성능 개선하기

쿼리 계획

  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  ()
PostgreSQL에서 쿼리 성능 개선하기

데이터 제한하기

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
PostgreSQL에서 쿼리 성능 개선하기

데이터 제한하기

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
인덱스 없음 인덱스 있음
계획 시간: 3.370 ms 계획 시간: 0.163 ms
실행 시간: 0.143 ms 실행 시간: 0.062 ms
PostgreSQL에서 쿼리 성능 개선하기

집계 - 서로 다른 세분화

 

SELECT r.country
  , COUNT(a.athlete_id) as athletes
FROM regions r -- 국가 수준
INNER JOIN athletes a -- 선수 수준
  ON r.country = a.country
GROUP BY r.country

 

 

  • 실행 시간: 0.267 ms
PostgreSQL에서 쿼리 성능 개선하기

집계 - 세분화 변경

WITH olympians AS ( -- 국가 수준
  SELECT country
  , COUNT(athlete_id) as athletes
  FROM athletes -- 선수 수준
  GROUP BY country
)
SELECT country, athletes
FROM regions r -- 국가 수준
INNER JOIN olympians o
  ON r.country = o.country
실행 시간
먼저 조인 0.267 ms
먼저 집계 0.192 ms
PostgreSQL에서 쿼리 성능 개선하기

Lass uns üben!

PostgreSQL에서 쿼리 성능 개선하기

Preparing Video For Download...