I have rows like these on postgres:
name | address | college
john | rome |
john | rome |
max | tokyo |
I create a table like this:
create test (
name varchar(10),
address varchar(20),
college varchar(20),
constraint test_uq unique (name,address,college);
How can I make null values become unique, so the output can be like this:
name | address | college
john | rome |
max | tokyo |
If you make it a primary key, instead of a unique constraint, it would work. For that, the column
college
would have to beNOT NULL
and use (for instance) empty strings instead of NULL values. Or are you looking for a query?If you just need unique records in the query result use
SELECT DISTINCT
If you want to enforce unique records ignoring null values you must create a conditional unique index
HTH
Postgres documentation claims that this behaviour is compliant with the SQL standard:
One possibility is to rethink your schema (to be honest, a uniqueness constraint on
name+address+college
doesn't make a whole lots of sense in your example).NULL is unknown so a value of NULL being equal to NULL can never be true. To work around this law do this.
Create a new look-up table for your colleges. In that table have a record with the value None. Then put a Foreign Key to the new college look-up table.
This is pseudo code so you may have to mess with it to make it work, but here is the basic idea.