[SQL]Primary Key & Foreign Key

김보림·2024년 6월 11일

SQL 기초

목록 보기
13/17

📌Primary Key (기본키)


  • 테이블의 각 레코드를 식별
  • 중복되지 않은 고유값을 포함
  • Null값을 포함할 수 없음
  • 테이블 당 하나의 기본키를 가짐

생성방법


Primary Key는 하나만 설정할 수도 혹은 여러개를 설정할 수도 있다

  • 테이블생성하면서 기본키 설정
Create Table tablename
(
	column1, data type not null,      #Null값을 포함할 수 없으니 Not Null
    column2, data type not null,      
    ...
    Constraint conatraint_name        #constraint는 생략 가능하다
    Primary key (column1, column2,....)
);
  • 이미 생성되어 있는 테이블에 기본키 설정하기

Alter Table tablename Add Primary Key (column1,column2...)

삭제방법


Primary Key는 각 테이블당 하나의 기본키를 가지므로 한개든 두개든 그냥 Drop하면 된다

Alter Table tablename Drop Primary Key;

📌Foreign Key (외래키)


  • 한 테이블을 다른 테이블과 연결
  • 참조되는 테이블의 항목은 그 테이블의 기본키(혹은 단일값)

생성방법


  • 테이블생성하면서 외래키 설정

Create Table tablename
(
	column1, data type not null,      
    column2, data type not null,      
    ...
    Constraint conatraint_name        
    Primary Key (column1, column2,....),
    Constraint constraint_name            #constriant 생략가능
    Foreign Key (colum3, column4,...) References REF_tablename(REF_column)
);
  • 이미 생성되어 있는 테이블에 외래키 설정하기


Alter Table tablename 
Add Foreign Key (column)
References REF_tablename(REF_columns);

삭제방법


기본키와 달리 외래키는 삭제할 때 이름을 적어줘야 한다

Alter Table tablename Drop Foreign Key constraint_name;

만약 constraint로 이름을 지정하지 않았을 경우, 자동 생성된 이름을 확인하면 됨.
Show create table tablename 을 치면 자동생성된 이름을 확인할 수 있음.

profile
볼로그

0개의 댓글