"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve IF NOT EXISTS Functionality in SQLite?

How to Achieve IF NOT EXISTS Functionality in SQLite?

Posted on 2025-03-23
Browse:102

How to Achieve IF NOT EXISTS Functionality in SQLite?

SQLite: Alternative to IF NOT EXISTS

SQLite does not natively support the IF NOT EXISTS syntax, which is commonly used in Microsoft SQL Server to conditionally insert data into a table only if it does not already exist. However, there are several alternative approaches to achieve the same functionality in SQLite.

1. INSERT OR IGNORE

The INSERT OR IGNORE statement instructs SQLite to attempt an insertion into the specified table, ignoring any errors that would result from duplicate key violations. This effectively creates a new row if the specified key does not exist and does nothing if it already exists.

INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES ('ANI Received');

2. SELECT...WHERE NOT EXISTS

This alternative approach uses a SELECT statement to check for the existence of the record before performing the insertion. If the SELECT statement returns no rows (indicating the record does not exist), the INSERT statement is executed.

INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');

Both of these approaches provide alternatives to the IF NOT EXISTS syntax and can be used to conditionally insert data into a SQLite table only if the specified key does not exist.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3