[PostgreSQL] PostgreSQL의 유니크 인덱스에 대해서 알아보자. (Unique Index)
A unique index guarantees that the table won't have more than one row with the same value.
It's advantageous to create unique indexes for two reasons: data integrity and performance.
Lookups on a unique index are generally very fast.
유니크 인덱스는 테이블에서 한개 이상의 row가 동일한 값을 갖지 않는 것을 보장한다.
data integrity와 performance 측면에서 장점이 있다.
찾는 속도가 가장 빠르다.
Only B-tree indexes can be declared unique.
오직 B-tree 인덱스만 유니크로 선언 가능하다.
CREATE UNIQUE INDEX name ON table (column [, ...])
people 테이블을 만들어보자.
CREATE TABLE people (
id integer,
first_name varchar(50),
last_name varchar(50)
);
\d people
Result
Table "public.people"
Column | Type | Collation | Nullable | Default
------------+-----------------------+-----------+----------+---------
id | integer | | |
first_name | character varying(50) | | |
last_name | character varying(50) | | |
여기에 유니크 인덱스를 걸어주자.
CREATE UNIQUE INDEX people_pkey ON public.people USING btree (id);
\d people
Result
Table "public.people"
Column | Type | Collation | Nullable | Default
------------+-----------------------+-----------+----------+---------
id | integer | | |
first_name | character varying(50) | | |
last_name | character varying(50) | | |
Indexes:
"people_pkey" UNIQUE, btree (id)
단, 이미 id 컬럼에 동일한 row가 들어있다면 에러가 발생한다.
그럴땐 유니크를 걸지 않던가 중복 값을 제거해줘야 한다.
테이블 생성시 PK가 정의되면 자동으로 Unique 인덱스를 생성한다.
CREATE TABLE people (
id integer PRIMARY KEY,
first_name varchar(50),
last_name varchar(50)
);
SELECT * FROM pg_indexes WHERE TABLENAME = 'people';
Result
schemaname | tablename | indexname | tablespace | indexdef
------------+-----------+-------------+------------+-------------------------------------------------------------------
public | people | people_pkey | | CREATE UNIQUE INDEX people_pkey ON public.people USING btree (id)
(1 row)
REFERENCES
PostgreSQL : Documentation: 13: PostgreSQL 13.7 Documentation
postgrespro.com