Page 1 of 1

Insert a row if it does not exist

Posted: Mon Feb 02, 2026 12:22 pm
by 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'
);