본문 바로가기

🌄SQL

[Tutorial] SQL BETWEEN 용법

BETWEEN


expr [NOT] 
BETWEEN begin_expr AND end_expr;

 

The BETWEEN operator is a logical operator that allows you to specify whether a value in a range or not. The BETWEEN operator is often used in the WHERE clause of the SELECT, UPDATE, and DELETE statements

1. 논리 연산자로 범위의 값을 지정해줄 때 사용한다. SELECT, UPDATE, DELETE 구문의 WHERE 절에서 주로 사용된다. 

The BETWEEN operator returns true if the value of the  expr is greater than or equal to (>=) the value of  begin_expr and less than or equal to (<= ) the value of the  end_expr, otherwise, it returns zero.

2. expr이 begin_expr 보다 크거나 같을 때, end_expr보다 작거나 같을때 true를 반환하고, 아니면 0을 반환한다. 

The NOT BETWEEN returns true if the value of  expr is less than (<) the value of the  begin_expr or greater than (>)the value of the value of  end_expr, otherwise, it returns 0.

3. NOT BETWEEN은 expr이 begin_expr보다 작거나, end_expr 보다 클 때 true를 반환하고, 아니면 0을 반환한다. 
4.
expr, begin_expr, end_expr은 모두 같은 데이터 타입이어야 하며, 식이 NULL이면 NULL 값을 반환한다. 

 

 

예시

SELECT 
    productCode, 
    productName, 
    buyPrice
FROM
    products
WHERE
    buyPrice BETWEEN 90 AND 100;

-- 
WHERE
    buyPrice >= 90 AND buyPrice <= 100;

buyprice가 90이상, 100이하인 값만 조건절에 걸려 값이 출력된다.
BETWEEN을 쓰지 않고 AND와 >= 기호를 써서 표현해도 값은 같다. 

SELECT 
    productCode, 
    productName, 
    buyPrice
FROM
    products
WHERE
    buyPrice NOT BETWEEN 20 AND 100;
    
--
WHERE
    buyPrice < 20 OR buyPrice > 100;

NOT BETWEEN을 사용하면 buyprice가 20미만, 100초과인 값을 출력한다.
마찬가지로 OR로 묶어 표현해도 값은 같다. AND나 OR로 연결하려면 expr(buyprice)을 반복해서 써줘야 한다.

SELECT 
   orderNumber,
   requiredDate,
   status
FROM 
   orders
WHERE 
   requireddate BETWEEN 
     CAST('2003-01-01' AS DATE) AND 
     CAST('2003-01-31' AS DATE);

Because the data type of the required date column is DATE so we used the CAST operator to convert the literal strings '2003-01-01' and '2003-12-31' to the DATE values.

데이터 타입을 변환시켜주는 CAST를 사용해서 문자열의 값을 숫자로 변환 후 BETWEEN 용법을 사용할 수 있다. 
예시에선 날짜 타입으로 바꿨는데, AS DATE를 써주지 않으면 작동하지 않는다. 

 

 

활용

해커랭크 The Report 문제 풀이

WHERE 절에서만 사용하는 줄 알았던 BETWEEN은 INNER JOIN에서도 사용된다. 범위 '조건'이기 때문이다. 

두 테이블을 조인할 때 공통 칼럼이 없다. 대신 첫번째 테이블의 marks의 범위를 지정하면 두 테이블을 조인할 수 있다. 

SELECT CASE WHEN grade < 8 THEN NULL ELSE s.name END AS name
     , g.grade
     , s.marks
FROM students s
    INNER JOIN grades g ON s.marks BETWEEN g.min_mark AND g.max_mark
ORDER BY g.grade DESC, name ASC, s.marks ASC

풀이해보면 s.marks 는 g.min_mark와 g.max_mark 사이의 값이라는 것.
조인을 엮을 때 쓰는 ON에는 항상 부등호(=)가 있어서 ON s.marks = BETWEEN g.min_mark AND g.max_mark로 쿼리를 작성했는데 s.marks가 저 범위 안에 있는 것이니 원래 BETWEEN 용법처럼 사용하면 된다. 

 


출처 : www.mysqltutorial.org/mysql-between