Search code examples
sqlms-accessms-access-97

Access97: INSERT INTO if not exists


I need to do a very simple task: execute an INSERT INTO query only if the record doesn't exist in the table. I found a lot of hints out there but none of them work in SQL Access97.

Example:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

this won't work because IF NOT EXISTS is not valid.

What is the right way to do this in one SQL clause?


Solution

  • You can build that into an insert . .. select:

    INSERT INTO Users (FirstName, LastName)
        SELECT TOP 1 'John', 'Smith'
        FROM Users
        WHERE NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' );