728x90
반응형
select * from course
select course_id, credits, credits+1 as increased_credits
from course
select dept_name, budget, budget-5000 as reduced_budget
from department
select instructor_id, name, salary, salary*1.05 as new_salary
from instructor
--comparison operators
select *
from student
where tot_cred >= 30
select *
from student
where tot_cred != 30
select *
from student
where tot_cred < 30
--logical operators
select *
from section
where semester = 'Fall' and year = 2012
select *
from section
where not semester = 'Fall'
--bitwise operators
select student_id, tot_cred, tot_cred ^ 1 as toggle_bit
from student
--string operators
select course_id, CONCAT(title, '-', dept_name) as course_inf
from course
select *
from instructor
where name not like 'B%'
--'B%' 는 문자열이 'B'로 시작하는 것을 의미하고, not like 는 이를 제외합니다.
select course_id, title
from course
where title like '_a%'
--'_' 은 임의의 한 글자,
--'a%' 는 a로 시작하는 나머지 문자열을 의미하므로
--예를 들어 'Math', 'Ballet', 'Dance' 등이 해당될 수 있습니다.
select dept_name
from department
where dept_name like '%\.%' escape '\'
--목적:
--department 테이블에서 dept_name(학과 이름) 중 "."(마침표) 가 포함된 값을 조회하려고 합니다.
--조건 설명:
--like '%\.%':
--%는 임의의 문자열, .는 마침표를 의미합니다.
--하지만 .는 **와일드카드(모든 문자)**로 인식되기 때문에, 그냥 쓰면 문자 . 자체를 찾지 못합니다.
--그래서 \. 처럼 이스케이프 문자(\)를 써서 "." 문자 자체를 찾도록 만듭니다.
--escape '\':
--\가 이스케이프 문자임을 명시합니다.
--set operators
select dept_name
from department
union
(select dept_name
from course)
--department와 course 테이블의 dept_name을 합칩니다.
--중복된 값은 제거됩니다.
--즉, 두 테이블의 dept_name 중복 없이 **모든 값의 집합(합집합)**을 보여줍니다.
select dept_name
from department
union all
(select dept_name
from course)
--UNION과 거의 같지만,
--중복을 제거하지 않음.
--즉, 두 테이블의 dept_name을 그대로 모두 합침 (중복 허용).
select dept_name
from department
intersect
(select dept_name
from course)
--두 테이블의 dept_name 중 공통으로 존재하는 값만 추출.
--즉, department에도 있고 course에도 있는 학과명만 결과로 나옴.
select dept_name
from department
except
(select dept_name
from course)
--department에만 있고 course에는 없는 dept_name만 추출.
--즉, department - course의 차집합.
select *
from takes
where grade in ('A', 'A-')
select *
from instructor
where salary between 60000 and 70000
select *
from course
where dept_name is not null
select *
from instructor i
where exists
(select 1
from teaches t
where t.instructor_id = i.instructor_id
)
--instructor 테이블의 모든 강사 i 중에서
--teaches 테이블에 해당 강사의 instructor_id가 존재하는 경우만 선택합니다.
--exists (select 1 ...) 의미:
--EXISTS는 서브쿼리 결과가 존재하는지만 판단합니다.
--select 1은 아무 숫자나 넣어도 상관없고, 존재 여부만 확인하기 위해 자주 쓰입니다.
반응형
'CS > database' 카테고리의 다른 글
[database] SQL index (1) | 2025.06.21 |
---|---|
[database] sql Date and Time (0) | 2025.06.21 |
[database] [COUNT, SUM, AVG, MIN, MAX, GROUP BY, HAVING] (0) | 2025.05.15 |
[database] select, where, order by & top (0) | 2025.05.13 |
[database] data insertion (3) | 2025.05.12 |