[MySQL] 4.1 데이터 정렬 - ORDER BY


http://www.mysqltutorial.org 내용을 따라 익히며 정리한 글입니다. 예시에 나오는 데이터셋은 MySQL 샘플 데이터셋인 classicmodels DB입니다.


1. ORDER BY 소개

SELECT 문을 사용할 때 결과셋은 따로 정렬되지 않는데, ORDER BY 절을 사용해 정렬할 수 있다.

2. ORDER BY 예시

다음 쿼리는 customers 테이블에서 성과 이름을 가져온 뒤 성을 기준으로 정렬해 보여준다.

SELECT
contactLastname,
contactFirstname
FROM
customers
ORDER BY
contactLastname
LIMIT 5;
+-----------------+------------------+
| contactLastname | contactFirstname |
+-----------------+------------------+
| Accorti | Paolo |
| Altagar,G M | Raanan |
| Andersen | Mel |
| Anton | Carmen |
| Ashworth | Rachel |
+-----------------+------------------+
5 rows in set (0.00 sec)

내림차순으로 정렬하려면 DESC 를 추가해준다.
따로 표시하지 않거나 ASC 을 써주면 오름차순 정렬이 실행된다.

SELECT
contactLastname,
contactFirstname
FROM
customers
ORDER BY
contactLastname DESC
LIMIT 5;
+-----------------+------------------+
| contactLastname | contactFirstname |
+-----------------+------------------+
| Young | Julie |
| Young | Jeff |
| Young | Mary |
| Young | Dorothy |
| Yoshido | Juri |
+-----------------+------------------+
5 rows in set (0.00 sec)

성은 내림차순으로, 이름은 오름차순으로 정렬하고 싶다면 각각의 컬럼에 DESCASC 를 명시해주면 된다.

SELECT
contactLastname,
contactFirstname
FROM
customers
ORDER BY
contactLastname DESC,
contactFirstname ASC
LIMIT 5;
+-----------------+------------------+
| contactLastname | contactFirstname |
+-----------------+------------------+
| Young | Dorothy |
| Young | Jeff |
| Young | Julie |
| Young | Mary |
| Yoshido | Juri |
+-----------------+------------------+
5 rows in set (0.00 sec)

3. 표현식에 기반한 ORDER BY 정렬

다음 쿼리는 orderdetails 테이블에서 주문번호와 주문라인번호, 주문수량과 단가의 곱을 불러온다.

SELECT
ordernumber,
orderlinenumber,
quantityOrdered * priceEach AS subtotal
FROM
orderdetails
ORDER BY
ordernumber,
orderLineNumber,
subtotal
LIMIT 5;
+-------------+-----------------+----------+
| ordernumber | orderlinenumber | subtotal |
+-------------+-----------------+----------+
| 10100 | 1 | 1729.21 |
| 10100 | 2 | 2754.50 |
| 10100 | 3 | 4080.00 |
| 10100 | 4 | 1660.12 |
| 10101 | 1 | 4343.56 |
+-------------+-----------------+----------+
5 rows in set (0.00 sec)

4. ORDER BY 와 커스텀 정렬

ORDER BY 를 이용하면 FIELD() 함수를 이용해 커스텀 정렬을 정의할 수 있다. 다음 순서대로 정렬을 해야한다고 가정하자.

  • In Process
  • On Hold
  • Cancelled
  • Resolved
  • Disputed
  • Shipped

이 경우 쿼리문은 다음과 같이 작성한다.

SELECT
orderNumber, status
FROM
orders
ORDER BY FIELD(status,
'In Process',
'On Hold',
'Cancelled',
'Resolved',
'Disputed',
'Shipped')
LIMIT 10;
+-------------+------------+
| orderNumber | status |
+-------------+------------+
| 10425 | In Process |
| 10421 | In Process |
| 10422 | In Process |
| 10420 | In Process |
| 10424 | In Process |
| 10423 | In Process |
| 10414 | On Hold |
| 10401 | On Hold |
| 10334 | On Hold |
| 10407 | On Hold |
+-------------+------------+
10 rows in set (0.00 sec)
© 2019 THE DATASCIENTIST All Rights Reserved.
Theme by hiero