Home > Database > Mysql Tutorial > How to Insert Records into SQLite Only If They Don't Already Exist?

How to Insert Records into SQLite Only If They Don't Already Exist?

Susan Sarandon
Release: 2024-12-20 10:15:10
Original
342 people have browsed it

How to Insert Records into SQLite Only If They Don't Already Exist?

SQLite: Inserting Records Only If They Don't Exist

In SQLite, the IF NOT EXISTS syntax used in Microsoft SQL Server is not directly supported. This can be a challenge when trying to insert records while ensuring their uniqueness.

Workaround 1: INSERT OR IGNORE

One workaround is to use the INSERT OR IGNORE command. This syntax allows you to insert a new record into a table, but if a record with the same key already exists, the insert will be ignored. For example:

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

Workaround 2: SELECT and INSERT

Another approach is to use a combination of a SELECT statement and an INSERT statement:

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

This syntax checks if a record with the specified EventTypeName already exists. If it does not, the INSERT statement is executed and a new record is added to the table.

The above is the detailed content of How to Insert Records into SQLite Only If They Don't Already Exist?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template