Vous avez besoin d'un index partiel. Supprimez la contrainte uniqe sur la colonne name
et créez un index partiel sur la colonne :
CREATE TABLE customers (
customer_id serial PRIMARY KEY,
name VARCHAR,
email VARCHAR NOT NULL,
active bool NOT NULL DEFAULT TRUE
);
CREATE UNIQUE INDEX ON customers (name) WHERE active;
INSERT INTO customers (NAME, email) VALUES
('IBM', '[email protected]'),
('Microsoft', '[email protected]'),
('Intel','[email protected]');
La requête devrait ressembler à ceci :
INSERT INTO customers (name, email)
VALUES
('Microsoft', '[email protected]')
ON CONFLICT (name) WHERE active
DO UPDATE SET email = excluded.email;
SELECT *
FROM customers;
customer_id | name | email | active
-------------+-----------+-----------------------+--------
1 | IBM | [email protected] | t
3 | Intel | [email protected] | t
2 | Microsoft | [email protected] | t
(3 rows)
Notez l'utilisation correcte de l'enregistrement spécial excluded.
Selon la documentation :