💽 DataBase

SQL

SQL

Structured Query Language
  • 현업에서 쓰이는 Relational DBMS의 표준 언어
  • 종합적인 Datatbase 언어 : DDL + DML + VDL

주요 용어

notion image

SQL에서 Relation

Tuple의 Multi Set(=Bag)
  • 중복된 Tuple을 허용한다.

SQL & RDBMS

💡
SQL은 RDBMS의 표준 언어지만, 구현에 강제가 없기 때문에 RDBMS마다 제공하는 SQL의 스펙이 조금씩 다르다.

예제

IT 회사 관련 RDB 만들기

부서, 사원, 프로젝트 관련 정보들을 저장할 수 있는 RDB를 만들자
  • MySQL(InnoDB)

Database 정의하기

SHOW DATABASES;
notion image
CREATE DATABASE company;
notion image
SHOW DATABASES;
notion image
// 어떤 데이터 베이스가 선택됐는지 확인 SELECT database();
notion image
// 사용할 데이터 베이스 지정 USE company;
notion image
// 어떤 데이터 베이스가 선택됐는지 확인 SELECT database();
notion image
// 데이터 베이스 지우기 DROP DATABASE company;

DATABASE VS SCHEMA

MySQL에서는 DATABASE와 SCHEMA가 같은 의미
  • CREATE DATABASE company == CREATE SCHEMA company
  • 다른 RDBMS에서는 의미가 다름
  • ex) PostgreSQL에서는 SCHEMA가 DATABASE의 namespace를 의미

Table 정의하기

부서, 사원, 프로젝트 관련 정보들을 저장할 수 있는 관계형 데이터 베이스
notion image

DEPARTMENT Table 생성

notion image

Attribute Data Type

숫자

notion image

문자열

notion image

날짜와 시간

notion image

그 외

notion image

Key Constraints : Primary Key

Primary Key를 선언하는 방법
notion image

Key Constraints : Unique Key

Unique Key를 선언하는 방법
notion image

NOT NULL Constraint

NOT NULL을 선언하는 방법
notion image

EMPLOYEE Table 생성

notion image

Attribute DEFAULT

Attribute의 Default 값을 정의할 때 사용
  • 새로운 Tuple을 저장할 때, 해당 Attribute에 대한 값이 없다면 default 값으로 저장
notion image
DEFAULT를 선언하는 방법
notion image

CHECK Constraint

Attribute의 값을 제한하고 싶을 때 사용
notion image
CHECK를 선언하는 방법
notion image

Referential Integrity Constraint : FOREIGN KEY

Attribute가 다른 Table의 Primary Key나 Unique Key를 참조할 때 사용
notion image
FOREIGN KEY를 선언하는 방법
notion image

Constraint 이름 명시하기

이름을 붙이면 어떤 Constraint를 위반했는지 쉽게 파악 할 수 있다.
  • Constraint를 삭제하고 싶을 때 해당 이름으로 삭제 가능
notion image

PROJECT Table 생성

notion image

WORKS_ON Table 생성

notion image

DEPARTMENT Table의 leader_id에 FK Schema 추가

notion image

ALTER TABLE

Table의 Schema를 변경하고 싶을 때 사용
notion image
💡
이미 서비스 중인 Table의 Schema를 변경하는 것이라면 변경 작업 때문에 서비스의 백엔드에 영향이 없을지 검토한 후에 변경하는 것이 중요

DROP TABLE

Table을 삭제할 때 사용
DROP TABLE table_name;

Database 구조를 정의할 때 중요한 점

💡
만드려는 서비스의 스펙과 데이터 일관성, 편의성, 확장성 등을 종합적으로 고려하여 DB Schema를 적절하게 정의하는 것이 중요!

출처