저장을 습관화

SQL - ORDER BY, IN, BETWEEN, Aliases 본문

공부/데이터베이스

SQL - ORDER BY, IN, BETWEEN, Aliases

ctrs 2023. 12. 3. 22:39

1. ORDER BY

출력 결과를 오름차순 또는 내림차순으로 정렬한다

오름차순으로 정렬할 때는 ASC(ascending)를 사용하고,

내림차순으로 정렬할 때는 DESC(descending)을 사용한다.

 

디폴트는 오름차순이기 때문에 지정을 하지 않았다면 오름차순으로 정렬된다.

 

예시 1) 가격을 기준으로 오름차순으로 정렬

select * from products
order by price

 

예시 2) 가격을 기준으로 내림차순으로 정렬

select * from products
order by price desc

 

예시 3) 숫자가 아닌 문자열인 경우에도 사용 가능하다. 영어와 한국어 모두 적용된다.

상품 이름을 기준으로 알파벳 오름차순으로 정렬

select * from products
order by productname

 

예시 4) 상품 이름을 기준으로 알파벳 내림차순으로 정렬

select * from products
order by productname desc

 

예시 5) 정렬 조건을 두 컬럼에 적용할 수 있다.

국가 이름을 기준으로 오름차순 정렬한 후, 국가 이름이 동일한 경우 고객 이름을 내림차순으로 정렬

select * from customers
order by country asc, customername desc

 

 

2. IN

WHERE 절에서 여러 조건을 적용할 때 사용한다.

OR 논리연산자를 여러번 사용한 것과 같은 결과이다.

 

예시 1) country가 'Germany', 'France', 'UK' 중 하나에 해당하는 데이터를 출력

select * from customers
where country in ('Germany', 'France', 'UK')

 

예시 2) NOT과 함께 사용하는 방법

country가 'Germany', 'France', 'UK' 중 어느 하나에도 해당하지 않는 데이터를 출력

select * from customers
where country not in ('Germany', 'France', 'UK')

 

예시 3) 하위 쿼리와 함께 사용하는 방법

orders 테이블에서 customerid를 검색한 결과가

customers 테이블의 customerid 컬럼에 해당하는 내용이 있다면 출력

즉, 주문을 넣은 고객을 조회

select * from customers
where customerid in (
	select customerid
	from orders
)

 

예시 4) NOT과 하위 쿼리를 함께 사용하는 방법

orders 테이블에서 customerid를 검색한 결과가

customers 테이블의 customerid 컬럼에 해당하는 내용이 없다면 출력

즉, 주문을 넣지 않은 고객을 조회

select * from customers
where customerid not in (
	select customerid
	from orders
)

 

 

3. BETWEEN

주어진 범위 내의 값을 조회한다.

값은 숫자, 문자열, 날짜일 수 있다.

between 연산자는 포괄적이며, 시작과 종료 값이 포함된다.

 

예시 1) 가격이 10에서 20 사이인 데이터를 조회

select * from products
where price between 10 and 20

 

예시 2) NOT BETWEEN

가격이 10에서 20 사이가 아닌 데이터를 조회

select * from products
where price not between 10 and 20

 

예시 3) IN과 함께 사용

가격이 10에서 20 사이이며, categoryid가 1, 2, 3 중 하나인 데이터를 조회

select * from products
where price between 10 and 20
and categoryid in (1, 2, 3)

 

예시 4) 범위 조건을 문자열로 지정

상품명이 알파벳 순으로 따졌을때 'Carnarvon Tigers'와 'Mozzarella di Giovanni' 사이인 데이터를 조회하고,

오름차순으로 정렬

select * from products
where productname between 'Carnarvon Tigers' and 'Mozzarella di Giovanni'
order by productname

 

예시 5) 범위 조건을 NOT과 문자열로 지정

상품명이 알파벳 순으로 따졌을때 'Carnarvon Tigers'와 'Mozzarella di Giovanni' 사이가 아닌 데이터를 조회하고,

오름차순으로 정렬

select * from products
where productname not between 'Carnarvon Tigers' and 'Mozzarella di Giovanni'
order by productname

 

예시 6) 범위 조건을 날짜로 지정

select * from orders
where orderdate between '1996-07-01' and '1996-07-31'

or

select * from orders
where orderdate between #07/01/1996# and #07/31/1996#

 

 

4. Aliases

alias는 별칭이다.

쿼리를 이용한 데이터 출력 결과의 컬럼명을 지정한다.

as 키워드를 사용하여 적용하며

해당 컬럼명은 쿼리 사용시에만 표시되는 것이지 실제 DB에 적용되는 것은 아니다.

 

예시 1)

select customerid as ID
from customers

 

 

예시 2) as 키워드는 생략이 가능하다.

select customerid ID
from customers

 

예시 3) 여러 열에 각각의 별칭을 적용할 수 있다.

select customerid as ID, customername as Customer
from customers

 

 

예시 4) 공백문자와 함께 사용할 경우 별칭을 [대괄호]나 "큰따옴표"로 묶는다.

select productname as [My Great Products]
from products

or

select productname as "My Great Products"
from products

 

예시 5) CONCAT, 여러 열을 하나의 열로 묶어서 사용할 때

select customername, concat(address, ', ', postalcode, ', ', city, ', ', country) as address
from customers

 

 

예시 6) 별칭은 테이블에도 지정 가능하다.

이 작업은 주로 둘 이상의 테이블을 한 번에 조회할 경우 사용한다.

- 테이블 별칭 사용 전

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;

 

- 테이블 별칭 사용 후

SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

 

'공부 > 데이터베이스' 카테고리의 다른 글

SQL - GROUP BY, HAVING, EXISTS  (0) 2023.12.04
SQL - UNION  (0) 2023.12.03
SQL - AND, OR, NOT  (0) 2023.12.03
SQL - SELECT, DISTINCT, WHERE  (0) 2023.12.03
SQL - 주석  (0) 2023.12.03