Open In App

SQLite – INSERT IF NOT EXISTS ELSE UPDATE

SQLite is a popular choice for embedded database applications due to its lightweight nature and ease of use. One common scenario in SQLite is the need to insert a row into a table if it does not already exist and update it if it does.

In this article, We will explore how to achieve this efficiently by understanding the SQLite’s INSERT OR REPLACE statement with the help of examples and so on.



How to Insert Record only if the Record Doesn’t Exist?

When working with SQLite databases, there are often situations where we need to insert a new record if it doesn’t exist, or update an existing record if it does.

This can be achieved using a combination of INSERT OR REPLACE statements that provide a more concise way to handle it.



Syntax:

INSERT OR REPLACE INTO users (id, name, email) VALUES (value1, value2, value3);

Explanation:

To understand How to Insert Record only if the Record Doesn’t Exist we need a table on which we will perform various operations and queries. Here we will consider a table called users which contains id, username and email as Columns.

Create Table:

CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE,
email TEXT
);

Insert Data:

INSERT INTO users (username, email) VALUES
('minal', 'minal@gmail.com'),
('mahi', 'mahi@gmail.com'),
('vardhana', 'vardhana@gmail.com');

Output:

Users Table

Explanation: Table got created successfully.

Examples of How to Insert Record only if the Record Doesn’t Exist

Below are the some example queries of how to insert a new data if it doesn’t exist or update it if exist.

Example 1: Insert A New User Profile If It Doesn’t Exist, Or Update The Email If The Username Already Exists

INSERT OR REPLACE INTO users (id, username, email) VALUES (1, 'john doe', 'john@gmail.com');

Output:

Output

Explanation:

Example 2: Insert A New User Profile If It Doesn’t Exist, Or Update Both Username And Email If The Id Already Exists

INSERT OR REPLACE INTO users (id, username, email) VALUES (2, 'minal', 'minal@gmail.com');

Output:

Output

Explanation:

Example 3: Insert A New User Profile If It Doesn’t Exist, Or Update The Email If The Username Already Exists

INSERT OR REPLACE INTO users (id, username, email) VALUES (4,'Gaurav', 'gaurav@gmail.com' );

Output:

Output

Explanation:

Example 4: Update The Email For An Existing User Profile Based On The Username

UPDATE users SET email = 'new_email@example.com' WHERE username = 'john_doe';

Output:

Output

Explanation:

Conclusion

SQLite is a dataset whose INSERT OR REPLACE function acts as a particular construct which enabling one to insert data that doesn’t exist or update it when it does exist. According to this function, developers can set up an automated data table they managed and so the SQLite databases in the applications will perform better and with precision.


Article Tags :