SQL Order of Operations

SELECT ์ฟผ๋ฆฌ ์‹คํ–‰ ์ˆœ์„œ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์•„์š”.

Reference: SQL BOLT

๋ฌธ๋ฒ• ์ˆœ์„œ

  1. SELECT column ๋ช…

  2. FROM table ๋ช…

  3. WHERE ์กฐ๊ฑด์‹

  4. GROUP BY column ๋ช…

  5. HAVING ์กฐ๊ฑด์‹

  6. ORDER BY column ๋ช…

์‹คํ–‰ ์ˆœ์„œ

  1. FROM

  2. ON

  3. JOIN

  4. WHERE

  5. GROUP BY

  6. HAVING

  7. SELECT

  8. DISTINCT

  9. ORDER BY

์‹คํ–‰ ์ˆœ์„œ ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

1. FROM and JOINs

  • JOIN์ด ๋จผ์ € ์‹คํ–‰๋˜์–ด data set์ด ๋ชจ์•„์ง„๋‹ค

  • ์ด ์ž‘์—…์—๋Š” subquery๋“ค๋„ ํฌํ•จ๋˜์–ด, JOIN ๋œ ๋ชจ๋“  row์™€ column์ด ํฌํ•จ๋œ ์ž„์‹œ table์„ ์ƒ์„ฑํ•œ๋‹ค

2. WHERE

  • Data set์„ ํ˜•์„ฑํ•˜๋ฉด, WHERE์˜ ์กฐ๊ฑด์ด ๊ฐ ํ–‰์— ์ ์šฉ๋œ๋‹ค

  • WHERE ์ ˆ์˜ ์ œ์•ฝ ์กฐ๊ฑด์€ FROM์ ˆ๋กœ ์š”์ฒญ๋œ table์— ์ ์šฉ๋œ๋‹ค

3. GROUP BY

  • WHERE ์ ˆ์ด ์ ์šฉ๋œ ํ›„ ๋‚จ์•„์žˆ๋Š” row๋“ค์€ GROUP BY์ ˆ์— ์ง€์ •๋œ column์˜ ๊ณตํ†ต๋œ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๊ทธ๋ฃนํ™”๋œ๋‹ค

  • GROUP BY ์ ˆ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๋‹น column์œผ๋กœ aggregate function (์ง‘๊ณ„ ํ•จ์ˆ˜)๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

4. HAVING

  • GROUP BY ์ ˆ์ด query์— ์žˆ๋Š” ๊ฒฝ์šฐ, HAVING ์ ˆ์˜ ์ œ์•ฝ ์กฐ๊ฑด์ด groupํ™” ๋œ row์— ์ ์šฉ๋œ๋‹ค

  • HAVING ์ ˆ์˜ ์กฐ๊ฑด ๋ณ€๊ฒฝ์€ ๊ฒฐ๊ณผ data์˜ ๋ณ€๊ฒฝ์€ ์—†๊ณ , ์ถœ๋ ฅ๋˜๋Š” record ๊ฐœ์ˆ˜๋งŒ ๋ณ€๊ฒฝ๋  ์ˆ˜ ์žˆ๋‹ค

5. SELECT

  • SELECT ์ ˆ์ด ๋งˆ์ง€๋ง‰์œผ๋กœ ์‹คํ–‰๋œ๋‹ค

6. DISTINCT

  • ๋‚จ์•„์žˆ๋Š” row ์ค‘์—์„œ, column ๊ฐ’์ด ์ค‘๋ณต๋œ row๋“ค์€ ์‚ญ์ œ๋œ๋‹ค

7.ORDER BY

  • ์ €์žฅ๋œ ๊ฐ’์„ ์˜ค๋ฆ„์ฐจ์ˆœ ํ˜น์€ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค

  • Query์˜ SELECT ์ ˆ์ด ์ด๋ฏธ ์‹คํ–‰๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์—, ORDER_BY ์ ˆ์—์„œ๋Š” alias๋ฅผ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋‹ค

Last updated