PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Mehrere NULL-Werte in einer UNIQUE-Spalte zulassen

Hier steckt ein verbreitetes Missverständnis dahinter. Die UNIQUE-Constraint tut bereits genau das, was Sie möchten – eine als UNIQUE definierte Spalte kann problemlos mehrere NULL-Werte enthalten.

Das Handbuch formuliert es deutlich:

In general, a unique constraint is violated when there is more than one row in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, but we have heard that other SQL databases might not follow this rule.

(Die Hervorhebung stammt von mir.)

Ein Punkt ist noch wichtig: Zeichenketten-Typen akzeptieren außerdem die leere Zeichenkette (''), die nicht dasselbe wie NULL ist. Eine leere Zeichenkette löst bei mehrfachem Vorkommen sehr wohl eine Verletzung der Eindeutigkeit aus.

Wollen Sie ausschließlich genau einen NULL-Wert erlauben, benötigen Sie einen partiellen Index, etwa CREATE UNIQUE INDEX ... ON tbl (col) WHERE col IS NOT NULL in Kombination mit einer separaten Sicherstellung.