슴슴한 IT

[SQLD,SQLP]SQL기본 - WHERE 비교연산자 본문

SQL

[SQLD,SQLP]SQL기본 - WHERE 비교연산자

요한바울 2023. 8. 4. 22:14
728x90

비교연산자

데이터 조회 시 두 값 또는 표현식을 비교하여 조건을 만족하는 데이터를 필터링하는 데 사용

연산자 설명
=(같음) 두 값이 서로 같은지 비교
<> 또는 !=  (같지않음) 두 값이 서로 다른 지 비교
< (작음) 첫 번째 값이 두 번째 값 보다 작은 지 비교
> (큼) 첫 번째 값이 두 번째 값보다 큰지 비교
<= (작거나 같음) 첫 번째 값이 두 번째 작거나 같은 비교
>= (크거나 같음) 첫 번째 값이 두 번째 값보다 크거나 같은지 비교

 


비교연산자 사용 예시

- 학생테이블에서 math_score가 85 인 경우

math_score가 85인 학생은 John, math_score = 100 으로 조건을 줄 경우 공집합으로 표현

SELECT student_id, student_name, math_score
FROM students
WHERE math_score = 85;
--결과
student_id | student_name | math_score 
------------ --------------------------
101        | John         | 85   
102        | Alice        | 90   
103        | Michael      | 78   
104        | Emily        | 70   
105        | Sophia       | 95

- math_score가 70 이 아닌 경우,

math_score가 70인 Emily를 제외하고 나머지 4명의 학생들이 조회

SELECT student_id, student_name, math_score
FROM students
WHERE math_score <> 70;
--결과
student_id | student_name | math_score 
------------ --------------------------
101        | John         | 85   
102        | Alice        | 90   
103        | Michael      | 78   
105        | Sophia       | 95

- math_score가 90점 이상인 경우,

math_score가 90 보다 크거나 같은 경우이므로 Alice 90, Sophia 95 2명이 조회 

SELECT student_id, student_name, math_score
FROM students
WHERE math_score >= 90;
--결과
student_id | student_name | math_score 
------------ -------------------------- 
102        | Alice        | 90   
105        | Sophia       | 95

- math_score가 85점 이하인 경우,

math_score가 85보다 크거나 작은 경우이므로 John 85, Michael 78, Emily 70 3명이 조회

SELECT student_id, student_name, math_score
FROM students
WHERE math_score <= 85;
--결과
student_id | student_name | math_score 
------------ --------------------------
101        | John         | 85   
103        | Michael      | 78   
104        | Emily        | 70

- math_score가 78미만 인 경우,

math_score가 78 보다 작은 경우이므로, Emily 70 이 조회 

SELECT student_id, student_name, math_score
FROM students
WHERE math_score < 78;
--결과
student_id | student_name | math_score 
------------ --------------------------
104        | Emily        | 70

비교연산자 주의사항

  • CHAR변수나 VARCHAR2와 같은 문자형 타입 비교시 비교 대상 값을 작은 따옴표(') 묶어서 비교
  • NUMERIC과 같은 숫자 데이터 타입은 인용부호 사용 안함
  • 숫자 유형의 컬럼의 경우 숫자로 변환 가능한 문자열과 비교되면 상대 타입을 숫자 타입으로 변경

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

728x90