[DB] 관계형 데이터베이스 개념과 Keys

쉬운코드 강의

relational data model

relation은 수학에서 나온 개념, 수학적 relation을 이해하기 위해 배경지식인 set를 알고 있어야 한다.

  • set은 집합으로, 서로 다른 elements를 가지는 collection
  • 하나의 set에서 elements의 순서는 중요하지 않다.

 

수학에서 릴레이션

수학에서 말하는 relation은 카다시안 곱(Cartesian Product)의 부분집합이다. (subset of Cartesian Product)

 

수학에서 relation 개념을 relational data model에 적용

  • set -> domain (relational data model에서 도메인마다 이름을 붙일 수 있다.)
  • 동일한 domain이 같은 릴레이션에서 두 번 사용될 때, 역할과 목적이 다를 수 있기 때문에 도메인의 역할을 표시해줘야 한다.
    이때 사용하는 것이 attribute(릴레이션 도메인들이 수행하는 역할을 부여)
  • relation을 가장 잘 표현하는 방법은 테이블

 

Relational Data Model 주요 개념 정리

  • domain : set of atomic values
  • domain name : domain 이름
  • attribute : domain이 relation에서 맡은 역할 이름
  • tuple : 각 attribute의 값으로 이루어진 리스트, 일부 값은 NULL 일 수 있다.
  • relation : set of tuples
  • relation name : relation의 이름

 

relation schema

  • relation의 구조를 나타낸다.
  • relation 이름과 attributes로 표기
  • attributes와 관련된 constraints도 포함
  • STUDENT(id, name, grade, major, phone_num, emer_phone_num)

 

relational database

  • relational data model 기반으로 구조화된 database
  • relational database는 여러 개의 relation로 구성된다.

 

relational database schema

  • relation schema set + Integrity constraints set

 

relation의 특징들

  • 중복된 튜플을 가질 수 없다 (relation : set of tuples)
  • tuple을 식별하기 위해 attribute의 부분집합을 key로 설정
  • tuple의 순서는 중요하지 않다.
  • attribute의 이름이 중복될 수 없다.
  • attribute의 순서도 중요하지 않다.
  • attribute는 atomic 한 값을 가져야 한다.
    • ex) address attribute가 서울특별시 강남구 청담동일 경우 잘라줘야 한다.
    • ex) major attribute가 컴공, 디자인일 경우 잘라줘야 한다.

 

NULL의 의미

  • 값이 존재하지 않는다.
  • 값이 존재하나 아직 그 값이 무엇인지 알지 못한다.
  • 해당 사항과 관련 없다.

NULL의 의미가 이렇게 중의적이기 때문에 되도록 사용하면 안 된다.

 

Keys

super key

  • relation에서 tuples를 unique 하게 식별할 수 있는 attribute set

candidate key

  • 어느 한 attribute라도 제거하면 unique 하게 tuples를 식별할 수 없는 super key
  • minimal super key

primary key

  • relation에서 tuples를 unique 하게 식별하기 위해 선택된 candidate key
  • 보통 candidate key 중 attribute 수가 적은 것이 primary key로 선정된다.

unique key(alternate key)

  • 선택되지 못한 candidate keys

foreign key

  • 다른 relation의 PK를 참조하는 attribute set

 

constraints

relational database의 relation들이 언제나 지켜줘야 하는 제약사항

implicit constraints

  • relational data model 자체가 가지는 constraints
  • relation은 중복되는 tuple을 가질 수 없다.
  • relation 내에서는 같은 이름의 attribute를 가질 수 없다.

schema-based constraints(explicit constraints)

  • 주로 DDL을 통해 schema에 직접 명시할 수 있는 constraints

domain constraint

  • attribute의 value는 해당 attribute의 domain에 속한 value여야 한다.

key constraint

  • 서로 다른 tuple은 같은 value의 key를 가질 수 없다.

NULL value constraint

  • attribute가 NOT NULL로 명시됐다면 NULL 값을 가질 수 없다.

entity integrity constraint

  • primary key는 value에 NULL을 가질 수 없다.

referential integrity constraint

  • FK와 PK와 도메인이 같아야 하고 PK에 없는 values를 FK 값으로 가질 수 없다.