๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ŒCS/DB

[SQL] ๋‹ค์ค‘์ •๋ ฌ ORDER BY

by dar0m! 2020. 1. 9.

๊ฒฐ๊ณผ ์ง‘ํ•ฉ์„ ์—ฌ๋Ÿฌ ์—ด๋กœ ์ •๋ ฌํ•˜๋ ค๋ฉด ORDER BY ์ ˆ์— ,(์‰ผํ‘œ) ๋กœ ๊ตฌ๋ถ„๋œ ์—ด ๋ชฉ๋ก์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ์•„๋ž˜๋Š” ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.

ํ…Œ์ด๋ธ”

id user_id title status created_at
1 123456789 ๊ฐ์žํƒ• OK 2020-01-08
2 456789 ๋ƒ‰๋ฉด OK 2020-01-09
3 123789 ์‚ผ๊ณ„ํƒ• COMPLETE 2020-01-10
4 12312 ์ผ€์ต OK 2020-01-09
5 45678943 ์กฑ๋ฐœ COMPLETE 2020-01-13

 

์กฐ๊ฑด

  1. ์ตœ์‹ ์ˆœ์œผ๋กœ ๋‚˜ํƒ€๋‚˜๊ฒŒ ํ•œ๋‹ค.
  2. status ๊ฐ’์ด COMPLETE ์ธ row๋Š” ๋งจ ์•„๋ž˜์— ๋ฐฐ์น˜๋˜์–ด์•ผ ํ•œ๋‹ค.

 

SQL

ORDER BY ๋‹ค์ค‘์ •๋ ฌ์„ ํ•  ๋•Œ, ์™ผ์ชฝ๋ถ€ํ„ฐ ์ˆœ์ฐจ์ ์œผ๋กœ ์ •๋ ฌ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
(=์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์—ดํ•˜์ž.)

์ฆ‰, ORDER BY column1 desc, column2 desc; ๋ผ๋ฉด
column1 ์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ ํ›„, column1์ด ๊ฐ™์€ ๊ฐ’์— ํ•œํ•ด์„œ column2๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ฒ ๋‹ค๋Š” ๋œป์ด๋‹ค.

๋”ฐ๋ผ์„œ ์˜ˆ์ œ์˜ ๊ฒฝ์šฐ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ ค๋ฉด ์•„๋ž˜ ์ˆœ์„œ๋กœ ์ •๋ ฌ์„ ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. 

  1. status
  2. createdAt
select * from ํ…Œ์ด๋ธ” order by status desc, created_at desc;

ASC - ์˜ค๋ฆ„์ฐจ์ˆœ(default), DESC - ๋‚ด๋ฆผ์ฐจ์ˆœ

์ด ๊ฒฝ์šฐ ORDER BY์ ˆ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

  • ๋จผ์ € ๊ฒฐ๊ณผ ์ง‘ํ•ฉ์„ 'status' ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.
  • ๊ทธ๋Ÿฐ ๋‹ค์Œ ์ •๋ ฌ ๋œ ๊ฒฐ๊ณผ ์ง‘ํ•ฉ์„ 'createdAt' ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.
    • ์ด ๋‹จ๊ณ„์—์„œ 'status' ๊ฐ’์˜ ์ˆœ์„œ๋Š” ๋ณ€๊ฒฝ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜ค์ง 'createdAt' ๊ฐ’์˜ ์ˆœ์„œ๋งŒ ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.

 

๊ฒฐ๊ณผ

id user_id title status created_at
2 456789 ๋ƒ‰๋ฉด OK 2020-01-09
4 12312 ์ผ€์ต OK 2020-01-09
1 123456789 ๊ฐ์žํƒ• OK 2020-01-08
5 45678943 ์กฑ๋ฐœ COMPLETE 2020-01-13
3 123789 ์‚ผ๊ณ„ํƒ• COMPLETE 2020-01-10

 

์ฐธ๊ณ 

๋Œ“๊ธ€