정리 노트

ORDER BY 절 본문

개념 정리/데이터베이스

ORDER BY 절

꿈만 꾸는 학부생 2024. 7. 2. 16:12
728x90

DML 문을 연습할 데이터 베이스는 아래의 사이트에서 스크립트를 다운로드하여 실행해 생성했습니다.

 

MySQL Sample Database

This page provides you with a MySQL sample database that helps you to practice with MySQL effectively and quickly.

www.mysqltutorial.org


ORDER BY 절은 SELECT 결과를 특정 열을 기준으로 정렬해 출력해 주는 역할을 합니다. ORDER BY 절에서는 기본적으로 오름차순으로 정렬하고, 내림차순으로 정렬하도록 지정할 수 있습니다.

ORDER BY 절 연습을 위해 아래의 테이블을 사용하겠습니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers;

기존 테이블

이 테이블에서 creditLimit 열을 기준으로 정렬한 결과를 보고 싶다면 아래와 같이 작성하면 볼 수 있습니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers
ORDER BY creditLimit;

creditLimit 열을 기준으로 정렬한 결과

따로 명시하지 않으면 오름차순이 기본이기 때문에 creditLimit 값이 0.0인 열부터 출력합니다. 내림차순으로 정렬하고 싶다면 열 이름 옆에 DESC를 작성하면 됩니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers
ORDER BY creditLimit DESC;

 

ORDER BY 절에서는 SELECT에서 사용했던 ALIAS를 사용할 수 있습니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit AS limits
FROM customers ORDER BY limits;

이 SQL문을 실행하면 위 사진과 동일한 결과를 얻을 수 있습니다.

 

또한 ALIAS 외에도 열에 번호를 붙여 정렬할 열을 지정할 수 있습니다. SELECT에서 지정한 열들을 1부터 순서대로 지정했을 때, 정렬 기준이 되는 열의 번호를 ORDER BY 옆에 작성하면 열의 이름을 썼을 때와 동일한 결과를 얻을 수 있습니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers
ORDER BY 7;

7번 열(country)를 기준으로 정렬한 결과

7번째에 있는 country 열을 기준으로 정렬하고 싶을 때 country 열 이름을 써도 되지만, 위와 같이 7이라 작성해도 정렬 결과를 얻을 수 있습니다.

 

ORDER BY 절에서 여러 열을 지정해 각 열마다 정렬 기준을 다르게 적용하여 테이블 내 데이터를 정렬할 수 있습니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers
ORDER BY country, state, city;

여러 열을 선정해 정렬한 결과

위와 같이 SQL을 작성하면 먼저 country 열을 기준으로 오름차순 정렬하고 state, city 순서대로 오름차순 정렬을 적용합니다. 위의 사진을 보면 같은 Australia를 가진 데이터들이 NSW, Queensland, Victoria 순의 state로 오름차순 정렬됐음을 볼 수 있습니다. 또한 같은 NSW를 가진 데이터들도 Chatswood, North Sydney 순의 city로 오름차순 정렬됐습니다.

 

여기서 city는 내림차순으로 정렬하려면 city 옆에 DESC를 작성하면 됩니다.

SELECT customerNumber, customerName, phone, city, state, postalCode, country, creditLimit FROM customers
ORDER BY country, state, city DESC;

city 열에 DESC 정렬 조건 추가 결과

결과를 보면 North Sydney, Chatswood 순으로 출력됐음을 확인할 수 있습니다.

728x90

'개념 정리 > 데이터베이스' 카테고리의 다른 글

GROUP BY, HAVING 절  (0) 2024.07.01
집계 함수  (0) 2024.06.25
SQL 단일 행 내장 함수들  (0) 2024.04.18
SELECT문 WHERE절  (4) 2024.02.28
SELECT문  (2) 2024.02.08