what is difference UNIQUE, UNIQUE NOT NULL, UNIQUE NULLS DISTINCT, UNIQUE NULLS NOT DISTINCT, in postgresql ?.
CREATE TABLE cus (
customer_id SERIAL PRIMARY KEY,
first VARCHAR(20) UNIQUE,
third VARCHAR(20) UNIQUE NOT NULL,
fourth VARCHAR(20) UNIQUE NULLS DISTINCT,
fifth VARCHAR(20) UNIQUE NULLS NOT DISTINCT
);
>Solution :
There are a few variations at play here…
UNIQUEmeans values in that column must be unique (e.g. they can’t be equal). You can then specify how the database should treat uniques:UNIQUE NULLS DISTINCT(default) – treats NULL values as distinct (so you can still have multiple rows with a NULL value in this column). This is the default behavior, so it’s the same as writingUNIQUEalone.UNIQUE NULLS NOT DISTINCT(default) – treats NULL values as if they are equal, so you can at most have one row with a NULL value in that column.
NOT NULLis a different modifier that just means that column won’t accept NULL values.
So with those in mind, here is the explained behavior for your examples:
CREATE TABLE cus (
customer_id SERIAL PRIMARY KEY,
first VARCHAR(20) UNIQUE,
-- All values in this column must be unique, but can have multiple nulls
third VARCHAR(20) UNIQUE NOT NULL,
-- All values in this column must be unique, nulls not allowed in this column at att
fourth VARCHAR(20) UNIQUE NULLS DISTINCT,
-- All values in this column must be unique, but can have multiple nulls (same as first)
fifth VARCHAR(20) UNIQUE NULLS NOT DISTINCT
-- All values in this column must be unique, at most one NULL value allowed
);