저장을 습관화
SQL - AND, OR, NOT 본문
1. AND
논리연산자 &&
where 절에서 여러 개의 조건을 설정할 때 사용하며
and 양 옆에 있는 조건이 모두 참인 데이터만 출력함
하나의 where 절에서 여러 and 연산자를 사용할 수 있음
단, 원하는 데이터가 제대로 출력되려면 모든 조건이 참이어야한다.
예시 1) customers 테이블에서 country가 'Spain'이고, customername이 G로 시작하는 데이터를 출력
select * from customers
where country = "Spain" and customername like 'G%'
예시 2) country가 "Germany"이며 city가 "Berlin"이고, postalcode가 12000보다 큰 데이터를 출력
select * from customers
where country = "Germany"
and city = "Berlin"
and postalcode > 12000
2. OR
논리연산자 ||
where 절에서 여러 개의 조건을 설정할 때 사용하며
or 양 옆에 있는 조건 중 하나라도 참인 데이터를 출력한다.
하나의 where 절에서 여러 or 연산자를 사용할 수 있음
단, 모든 조건 중 하나라도 참이라면 원하는 데이터를 포함하여 출력될 것이다.
예시 1) country가 "Germany"이거나 "Spain"인 데이터를 모두 출력
select * from customers
where country = "Germany" or country = "Spain"
예시 2) city가 "Berlin"이거나, customername이 G로 시작하거나, country가 "Norway"인 데이터는 모두 출력
select * from cutomers
where city = "Berlin" or customername like 'G%' or country = "Norway"
3. and와 or 결합
and와 or 논리연산자는 조건부를 (괄호)로 묶을 수 있으며 혼합해서 사용할 수도 있다.
예시) country가 "Spain"이면서, customername이 G로 시작하거나 R로 시작하는 데이터를 모두 출력
select * from customers
where country = "spain" and (customername like 'G%' or customername like "R%")
4. and와 or의 차이
and는 모든 조건이 참일 경우 사용하며
or는 조건 중 하나라도 참일 경우에 사용한다.
5. NOT
다른 연산자와 함꼐 사용하며 연산자 본래 역할의 반대 결과를 출력한다.
예시 1) not =, country가 "Spain"이 아닌 데이터를 출력한다.
select * from customers
where not country = "Spain"
예시 2) not like, customername이 A로 시작하지 않는 데이터를 출력
select * from customers
where customername not like "A%"
예시 3) not between, customerid가 10에서 60 사이가 아닌 데이터를 출력
select * from customers
where customerid not between 10 and 60
예시 4) not in, city가 'Paris'나 'London'이 아닌 데이터를 출력한다.
select * from customers
where city not in ('Paris', 'London')
예시 5) not >, customerid가 50보다 크지 않은 데이터를 출력한다.
select * from customers
where not customerid > 50
같은 기능을 하는 연산자로는 '!>'가 있다.
예시 6) not <, customerid가 50보다 작지 않은 데이터를 출력한다.
select * from customers
where not customerid < 50
같은 기능을 하는 연산자로는 '!<'가 있다.
'공부 > 데이터베이스' 카테고리의 다른 글
SQL - GROUP BY, HAVING, EXISTS (0) | 2023.12.04 |
---|---|
SQL - UNION (0) | 2023.12.03 |
SQL - ORDER BY, IN, BETWEEN, Aliases (0) | 2023.12.03 |
SQL - SELECT, DISTINCT, WHERE (0) | 2023.12.03 |
SQL - 주석 (0) | 2023.12.03 |