#5 Subqueries and CTEs
#5.1 Introduction
subquery์ CTE๋ฅผ ํ์ฉํด ๋ ๋์ ํ์ฉ์ด ๊ฐ๋ฅ
-- List movies with a (rating|revenue) higher than the average (rating|revenue) of all movies.
-- List movies with a rating higher than the average rating of movies in their genre.
-- Find the directors with a career revenue higher than the average revenue of all directors.
-- Find the movies with a rating higher than the average rating of movies released in the same year.
-- Make a super slow query and optimize it as much as we can with what we know so far.#5.1 Independent Subqueries
Subquery - ๋ค๋ฅธ ์ฟผ๋ฆฌ ๋ด๋ถ์ ์๋ ์ฟผ๋ฆฌ๋ก ๊ดํธ๋ก ๊ฐ์ธ ์ฌ์ฉ
Independence Subquery - ์๋ธ ์ฟผ๋ฆฌ์ ์ผ์ข ์ผ๋ก ์ฟผ๋ฆฌ์ ๊ฒฐ๊ณผ๊ฐ ๋ฐ๋์ง ์๊ธฐ์ ํ๋ฒ๋ง ์คํ์ํจ ํ ๊ฐ์ ๊ธฐ์ตํด ๋๋จธ์ง์ ํ์ฉ
-- List movies with a (rating|revenue) higher
-- than the average (rating|revenue) of all movies.
SELECT title, rating, revenue
FROM movies
WHERE
rating > (SELECT avg(rating) FROM movies) AND
revenue > (SELECT avg(revenue) FROM movies)#5.2 CTEs
Common Table Expressions - Independent Subqueries๋ฅผ ์ฌ์ฌ์ฉํ ์ ์๊ฒ ํ๋ค.
SQL ์ฟผ๋ฆฌ๋ฅผ ๋ ์์ ๋ ผ๋ฆฌ์ ๋จ์๋ก ๋๋ ๋ชจ๋์ SQL ์ฟผ๋ฆฌ๋ฅผ ๊ตฌํํ๋ค.
View์ ๋น์ทํ์ง๋ง ์๊ตฌ์ ์ด์ง ์์ผ๋ฉฐ ํด๋น ์ฟผ๋ฆฌ์ context์์๋ง ์์ฑ๋๊ณ ๋ฒ๋ ค์ง๋ค.
#5.3 Correlated Subqueries
์๊ด๊ด๊ณ ์๋ธ์ฟผ๋ฆฌ - ์ธ๋ถ ์ฟผ๋ฆฌ์ ๊ฐ์ ์ฌ์ฉํ๋ ์๋ธ์ฟผ๋ฆฌ ์ธ๋ถ ์ฟผ๋ฆฌ์์ ์ฐธ์กฐ๋๋ ํ ์ด๋ธ์์ ๋ฐ์ดํฐ๋ฅผ ๊ฒ์ํจ ์๋ธ์ฟผ๋ฆฌ์ ์คํ์ด ์ธ๋ถ ์ฟผ๋ฆฌ์ ํ์ ์ํฅ์ ๋ฐ๊ธฐ ๋๋ฌธ์ "์๊ด๋จ"์ด๋ผ๊ณ ํจ ์๊ด๊ด๊ณ๊ฐ ์๋ ์๋ธ์ฟผ๋ฆฌ์์๋ ์๋ธ์ฟผ๋ฆฌ๊ฐ ๋จผ์ ๋ ๋ฆฝ์ ์ผ๋ก ์คํ๋ ๋ค์ ํด๋น ๊ฒฐ๊ณผ๊ฐ ์ธ๋ถ ์ฟผ๋ฆฌ์ ๊ฐ์ผ๋ก ์ฌ์ฉ๋์ง๋ง, ์๊ด ๊ด๊ณ๊ฐ ์๋ ์๋ธ์ฟผ๋ฆฌ๋ ์ด์ ์ฐธ์กฐํ์ฌ ์ธ๋ถ ์ฟผ๋ฆฌ์ ์ฐ๊ฒฐ๋๊ณ ์ธ๋ถ ์ฟผ๋ฆฌ์์ ์ฒ๋ฆฌํ๋ ๊ฐ ํ์ ๋ํด ํ ๋ฒ์ฉ ๋ฐ๋ณต์ ์ผ๋ก ์คํ๋๋ค.
#5.4 Correlated CTEs
#5.5 Subquery Practice
#5.6 Final Practice
Last updated
Was this helpful?