SQL과 데이터베이스 강의를 요약 · 정리한 글입니다.
LIKE 연산자
LIKE는 패턴 비교 연산자이다.
조건을 'where절'에 전달하여 해당 조건에 맞는 행을 선택하는 용도로 사용된다.
정확한 일치가 아닌 패턴에 만족하는 행을 착기 위해서 사용되는 연산자이다.
like와 함께 패턴을 완성하는 두 기호로 %와 _(underscore) 등이 있다.
1) 이름이 A로 시작하는 직원 모두 출력 : name LIKE 'A%' (%: '모든'이라는 의미로, 글자수 제한없이 [AA] [ABCD]와 같이 A로 시작하는 직원을 모두출력한다) |
2) 이름이 A로 시작하는 4자리인 직원 모두 출력 :name LIKE 'A___' (under바 3자리를 뒤에 입력해줌으로써 4자리 수 조건을 준다) |
3) 중간에 이름이 E가 포함된 직원 모두 출력 :name LIKE '%E% (중간에 E가 있으면 앞뒤에는 어떤 문자가 와도 괜찮다는 의미) |
4) 이름이 E로 끝나는 직원 모두 출력 :name LIKE '%E' |
5) 두번째 이름이 E인 직원 모두 출력 :name LIKE '_E%' |
-- 주민번호 끝자리가 2인 사람을 출력하시오.
-- 주민번호 앞 6자리는 고정이기에 '_' 여섯번 나열
-- 나머지 자리는 제한 없으니 %기호를 사용하고 7번쩨 자리에 2를 고정한다.
select name, jumin, grade from student
where jumin like '______2%';
IS NULL / IS NOT NULL 연산자
NULL 은 0 또는 space 값과는 다른, 아직 지정되지 않은 상태의 데이터를 의미한다.
NULL을 포함한 산술 연산의 결과는 NULL을 리턴한다.
NULL을 포함한 데이터의 조건은 IS NULL / IS NOT NULL로 전달한다. (NULL을 포함한 연산의 경우 이 점을 유의)
즉 bonas = null은 '보너스가 없다.', '0이다.'라고 해석하는 것이 아닌 아직 보너스가 정의되지 않았다라고 해석하는 것이 옳다.
-- '=' 기호를 대신해서 is null is not null 사용
-- null의 검색조건 is null, is not null
select name, grade, deptno1, deptno2 from student
where deptno2 is null;
select name, grade, deptno1, deptno2 from student
where deptno2 is not null; # null이 아닌 조건
▶ 중간요약
1. LIKE 연산자를 사용한 패턴 추출법
(%: 모든이라는 의미로 제한 없이 출력, _: 자리수 제한하여 원하는 패턴을 포함하여 출력)
2. NULL이란 정의되지 않은 값을 의미한다.
3. IS NULL / IS NOT NULL을 사용한 NULL의 선택에 대해 학습했습니다.
ORDER BY 절
order by 절은 데이터의 정렬을 수행하는 구문이다.
정렬 순서의 경우 생략이 가능하며 생략 시 기본 정렬순서는 오름차순(ASC)로 설정되어 있다. 내림차순으로 정의하고 싶을 경우 DESC를 추가하면 된다.
ORDER BY 컬럼1 [ ASC | DESC] , 컬럼2 [ ASC | DESC] ··· |
select name, position, pay from professor
where position = '정교수'
order by pay;
select name, position, pay from professor
where position = '정교수'
order by pay desc;
여러개의 컬럼에 각각 서로 다른 정렬 순서를 전달하려고 할 경우
1차 결과에서 값이 같을 경우 2차 정렬 기준으로 추가 정렬을 한 뒤 출력한다.
select name, deptno1, grade, height from student
where deptno1 = 201
order by grade, height desc;
ORDER BY 절에 컬럼 별칭 전달하기
order by 절은 select 절을 제외하고 컬럼 별칭을 유일하게 전달할 수 있다.
# select order by 절을 제외한 절에서 별칭을 사용할 경우 에러
select name, deptno1 as 학번, grade as 학년, height as 키
from student
where 학번 = 201
order by grade, height desc;
# order by 절에서만 컬럼 별칭을 사용할 수 있다
select name, deptno1 as 학번, grade as 학년, height as 키
from student
where deptno1 = 201
order by 학년, height desc;
▶ 중간요약
1. order by 절을 통한 데이터 정렬
행 순서 변경할 수 있으며 ,(콤마)로 구분 하여 나열하면 됩니다.
2. 각 컬럼 별 정렬 순서 전달
asc(오름차순) desc(내림차순)
3. 컬럼 별칭을 사용한 간단한 컬럼의 정렬 수행
LIMIT 절
SQL의 표준 문법인 DBMS 표준문법이 아닌 문법으로 행의 수를 제한할 때 사용합니다.
ORDER BY 절 뒤에 나열하여 사용하고, 정렬 후 상위 n개의 행 추출 용도로 사용 가능합니다.
offset을 사용하여 행 생략이 가능합니다.
ORDER BY을 이용해 성적이 높은 상위 5명의 학생정보를 출력할 경우
성적 순위를 계산 -> '순위가 5 이하' 라는 조건을 전달한다.
ORDER BY + LIMIT을 이용해 성적이 높은 상위 5명의 학생정보를 출력하는 경우
높은 성적순으로 정렬 -> 상위 5개 행을 선택한다
offset
limit절에서 offset을 이용해 상위 n개의 행을 생략할 수 있다.
-- limit절 몇개 행만 선택, 행의 수 제한해서
-- order by 절과 함께 사용시 상위 몇개, 하위 몇개만 출력할 경우 사용
select studno, name, height from student
order by height desc
limit 3;
-- offset을 통해 일부 행을 건너뛰는 방법
-- offset 사용하는 경우. limit 절로 행의 수를 제한할 때 일부행은 건너뛸 수 있었다
select studno, name, height from student
order by height desc
limit 3 offset 2;
▶ 중간요약
1. LIMIT n
: n개의 행 일부를 출력 (출력 행의 수 제한)
2. ORDER BY column + LIMIT n
: column 순서대로 상위 n개 추출
3. LIMIT n OFFSET m
: 상위 m개 제외 후, n개 행 추출
FETCH
OFFSET start { ROW | ROWS } FETCH { FIRST | NEXT } [ row_count ] { ROW | ROWS } ONLY |
start ~ offset으로 건너뛸 행의 수
row_count ~ limit n에서 n처럼 최종 출력 행의 수
- first? 앞에서부터 n개의 행을 출력하겠다
- next? offset에서 제외한 뒤의 n개의 행을 출력
-- 키가 작은 5명만
select name, grade, height from student
order by height
fetch next 5 row only;
-- fetch: 행의 수 제한
-- first: 'next'로 대체 가능
-- rows는 'row'로 대체 가능하다
▶ 중간요약
1. FETCH FIRST n ROWS ONLY
: 상위 n개 행 출력
2. ORDER BY column + FETCH
: column 순서대로 상위 n개 추출
3. OFFSET m FETCH n
: 상위 m개 제외 후, n개 행 추출
'Language > SQL' 카테고리의 다른 글
[postgresql] SELECT의 기본 문법 (0) | 2023.04.20 |
---|---|
[BigQuery] 데이터 마이닝 (0) | 2022.07.04 |
[BigQuery] 입력 양식 최적화하기 (0) | 2022.07.01 |