ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/DataBase

[SQL] ORDER BY ์ ˆ

NaNaRin๐Ÿ™ƒ 2021. 2. 19. 22:11

1. ORDER BY ์ ˆ

- ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•  ๋•Œ ์‹œ๊ฐ„์ด๋‚˜ ์ด๋ฆ„ ์ˆœ์„œ ๋˜๋Š” ์–ด๋–ค ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ •๋ ฌํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ORDER BY์ ˆ ์‚ฌ์šฉ

- SELECT๋ฌธ์„ ์ž‘์„ฑํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์—ฌ๋Ÿฌ ์ ˆ ์ค‘ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— ์ž‘์„ฑ

- ์ˆซ์ž ๋ฟ ์•„๋‹ˆ๋ผ ๋ฌธ์ž ๋ฐ์ดํ„ฐ ๋˜ํ•œ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ๋‚ ์งœ ๋ฐ์ดํ„ฐ๋„ ์ •๋ ฌ์ด ๊ฐ€๋Šฅ

- ์ •๋ ฌ ์˜ต์…˜์„ ์ง€์ •ํ•˜์ง€ ์•Š์œผ๋ฉด ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์„ค์ •. default ASC

- ์˜ค๋ฆ„์ฐจ์ˆœ ASC / ๋‚ด๋ฆผ์ฐจ์ˆœ DESC

SELECT 	[์กฐํšŒํ•  ์นผ๋Ÿผ 1 ์ด๋ฆ„], [์นผ๋Ÿผ 2 ์ด๋ฆ„], … , [์นผ๋Ÿผ N ์ด๋ฆ„]
FROM 	[์กฐํšŒํ•  ํ…Œ์ด๋ธ” ์ด๋ฆ„]
…
( ๊ทธ ๋ฐ–์˜ ์ ˆ )
…
ORDER BY [์ •๋ ฌํ•˜๋ ค๋Š” ์นผ๋Ÿผ ์ด๋ฆ„] [์ •๋ ฌ ์˜ต์…˜];

-- 1. ์˜ค๋ฆ„์ฐจ์ˆœ ์‚ฌ์šฉ
SELECT * FROM EMP ORDER BY SAL;
SELECT * FROM EMP ORDER BY SAL, DEPTNO;

-- 2. ๋‚ด๋ฆผ์ฐจ์ˆœ ์‚ฌ์šฉ
SELECT * FROM EMP
ORDER BY SAL DESC;

-- 3. ๋‘˜ ๋‹ค ์‚ฌ์šฉ
SELECT * FROM EMP
ORDER BY DEPTNO ASC, SAL DESC;

  (1) ์˜ค๋ฆ„์ฐจ์ˆœ ์‚ฌ์šฉ : SAL ์นผ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ, SAL์ด ๊ฐ™์œผ๋ฉด DEPTNO ์นผ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ

  (2) ๋‚ด๋ฆผ์ฐจ์ˆœ ์‚ฌ์šฉ : SAL ์นผ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

  (3) ๋‘˜ ๋‹ค ์‚ฌ์šฉ : DEPNO ์นผ๋Ÿผ์„ ๊ธฐ๋ถ„์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ, DEPNO๊ฐ€ ๊ฐ™์œผ๋ฉด SAL ์นผ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

- ORDER BY ์ ˆ ์‚ฌ์šฉ์‹œ ์ฃผ์˜์‚ฌํ•ญ : ์ •๋ ฌํ•˜๋Š” ๋ฐ ๋งŽ์€ ๋น„์šฉ์ด ์†Œ๋ชจ๋˜๊ธฐ ๋•Œ๋ฌธ์— SQL๋ฌธ์˜ ํšจ์œจ์ด ๋‚ฎ์•„์ ธ ์„œ๋น„์Šค ์‘๋‹ต ์‹œ๊ฐ„์ด ๋Š๋ ค์ง„๋‹ค. ์ •๋ ฌ์ด ๊ผญ ํ•„์š”ํ•œ ๊ฒฝ์šฐ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ๊ฒƒ