SQL과 데이터베이스 강의를 요약 · 정리한 글입니다.
테이블이란?
데이터가 지정되는 데이터베이스 내의 기본 단위로, 행과 열의 구조로 이루어져 있습니다. 사전에 형태가 정의되고 생성되어 있어야만 데이터가 입력 가능합니다.
테이블의 이해를 돕기 위해 엑셀 표와 테이블을 비교해보겠습니다.
엑셀 | 테이블 |
손 쉽게 컬럼 추가가 가능하다. | 구조가 정해져 있는 상태로, 해당 컬럼 이외의 컬럼은 손쉽게 추가가 불가능하다. |
데이터 수정 및 입력 시 데이터 타입에 제약을 받지 않는다. | 정해진 형태로만 데이터를 관리한다 |
문자, 숫자, 날짜 등 어떤 형식의 데이터도 입력 가능하다. | 물리적으로 생성된 테이블의 구조를 변경한다면 가능하지만 구조적 변경없이는 불가능하다. |
SAMPLE DATA 생성하기
create table 테이블명
(no numeric(4),
# 컬럼이름 데이터타입(데이터 사이즈)
# "no"는 숫자로 최대 4바이트까지 입력가능
name varchar(10),
# "name"은 문자로 최대 10바이트까지 입력가능
tel varchar(20),
point numeric(10));
# numeric -> 숫자형(정확한 숫자) / varchar -> 문자열
CREATE TABLE 테이블명
컬럼이름 데이터타입(데이터 사이즈);
SELECT문 기본 문법
-데이터 조회하기
select * from professor;
# select :저장된 데이터 조회하기
# select * :모든 컬럼, from professor :professor 테이블에서부터 생성된 모든 데이터 조회
SELECT -> 조회할 대상(컬럼 및 표현식) 나열
FROM -> 조회하고자 하는 데이터를 갖는 테이블명을 전달
- 원하는 컬럼만 선택하여 조회하기
select studno, name
from student;
SELECT 절 뒤에 컬럼명을 나열하여 조회하면 된다.
SELECT 절에 나열된 순서에 맞게 데이터가 출력된다.
- 표현식을 사용한 출력
select studno, name, '학생입니다'
from student;
컬럼명 이외의 문자열을 출력하는 경우를 표현식이라 한다.
select, from처럼 정의된 문법이 아닌 대상은 문자열이라는 구분자로 홑따옴표로 묶어서 사용한다.
- 컬럼 별칭(alias) 사용하여 출력하기
컬럼명 대신 다른 이름으로 출력하고 싶을 경우 출력되는 컬럼명을 임시 변경할 수 있다.
(테이블 레이아웃은 한번 저장되면 구조 변경을 하지 않는 한 변경되지 않는다)
컬럼 뒤에 "AS 별칭"으로 표현한다 (AS는 생략 가능)
select studno AS 학번, name 학생이름
from student;
컬럼 별칭 전달 시 주의사항으로 컬럼 별칭에 쌍따옴표가 필요한 경우
- 별칭에 띄어쓰기를 사용할 경우
- 특수 기호를 사용할 경우
- 대소 구분이 필요할 경우
별칭을 사용해쓸 경우 원본 컬럼이 수정되는 것이 아니라는 점을 다시 한 번 유의해야한다.
# 대소문자 구분이 필요할 경우, 특수기호 사용할 경우
select name as "NAME", studno as "학생#"
from student;
SELECT DISTINCT문
중복된 행의 UNUQUE한 값을 출력하려 할 때 사용한다. (UNIQUE 값은 동일한 값이 아닌 유일한 값)
SELECT 바로 뒤에 명시해야 한다.
DISTINCT 뒤에 나열된 컬럼의 조합이 중복일 때 생략한다.
select [distinct] {*| 컬럼명 | 표현식}
from 테이블명
- DISTINCT 뒤 컬럼이 하나인 경우 DISTINCT를 사용하여 출력하면
select grade from student;
select distinct grade from student;
- DINSTINCT 뒤 컬럼이 두개 이상인 경우
grade, name 컬럼의 모든 값이 중복될 경우에만 생략한다.
select grade, name from student;
select distinct grade, name from student;
연결연산자(||)
데이터의 결합 시 사용하며, 결합할 대상 사이에 || 를 명시하여 사용한다. 컬럼과 컬럼, 컬럼과 표현식의 결합 시 주로 사용한다. 연결연산자는 각각 다른 컬럼으로 표현되는 대상을 하나로 합쳐서 출력하기 위해 연결 연산자를 사용한다.
select name, studno from student;
select name || '-' || studno from student;
# 연결 연산자 뒤에 띄어쓰기를 하고싶을 경우
# 아래와 같이 띄어쓸 경우 문법적 띄어쓰기이므로 출력결과는 같다
select name, '학생은', grade, '입니다' from student;
# 아래와 같이
select name ||' 학생은 '||grade||'학년입니다' from student;
▶ 중간요약
DISTINCT : 행제거 (중복된 행 제거)
연결연산자(||) : 컬럼연합 (분리되어진 컬럼의 값들을 하나로 연결)
WHERE 절
조건에 맞는 데이터만 선택하여 출력할 경우에 사용한다.
where name = '홍길동' 과 같이 문자열과 날짜 상수의 전달은 항상 홑따옴표와 함께 사용한다.
(숫자 상수의 경우에는 홑따옴표 없이 사용할 수 있다. 또한 컬럼명 테이블명, select, from, where 같은 문법에는 따옴표가 붙지 않는다.) 객체 이름이나 문법은 대소문자를 구분하지 않는다. 그러나 조건절의 문자 상수는 대소를 구분한다.
where 절에서의 연산자는 아래와 같이 다양하다.
연산자 종류 | 설명 |
= | 같은 조건을 검색 |
!= , <> | 같지 않은 조건을 검색 |
> | 큰 조건을 검색 |
>= | 크거나 같은 조건을 검색 |
< | 작은 조건을 검색 |
<= | 작거나 같은 조건을 검색 |
-- where문
-- where 엑셀의 필터기능 담당(원하는 기능 선택) 반드시 선택을 원하는 조건을 전달해야함.
-- 조건을 원하는 대상 deptno1 = 제1 전공
select name, grade, deptno1 from student where grade = 4;
select name, height, weight from student
where height >= 170 and weight >= 80;
논리 연산자
여러 조건의 결합 및 부정에 사용하는 연산자이다
AND : 나열된 조건을 모두 만족해야할 때 사용 ex) 학년이 4학년이고, 성적이 80 이상인 |
OR : 나열된 조건 중 하나만 만족 ex) 4학년이거나, 성적이 80 이상인 |
NOT : 단일 조건의 결과 부정 ex) 성적이 80과 90사이가 아닌 |
-- and로 나열된 조건 만족시키기
select profno, name, position, pay from professor
where position = '정교수' or pay >= 500;
-- 나열된 조건 중 하나만 만족하면 출력 or=
select name, grade, height, weight, (height-100) * 0.9 as "표준몸무게"
from student
where grade in(1,2)
and height between 160 and 170;
▶ 중간요약
1. WHERE 절을 통한 필터링이 가능
2. 문자 상수와 날짜 상수 전달은 홑따옴표
3. 문자 상수는 대소문자 구분
산술 연산자
+, -, *, / 등의 산술연산자 표현 가능하다.
산술 연산자는(+, -, *, / )는 'select' ,'where' 절 외에 다른 구문에서도 사용가능하다.
BETWEEN 연산자
'where'절에서만 사용 가능한 연산자로, 'between a and b'는 a 이상, b 이하 사잇값을 반환한다.
select name, pay from professor
where pay between 500 and 600;
IN 연산자
between과 마찬가지로 'where절'에서만 사용가능한 연산자이다. IN('a','b','c') 는 a 또는 b 또는 c 여러 개 동시 출력한다는 뜻을 지닌 포함 연산자이다.
select name, grade, sid from student
where grade in (1, 2);
# 'in 연산자'는 or의 축약형 연산자
# 숫자는 홑따옴표를 사용하지 않는다
select name, position, pay from professor
where position in ('정교수', '전임강사');
# 문자 상수에는 반드시 '' 홑따옴표를 사용한다 !
응용 문제를 풀어보겠습니다. "키가 160 이상 170 이하인 학생들의 이름, 학년, 키, 몸무게, 표준몸무게를 출력하시오."
표준 몸무게를 구하기 위해서는 표준몸무게를 가공해서 출력해야 합니다.
이때 가공되는 표현식은 별칭을 생성한 뒤 출력해주는 것이 좋습니다.
# select 응용문제
## 표준몸무게 = (키-100)*0.9
select name, grade, height, weight, (height-100)*0.9 as "표준 몸무게"
from student
where grade in (1,2) and
height between 160 and 170;
▶ 중간요약
연산자의 종류에는 산술 연산자, between 연산자, in 연산자 등이 있다,
select, where 절에서의 연산자 사용방법은
산술연산자 | select, where 절 모두 사용 가능 |
BETWEEN 연산자 | where 절에서만 사용 가능 |
IN 연산자 | where 절에서만 사용 가능 |
'Language > SQL' 카테고리의 다른 글
[postgresql] SELECT의 기본 문법(2) (0) | 2023.04.28 |
---|---|
[BigQuery] 데이터 마이닝 (0) | 2022.07.04 |
[BigQuery] 입력 양식 최적화하기 (0) | 2022.07.01 |