ORDER BY (데이터를 정렬할 때 사용)
SELECT *
FROM 테이블명
WHERE 조건
ORDER BY 정렬 기준 ASC(DESC)
- ASC (오름차순, 기본값) / DESC (내림차순)
- ORDER BY절의 위치는 FROM 뒤, WHERE절이 있는 경우 WHERE절 뒤
- 다중 정렬 : ORDER BY 정렬 기준1 ASC(DESC), 정렬 기준2 ASC(DESC)
내림차순 / 오름차순 정렬하기
ex1) orderdetails 테이블에서 quantity가 80 초과인 행만 quantity를 기준으로 내림차순 정렬하여 출력해라
SELECT *
FROM orderdetails
WHERE quantity > 80
ORDER BY quantity DESC

ex2) orderdetails 테이블에서 quantity가 가장 큰 행을 출력해라
SELECT *
FROM orderdetails
ORDER BY quantity DESC
LIMIT 1

ex3) orderdetails 테이블에서 quantity가 가장 작은 행을 출력해라
SELECT *
FROM orderdetails
ORDER BY quantity
LIMIT 3

→ 위의 경우 quantity를 오름차순 정렬했을 때, 첫번째 행부터 세번째 행까지 quantity의 최솟값인 1로 같으므로 3개의 행을 모두 출력해야 한다.
<HackerRank 연습문제>
▶Query the Name of any student in STUDENTS who scored higher than 75 Marks. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID.
⇒ name 컬럼 출력, marks 75보다 커야함, 이름의 마지막 3글자를 기준으로 오름차순 정렬, 만약 3글자가 동일한 학생이 존재하는 경우엔 id를 기준으로 오름차순 정렬
column
|
type
|
ID
|
Integer
|
Name
|
String
|
Marks
|
Integer
|
SELECT name
FROM students
WHERE marks > 75
ORDER BY RIGHT(name, 3), id
+ RIGHT(name, 3)은 다음과 같이 작성해도 결과가 동일함
SUBSTR(name, -3, 3)
SUBSTR(name, -3)
↘↘↘
[백문이불여일타] 데이터 분석을 위한 기초 SQL
'📖 STUDY > SQL' 카테고리의 다른 글
[SQL] review_HackerRank (0) | 2022.03.04 |
---|---|
[SQL] CEIL, FLOOR, ROUND (0) | 2022.03.04 |
[SQL] LEFT, RIGHT, SUBSTRING (0) | 2022.03.04 |
[SQL] WHERE_(LIKE, IN, BETWEEN, IS NULL) (0) | 2022.03.04 |
[SQL] SELECT, FROM, LIMIT (0) | 2022.03.04 |