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
'DB > PostgreSQL' 카테고리의 다른 글
[PostgreSQL] View Table(뷰 테이블)에 대해서 알아보자. (0) | 2022.11.11 |
---|---|
[PostgreSQL] PostgreSQL의 멀티 칼럼 인덱스에 대해서 알아보자. (Multicolumn Indexes) (0) | 2022.06.30 |
[PostgreSQL] PostgreSQL의 GiST, SP-GiST Index에 대해서 알아보자. (0) | 2022.06.19 |
[PostgreSQL] PostgreSQL의 Geometric Type에 대해서 알아보자. (0) | 2022.06.19 |
[PostgreSQL] PostgreSQL의 B-tree, Hash Index에 대해서 알아보자. (0) | 2022.06.19 |