How to write insert and update operations in a single query?
When we attempt to update or insert a record based on the primary key, we use an if-else condition in our code base and write a separate query for that. But we can do this in our SQL server in a single query that is more compact and faster.
For example, let’s create a users
table and attempt to update and insert it in a single query.
If Exists then Update else Insert in SQL Server
IF EXISTS( SELECT 1 FROM users WHERE user_id = 2 )
UPDATE users SET user_name = 'Sujan', user_phone = '9988776655' WHERE user_id = 2
ELSE
INSERT INTO users ( user_name, user_phone ) VALUES ( 'Rohit', '1122334455' )
CREATE TABLE dbo.users
(
user_id int IDENTITY(1,1) PRIMARY KEY,
user_name varchar(50) NULL,
user_phone varchar(12) NULL
)
GO