티스토리 뷰

TL;DR

 

Postgres 에서  primary key를 unique, autoincrement 로 생성하고 싶다면 serial이 아닌 generated always as identity 를 사용하자

 

내용

 

Postgres 에서 table을 생성하며 PK를 하나씩 증가하는 8바이트 정수형으로 선언하려 BIGSERIAL 을 사용하였는데

그 보다는  generated always as identity 를 사용하는 것이 낫다 한다. 그 이유는

 

1. serial은 Postgres 에서 "auto-generated unique value"를 생성하게 하는 구현이며, SQL 스탠다드가 아니다

2. Postgres 10 부터는 generated as identity 를 지원한다. SQL 스탠다드이다.

 

상세

 

참고 링크: https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-identity-column/

문법은 다음과 같다.

 

column_name type GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY[ ( sequence_option ) ]

 

1. ALWAYS와 DEFAULT

  • DEFAULT 는 자동으로 증가하며 생성시켜주지만, 값을 지정하여 INSERT 할 경우에는 그 값을 사용한다.
  • ALWAYS 는 자동으로 증가하며 생성시켜주고 임의의 값으로 INSERT 할 수 없다.

2. sequence_option

  • 시작 숫자와 증가 단위를 설정하는 것이다.
  • 사용하지 않으면 디폴트는 1, 1이 된다.

공식 문서

링크: https://bit.ly/3XPgH3a

Don't use serial

For new applications, identity columns should be used instead.

Why not?

The serial types have some weird behaviors that make schema, dependency, and permission management unnecessarily cumbersome.

When should you?

  • If you need support to PostgreSQL older than version 10.
  • In certain combinations with table inheritance (but see there)
  • More generally, if you somehow use the same sequence for multiple tables, although in those cases an explicit declaration might be preferable over the serial types.
반응형

'til' 카테고리의 다른 글

docker run -p와 Dockerfile의 EXPOSE  (0) 2022.12.12
COCO dataset 소수점 자리수  (0) 2022.12.03
P99 latency란?  (0) 2022.11.28
Strangler Fig Application  (0) 2022.11.28
k9s를 Ubuntu에 설치하기  (2) 2022.11.16
반응형
잡학툰 뱃지
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함