Skip to content

Instantly share code, notes, and snippets.

@Barolina
Created July 16, 2021 12:31
Show Gist options
  • Save Barolina/32f0751afb8f661a12e5f3c44fb7f625 to your computer and use it in GitHub Desktop.
Save Barolina/32f0751afb8f661a12e5f3c44fb7f625 to your computer and use it in GitHub Desktop.
Postgres: группой индекс уникальности, если одно из поелй может быть NULL
  1. This method can also be used to create a constraint that allows only a single null for each non-null composite indexed value:
CREATE TABLE table (x INTEGER, y INTEGER);

CREATE UNIQUE INDEX i_table ON table (x, (y IS NULL)) WHERE y IS NULL;

INSERT INTO table VALUES (1, NULL);
INSERT INTO table VALUES (2, NULL);
INSERT INTO table VALUES (2, NULL);
ERROR:  duplicate key value violates unique constraint "i_table"
DETAIL:  Key (x, (y IS NULL))=(2, t) already exists.

INSERT INTO table VALUES (2, 3);
INSERT INTO table VALUES (2, 3);

  1. Текстовые поля луше делать всегда NOT NULL, но c default='', если необходимо пустое значение
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment