Skip to content
Advertisement

Unique constraint keys not invoked when a field is NULL

I have a table named AQI, with the following column enter image description here

Only one unique value of date, pollutant_code, source_id and time are able to exist, so I defined a unique constraint source_code_time_uq.

And the upsert query like

The upsert method work normally when all the field available, but when I put NULL in the time column (in an attempt to make that row represent AQI data for a whole day), the source_code_time_uq constraint doesn’t invoked and it still insert a new row.

So how can I add unique constraint check on the field that can also be NULL , do I need to update my upsert query ?

Advertisement

Answer

You can use a filtered unique index:

Then, you probably also want to guarantee only one NULL row per day, so:

Of course, remove the unique constraint as well.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement