Postgres INSERTAR EN CONFLICTO ACTUALIZAR vs INSERTAR o ACTUALIZAR
yo tengostock_price_alert
Mesa con 3 columnas.stock_price_id
esPRIMARY KEY
& ademásFOREIGN KEY
a otra mesa. Definición de la tabla a continuación:
create table stock_price_alert (
stock_price_id integer references stock_price (id) on delete cascade not null,
fall_below_alert boolean not null,
rise_above_alert boolean not null,
primary key (stock_price_id)
);
Necesito ya sea:
1)INSERT
registrar si no existe
-- query 1
INSERT INTO stock_price_alert (stock_price_id, fall_below_alert, rise_above_alert)
VALUES (1, true, false);
2)UPDATE
registrar si existe
-- query 2
UPDATE stock_price_alert SET
fall_below_alert = true,
rise_above_alert = false
WHERE stock_price_id = 1;
Primero necesito emitirSELECT
consulta sobrestock_price_alert
tabla, para decidir si realizar la consulta (1) o (2).
Postgres apoyaINSERT INTO TABLE .... ON CONFLICT DO UPDATE ...
:
-- query 3
INSERT INTO stock_price_alert (stock_price_id, fall_below_alert, rise_above_alert)
VALUES (1, true, false)
ON CONFLICT (stock_price_id) DO UPDATE SET
fall_below_alert = EXCLUDED.fall_below_alert,
rise_above_alert = EXCLUDED.rise_above_alert;
En lugar de usar query (1) o (2), ¿puedo usar siempre query (3)? Entonces no necesito emitirSELECT
consulta en anterior y ayuda a simplificar el código.
Pero me pregunto, ¿cuál es la mejor práctica? ¿La consulta (3) causará problemas de rendimiento o efectos secundarios no deseados? Gracias.