I am using Postgres 9.6, and have an issue where I am using jsonb_populate_recordset
.
I created an UNIQUE
constraint on the table, but I am able to bypass this when performing an INSERT
with null values.
Is there was a way to force the unique constraint to keep only 1 record, even if it has null
values, and not allow duplicates afterward?
Here is a quick example:
CREATE TABLE person(
person_id SERIAL PRIMARY KEY,
person_name TEXT,
CONSTRAINT unq_person UNIQUE(person_name)
);
INSERT INTO person (person_name) VALUES ('Frank');
CREATE TABLE locations(
location_id SERIAL PRIMARY KEY,
city TEXT,
state TEXT,
address TEXT,
address_country TEXT,
postal_code TEXT,
person_id INTEGER REFERENCES person(person_id)
ON DELETE CASCADE,
CONSTRAINT unq_location UNIQUE(city, state, address, address_country, postal_code, person_id)
);
In this example, city and address are null
(but theoretically, they could all be null
, or any combination of record properties).
Every time I run the following query, a new record gets inserted. I don't want more than one of these records.
INSERT INTO locations (city, state, address, address_country, postal_code, person_id)
SELECT city, state, address, address_country, postal_code, person_id
FROM jsonb_populate_recordset(NULL::locations, '[{"city": null, "address": null, "address_country": "USA", "state": "NY", "person_id": 1, "postal_code": "10001"}]'::jsonb)
How can I only allow 1 record, and not multiple when inserting a JSONB
object into Postgres?