Through this question I felt the need to research and understand a little about the UPSERT . I was wondering what a blessed command this is? I never saw ..
I found some information but it is still not clear to me because there is no "basic command", type UPSERT tabela (id=0, valor='nome')
, for example.
I usually see codes using the following structure:
IF EXISTS (SELECT 1 FROM tabela WHERE id = 0)
UPDATE tabela SET campo = 2 where id = 0
ELSE
INSERT INTO tabela (id, campo) VALUES (0, 1)
END
About upsert found this way :
MERGE INTO tabela
USING (SELECT 0 AS id, 1 AS campo) AS reg
ON tabela.id = reg.id
WHEN MATCHED THEN
UPDATE SET campo = reg.campo
WHEN NOT MATCHED THEN
INSERT(id , campo)
VALUES (reg.id, reg.campo)
So, regarding performance , which way should I use it? the IF
that queries existence by the identifier and defines which flow to follow ( insert or update ) or MERGE
( upsert ) condenses the two commands?