개키우는개발자 : )

PostgreSQL 필터링 조회 (IN 연산자) 본문

PostgreSQL/데이터 조회와 필터링

PostgreSQL 필터링 조회 (IN 연산자)

DOGvelopers 2019. 10. 28. 00:26
반응형

IN연산자 문법

특정 집합(컬럼 혹은 리스트)에서 특정 집합 혹은 리스트가 존재하는지 판단하는 연산자입니다.

 

기본 문법

 

column_name이 가지고 있는 집합에서 value1,2 등의 값이 존재하는지 확인합니다.

select * from table_name where column_name in(value1,value2,...)

 

column_name이 가지고 있는 집합에서 table_name2 테이블의 column_name2의 집합이 존재하는지 확인합니다.

select * from table_name where column_name in
(select column_name2 from table_name2);

 

실습

 

- IN연산자를 사용하여 rental 테이블의 customer_id 가 1 또는 2 인 값을 return_date 내림차순으로 정렬하여 조회합니다.

select
	customer_id,
	rental_id,
	return_date
from rental
where customer_id in(1,2)
order by return_date desc;

실습1

- OR연산자를 사용하여 rental 테이블의 customer_id 가 1 또는 2 인 값을 return_date 내림차순으로 정렬하여 조회합니다.

 

select
	customer_id,
	rental_id,
	return_date
from rental
where customer_id = 1 or customer_id = 2
order by return_date desc;

실습2

IN과 OR은 customer_id가 1 또는 2인 모든 값을 조회합니다.

 

- NOT IN연산자를 사용하여 rental 테이블의 customer_id 가 1과 2 가 아닌 값을 return_date 내림차순으로 정렬하여 조회합니다.

select
	customer_id,
	rental_id,
	return_date
from rental
where customer_id not in(1,2)
order by return_date desc;

실습3

- AND연산자를 사용하여 rental 테이블의 customer_id 가 1과 2 가 아닌 값을 return_date 내림차순으로 정렬하여 조회합니다.

select
	customer_id,
	rental_id,
	return_date
from rental
where customer_id <> 1 and customer_id <> 2
order by return_date desc;

실습4

<> ,!= 은 부정을 나타내며 해석을 하자면 customer_id 가 1이 아니고 customer_id 가 2도 아닌 나머지를 조회합니다.

- 서브 쿼리를 사용하여 rental 테이블의 return_date 가 2005-05-27 인 customer_id를 조회합니다.

 

cast는 return_date를 date type으로 변환시켜주는 함수입니다.

select customer_id
from rental
where cast (return_date as date) = '2005-05-27'

실습5

 

- IN 연산자에 서브 쿼리를 사용하여 rental 테이블 return_date 가 2005-05-27 인 customer_id 값으로

customer 테이블의 customer_id컬럼을 비교하여 first_name, last_name의 데이터를 조회합니다.

 

select first_name,last_name
from customer
where customer_id in(
	select customer_id
	from rental
	where cast (return_date as date ) = '2005-05-27'
);

조금 복잡할 수 있는 쿼리이며 IN의 인자 값에 서브 쿼리의 데이터 값을 넣을 수 있습니다.

실습6

 

꼭 실습해보시길 바랍니다 ^_^

반응형
Comments