Insert or Update (Upsert) logic
Thinking through the case that if you know the key beforehand through a deterministic process. Then MS SQL Server has a very handy builtin constraint that you can turn off so that you no longer have to perform complicated merge logic i.e. you are happy with putting the first result when doing an insert.
Change the constraint on the your key to
IGNORE_DUP_KEY = ON
Example
CREATE TABLE [abc](
[Id] [int] NOT NULL,
CONSTRAINT [PK_abc] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Then you can do the following statement as many times as you want and the first statement is run and all others with the same key are ignored after that. This means you can write a simple INSERT
statement instead of a more complicated MERGE
or transaction based SELECT
and UPDATE
INSERT INTO abc (Id) VALUES (1);
In Postgres use the CONFLICT
statement