Primary Key + Auto_Increment 를 하고싶을 때,
Sequence, Serial 을 버려라.
Sequence
특징
- 데이터 타입을 따로 명시해야하고.
- 테이블 생성시 같이 선언해야한다.
- 값을 업데이트할 경우, sequence 이름을 명시해야한다.

Serial
특징
- 데이터 타입을 따로 명시할 필요가 없다.
- `INSERT` privilege 를 테이블 권한에 및 `USAGE` privilege 를 기저를 이루는 sequence 에 줘야한다.
(Serial 도 결국 sequence 생성이 이뤄지기 때문에)

✅ PostgreSQL version 10부터는 Identity 가 국룰이다.
특징
- 컬럼의 데이터 타입을 명시해야하고
- 오로지 `INSERT` privilege 만 테이블에 부여하는 것으로 충분하다.

굳이 왜 serial 이 아니라 identity 를 쓸까?
Management

Sequence, Serial 은 Permission 관련해 부자연스러운 동작이 있고 사용이 불편하다.
또, SQL Standard 에도 맞지 않기 때문에 PostgreSQL 10버전부터 Identity 를 사용하기로했다.
📝 결론
PostgreSQL 에서 PK with auto_increment 가 필요하다면 `generated always as identity` 를 사용하자.
🔗 Reference
PostgreSQL에서의 일련번호 처리
번호를 차례대로 매기는 방법
postgresql.kr
PostgreSQL 10 identity columns explained - 2ndQuadrant | PostgreSQL
For PostgreSQL 10, I have worked on a feature called “identity columns”. Depesz already wrote a blog post about it and showed that it works pretty much like serial columns: CREATE TABLE test_old ( id serial PRIMARY KEY, payload text ); INSERT INTO test
www.2ndquadrant.com
Don't Do This - PostgreSQL wiki
A short list of common mistakes. Kristian Dupont provides schemalint a tool to verify the database schema against those recommendations. Database Encoding Don't use SQL_ASCII Why not? SQL_ASCII means "no conversions" for the purpose of all encoding convers
wiki.postgresql.org
PostgreSQL: serial vs identity
To have an integer auto-numbering primary key on a table, you can use SERIAL But I noticed the table information_schema.columns has a number of identity_ fields, and indeed, you could create a col...
stackoverflow.com
'DataBase > PostgreSQL' 카테고리의 다른 글
| [PostgreSQL] Delete duplicates in array (0) | 2022.06.22 |
|---|---|
| [PostgreSQL] CHECK Constraint (0) | 2022.05.04 |
| [PostgreSQL] Trigger + Transaction (0) | 2022.04.18 |
| [PostgreSQL] Transaction + Pool 사용시 주의 (0) | 2022.04.04 |
| [PostgreSQL] Function (feat. trigger) (0) | 2022.03.29 |