[PostgreSQL] NULLS NOT DISTINCT
UNIQUE Index๋ ์ ์ผ์ฑ์ ๋ณด์ฅํ ์ ์๊ฒ ํด์ฃผ๋ ๊ฐ๋ ฅํ ๊ธฐ๋ฅ์ด์ง๋ง ๊ตฌ๋ฉ๋ ์๋ค.
ํ ์ด๋ธ๊ณผ ์ ๋ํฌ๋ฅผ ํ๋ ๋ง๋ค์ด๋ณด๊ฒ ๋ค.
CREATE TABLE testable (
id SERIAL PRIMARY KEY,
age int NULL,
name TEXT NOT NULL
);
CREATE UNIQUE INDEX uidx_name_age on testable(name, age);

๊ทธ๋ฌ๋ฉด ๋น์ฐํ ์ค๋ณต ๋ฐ์ดํฐ ์กฐํฉ์ ๋ํด์๋ ์ค๋ฅ๋ฅผ ๋ฐ์์ํฌ ๊ฒ์ด๋ค.
INSERT INTO testable(age, name)
VALUES (10, 'john');
INSERT INTO testable(age, name)
VALUES (10, 'john');

๊ทผ๋ฐ ๋ฌธ์ ๋, ์ ๋ํฌ ์กฐ๊ฑด ์ค์ null์ด ํฌํจ๋ ๊ฒฝ์ฐ๋ค. null์ด ํฌํจ๋๋ฉด ๊ทธ๊ฑด ์ ๋ํฌ ์กฐ๊ฑด์์ ๋ฐฐ์ ๋๋ค!
INSERT INTO testable(age, name)
VALUES (NULL, 'john');
INSERT INTO testable(age, name)
VALUES (NULL, 'john');
์๋์น ์์ ์ค๋ณต ๋ฐ์ดํฐ๊ฐ ๋ฐ์ํ ์ ์๋ ๊ฒ์ด๋ค.
NULLS NOT DISTINCT ์ต์
๋คํํ๋ ์ด ๋ฌธ์ ๋ฅผ ํด์ํ๊ธฐ ์ํ ์ต์
์ด ์๋ค.
์ด ๊ธฐ๋ฅ์ PostgreSQL 15 ๋ฒ์ ๋ถํฐ ์ง์๋๋ค.
DROP INDEX uidx_name_age;
CREATE UNIQUE INDEX uidx_name_age on testable(name, age) NULLS NOT DISTINCT;
์์ ๊ฐ์ด ์ธ๋ฑ์ค ์์ฑ์์ ์ต์
์ ์ฃผ๋ฉด, null๋ ํ๋์ ๊ฐ์ผ๋ก ๊ฐ์ฃผํด์ ์ธ๋ฑ์ค ์กฐ๊ฑด์ผ๋ก ์ฌ์ฉํ๊ฒ ๋๋ค.
๊ทธ๋ฌ๋ฉด ์ด์ ๋ ์ค๋ณต ๋ฐฐ์ ๊ฐ ์ ๋ ๊ฒ์ด๋ค.
์ฐธ์กฐ
https://www.postgresql.org/about/featurematrix/detail/unique-nulls-not-distinct/
https://stackoverflow.com/questions/8289100/create-unique-constraint-with-null-columns