๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

TIL, WIL/TIL๐Ÿ“˜

08. 14 TIL : mySQL ~ ORDER BY NULL

728x90

 

ORDER BY NULL์€ MySQL์—์„œ ์‚ฌ์šฉ๋˜๋Š” ํŠน์ˆ˜ํ•œ ๊ตฌ๋ฌธ์œผ๋กœ,

๊ฒฐ๊ณผ ์ง‘ํ•ฉ์˜ ์ •๋ ฌ์„ ๋ฌดํšจํ™”ํ•˜๊ฑฐ๋‚˜ ๋น„ํ™œ์„ฑํ™”ํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ฆ‰, ์ •๋ ฌ์„ ํ•˜์ง€ ์•Š๊ฒ ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค

 

๋ณดํ†ต MySQL ์ฟผ๋ฆฌ์—์„œ ORDER BY ์ ˆ์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒฐ๊ณผ๊ฐ€ ํŠน์ • ์—ด์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๋•Œ๋กœ๋Š” ์ •๋ ฌ์„ ์›ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ์ •๋ ฌ์ด ๋ถˆํ•„์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋•Œ ORDER BY NULL์„ ์‚ฌ์šฉํ•˜๋ฉด ์ฟผ๋ฆฌ๊ฐ€ ์ •๋ ฌ ์—†์ด ์ˆ˜ํ–‰๋ฉ๋‹ˆ๋‹ค.

์ด ๊ตฌ๋ฌธ์€ ์ฃผ๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ƒํ™ฉ์—์„œ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค:

  1. GROUP BY์™€ ํ•จ๊ป˜ ์‚ฌ์šฉ: GROUP BY ์ ˆ์„ ์‚ฌ์šฉํ•  ๋•Œ MySQL์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ๊ฒฐ๊ณผ๋ฅผ ๊ทธ๋ฃนํ•‘๋œ ์—ด์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ •๋ ฌ์ด ํ•„์š” ์—†๋Š” ๊ฒฝ์šฐ ORDER BY NULL์„ ์‚ฌ์šฉํ•ด ๋ถˆํ•„์š”ํ•œ ์ •๋ ฌ์„ ๋ฐฉ์ง€ํ•˜๊ณ  ์„ฑ๋Šฅ์„ ์ตœ์ ํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  2. SELECT column1, COUNT(*) FROM table GROUP BY column1 ORDER BY NULL;
  3. ORDER BY ์ƒ๋žต ํšจ๊ณผ: ๋ช…์‹œ์ ์œผ๋กœ ์ •๋ ฌ์„ ์›ํ•˜์ง€ ์•Š์Œ์„ ํ‘œํ˜„ํ•˜๊ณ ์ž ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” ORDER BY ์ ˆ์„ ์•„์˜ˆ ์ƒ๋žตํ•˜๋Š” ๊ฒƒ๊ณผ ๋™์ผํ•œ ํšจ๊ณผ๋ฅผ ์ค๋‹ˆ๋‹ค.
  4. ๋Œ€๋Ÿ‰ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ: ๋ฐ์ดํ„ฐ๊ฐ€ ๋งค์šฐ ๋งŽ๊ณ  ์ •๋ ฌ์ด ์„ฑ๋Šฅ์— ์˜ํ–ฅ์„ ์ค„ ์ˆ˜ ์žˆ๋Š” ์ƒํ™ฉ์—์„œ ORDER BY NULL์„ ์‚ฌ์šฉํ•ด ์ฟผ๋ฆฌ ์„ฑ๋Šฅ์„ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ์ œ

๋‹ค์Œ ์˜ˆ์ œ๋Š” ๊ธฐ๋ณธ์ ์ธ ์‚ฌ์šฉ๋ฒ•์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค:

SELECT * FROM employees ORDER BY NULL;

์ด ์ฟผ๋ฆฌ๋Š” employees ํ…Œ์ด๋ธ”์—์„œ ๋ชจ๋“  ํ–‰์„ ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ, ์–ด๋–ค ๊ธฐ์ค€์œผ๋กœ๋„ ์ •๋ ฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์š”์•ฝ

  • ORDER BY NULL์€ ์ •๋ ฌ์„ ๋น„ํ™œ์„ฑํ™”ํ•˜๋Š” ๊ตฌ๋ฌธ์ด๋‹ค.
  • ์ฃผ๋กœ GROUP BY์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜์—ฌ ๋ถˆํ•„์š”ํ•œ ์ •๋ ฌ์„ ๋ฐฉ์ง€ํ•˜๊ณ  ์ฟผ๋ฆฌ ์„ฑ๋Šฅ์„ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์ •๋ ฌ์ด ํ•„์š” ์—†๋Š” ์ƒํ™ฉ์—์„œ ์ฟผ๋ฆฌ ์„ฑ๋Šฅ ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
728x90