Insert a row if it does not exist

Post Reply
admin
Site Admin
Posts: 39
Joined: Mon Sep 16, 2024 5:00 pm
Contact:

Insert a row if it does not exist

Post: # 295Post admin »

To insert a row into a table only if it does not already exist, you can use the IF NOT EXISTS condition or other techniques depending on your SQL database. Here's how you can achieve this in SQL Server:
1. Using IF NOT EXISTS
SQL

Code: Select all

IF NOT EXISTS (
    SELECT 1 
    FROM YourTable 
    WHERE ColumnName = 'Value'
)
BEGIN
    INSERT INTO YourTable (ColumnName, AnotherColumn)
    VALUES ('Value', 'AnotherValue');
END;
2. Using INSERT with NOT EXISTS in a Single Query
SQL

Code: Select all

INSERT INTO YourTable (ColumnName, AnotherColumn)
SELECT 'Value', 'AnotherValue'
WHERE NOT EXISTS (
    SELECT 1 
    FROM YourTable 
    WHERE ColumnName = 'Value'
);
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest