[Database] (쉬운 코드) 관계형 데이터베이스
쉬운 코드 강의 「데이터베이스」 내용을 바탕으로, relational data model의 기본 개념과 relational database의 의미에 대한 내용을 정리한 포스트 입니다.
Relation in mathematics
set: 서로 다른 elements를 가지는 collection으로 하나의 set에서 elements의 순서는 중요하지 않다.
수학에서의 relation의 의미는 다음과 같다.
set A와 set B가 있다고 하자. 이 때, set A의 원소 하나와 set B의 원소 하나를 하나의 pair로 만들자고 하자. 이때, 만들 수 있는 모든 pair를 수학적으로 표현하면 다음과 같다.
\[\text{Cartesian product } A \times B = {(a, b) | a \in A \text{ and } b \in B}\]binary relation: 두 개의 집합 A, B 가 있을 때, $A \times B$ 의 부분 집합을 의미n-ary relation: n개의 집합 $X_1, X_2, \ldots, X_n$ 이 있을 때, $X_1 \times X_2 \times \ldots \times X_n$의 부분 집합을 의미
이 때, 각 집합에서 원소 한 개씩 선택해 하나의 pair를 만든 것을 튜플이라고 부른다.
정리하자면, 수학에서의 relation을 정리하면 Cartesian product의 부분 집합으로 튜플들의 집합이라고 부른다.
Relational data model
data model에서는 set의 원소를 element, value라고 하며 이런 값들의 집합 즉, 수학에서의 set을 도메인이라고 한다.
마찬가지로 data model에서도 tuple을 가질 수 있으며 이 전체를 relation이라고 부른다.
student relation을 예로 들어보자.
- domain 정의
- students_ids: 학번 집합, 7자리 integer 정수
- human_names: 사람 이름 집합, 문자열
- university_grads: 대학교 학년 집합, {1, 2, 3, 4}
- major_names: 대학교에서 배우는 전공 이름 집합
- phone_numbers: 핸드폰 번호 집합
- relation 만들기
attribute: relation에서 어떤 역할을 수행하는지 구분하기 위해 붙인 이름을 의미- students_ids → id
- human_names → name
- university_grades → grade
- major_names → major
- phone_numbers → phone_num
- phone_numbers → emer_phone_num
이러한 관계를 잘 표현하기 위해서 그림보다는 table로 표현하며 이런한 이유로 relation을 table이라고 말한다.
위의 예시를 테이블로 표현하면 아래와 같다.
| id | name | grade | major | phone_num | emer_phone_num |
|---|---|---|---|---|---|
| 2022022 | 홍진호 | 4 | 스타 | 010-1234-5678 | 010-3412-0429 |
| 2022237 | 손흥민 | 3 | 축구 | 010-4523-4912 | 010-3777-1910 |
| 2021411 | 최민정 | 2 | 쇼트트랙 | 010-0409-5710 | 010-5811-9348 |
- relation name: STUDENT
- attribute: id, name, grade, major, phone_num, emer_phone_num
- tuple: 표에서 하나의 행의 값들
- relation(table): 모든 tuple + attribute(표 전체)
위의 개념을 정리하면 다음과 같다.
| 주요 개념 | 설명 |
|---|---|
| domain | set of atomic values |
| domain name | domain 이름 |
| attribute | domain이 relation에서 맡은 역할 이름 |
| tuple | 각 attribute의 값으로 이루어진 리스트, 일부 값은 NULL일 수 있다 |
| relation | set of tuples |
| relation name | relation의 이름 |
atomic: 더 이상 나눠질 수 없는(뒤에서 설명)
Relation schema
relation schema는 relation의 구조를 나타내며 relation의 이름과 attributes 리스트로 표기된다.
- e.g. STUDENT(id, name, grade, major, phone_num, emer_phone_num)
이 때 attributes와 관련된 constraints도 포함한다.
degree of a relation
relation schema에서 attributes의 수를 degree라고 한다.
- e.g. STUDENT(id, name, grade, major, phone_num, emer_phone_num) → degree 6
relation(or relation state)
위에서는 relation을 모든 tuple과 attributes를 포함해서 relation이라고 했지만 attributes를 제외한 모든 tuple만을 가르킬 때 relation 혹은 relation state라고도 한다.
이러한 이유로 문맥을 통해서 tuple들 + attributes 인지 아니면 tuple들 만인지 파악이 필요하다.
Relational database
Relational database는 relational data model을 기반하여 구조화된 database 로 relationl database는 여러 개의 relations로 구성된다.
relational database schema: relation schemas set + integrity constraints set
Relation 특징
- relation은 중복된 tuple을 가질 수 없다(relation is set of tuples)
- relation의 tuple을 식별하기 위해 attribute의 부분 집합을 key로 설정한다.
- relation에서 tuple의 순서는 중요하지 않다.
- 하나의 relation에서 attribute의 순서는 중요하지 않다.
- attribute는 atomic 해야한다(composite or multivalued attribute 허용 안됨)
- ex. address: 서울특별시 강남구 청담동 → 시/구/동 으로 나눠질 수 있으며 이런 경우를 composite attribute라고 함
- ex. major: 컴공, 디자인 → 컴공/디자인 으로 나눠질 수 있으며 이런 경우를 multivalued attribute라고 함
NULL
NULL은 다음과 같은 의미를 가진다.
- 값이 존재하지 않는다.
- 값이 존재하나 아직 그 값이 무엇인지 알지 못한다.
- 해당 사항과 관련이 없다.
이렇게 NULL은 중의적인 의미를 가지므로 최대한 적게 사용하는 것이 좋다.
Keys
key에는 여러 종류가 있다.
superkey: relation에서 tuples를 unique하게 식별할 수 있는 attributes set- e.g. PLAYER(id, name, team_id, back_number, birth_date)의 superkey는 {id, name, team_id, back_number, birth_date}, {id, name}, {name, team_id, back_number}, …etc
candidate key: 어느 한 attribute라도 제거하면 unique하게 tuples를 식별할 수 없는 super key로 key 또는 minimal superkey라고 말한다.- e.g. PLAYER(id, name, team_id, back_number, birth_date)의 superkey는 {id}, {team_id, back_number}
primary key: relation에서 tuples를 unique하게 식별하기 위해 선택된 candidate key- e.g. PLAYER(id, name, team_id, back_number, birth_date)의 primary key는 {id} or {team_id, back_number}
- 보통 attribute 가 적은 것을 primary key로 선택한다. ({id} 와 {team_id, back_number} 중 대부분 {id}를 선택)
unique key: primary key가 아닌 candidate keys로 alternate key라고 부른다.- e.g. PLAYER(id, name, team_id, back_number, birth_date)의 unique_key는 {team_id, back_number}
foreign key: 다른 relation의 PK를 참조하는 attributes set- e.g. PLAYER(id, name, team_id, back_number, birth_date)와 TEAM(id, name, manager)가 있을 때 foreign key는 PLAYER의 {team_id}
- team_id가 TEAM을 참조
Constraints
constraints는 relational database의 relations들이 언제나 항상 지켜줘야 하는 제약 사항이다.
implicit constraints: relational data model 자체가 가지는 constraints- relation은 중복되는 tuple을 가질 수 없다.
- relation 내에서는 같은 이름의 attribute를 가질 수 없다.
schema-based constraints: 주로 DDL을 통해 schema에 직접 명시할 수 있는 constraints- explicit constraints
Schema-based constraints
schema-base constraints에는 여러 constraints가 있다.
domain constiraints: attribute의 value는 해당 attribute의 domain에 속한 value여야 한다.- e.g. grade(학년)에는 5 이상의 값이 들어갈 수 없다.
key constraints: 서로 다른 tuples는 같은 value의 key를 가질 수 없다.NULL value constraint: attribute가 NOT NULL로 명시됐다면 NULL을 값으로 가질 수 없다.entity integrity constraint: primary key는 value에 NULL을 가질 수 없다.referential integrity constraint: FK와 PK와 도메인이 같아야 하고 PK에 없는 values를 FK가 값으로 가질 수 없다.- PLAYER - team_id에 TEAM - id에 없는 value가 존재할 수 없음