Composite PRIMARY KEY enforces NOT NULL constraints on involved columns

If you need to allow NULL values, use a UNIQUE constraint (or index) instead of a PRIMARY KEY (and add a surrogate PK column – I suggest a serial or IDENTITY column in Postgres 10 or later). Auto increment table column A UNIQUE constraint allows columns to be NULL: CREATE TABLE distributor ( distributor_id GENERATED … Read more

HashSet contains duplicate entries

The problem is that your Element class has not overridden the equals and hashCode methods or these implementations are broken. From Object#equals method javadoc: The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference … Read more

Postgresql enforce unique two-way combination of columns

A variation on Neil’s solution which doesn’t need an extension is: create table friendz ( from_id int, to_id int ); create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id)); Neil’s solution lets you use an arbitrary number of columns though. We’re both relying on using expressions to build the index which is documented https://www.postgresql.org/docs/current/indexes-expressional.html