SQLite – INSERT IF NOT EXISTS ELSE UPDATE
Last Updated :
19 Mar, 2024
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:
- users is the name of the table.
- (id, name, email) specifies the columns to insert or replace.
- VALUES (value1, value2, value3) defines the values to be inserted or replaced, typically provided as parameters.
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', '[email protected]'),
('mahi', '[email protected]'),
('vardhana', '[email protected]');
Output:
Users TableExplanation: 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', '[email protected]');
Output:
OutputExplanation:
- INSERT OR REPLACE INTO users: It says that you want to insert a new record into the users' table or if the record already exists and the primary key (in this case, id) is the same then to replace it.
- (id, username, email): This means the columns in which data will be saved.
- VALUES (1, 'john doe', '[email protected]'): This defines where in the rows and columns to insert these values. As we can see that the values get updated of primary key 1.
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', '[email protected]');
Output:
OutputExplanation:
- INSERT OR REPLACE INTO users: It says that you want to insert a new record into the users' table or if the record already exists and the primary key (in this case, id) is the same then to replace it.
- (id, username, email): It is the explanation of which columns to where the data will be inserted.
- VALUES (2, 'minal', '[email protected]'): This specifies the values to be inserted into the corresponding columns.
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', '[email protected]' );
Output:
OutputExplanation:
- INSERT OR REPLACE INTO users: It says that you want to insert a new record into the users' table or if the record already exists and the primary key (in this case, id) is the same then to replace it.
- (id, username, email): This indicates the columns into which the data should be inserted or copied.
- VALUES (4, 'Gaurav', '[email protected]'): The value corresponding to 4 will be inserted into the "id" column, 'Gaurav' into the "username" column, and '[email protected]' into the "email" column.
Example 4: Update The Email For An Existing User Profile Based On The Username
UPDATE users SET email = '[email protected]' WHERE username = 'john_doe';
Output:
OutputExplanation:
- UPDATE users: The query now refers to the table that will be modified, and this is table "users".
- SET email = '[email protected]': It replaces the original 'email' column with '[email protected]'.
- WHERE username = 'john_doe': This method prevents the unnecessary updating of records by only updating records where the "username" column is equal to 'john_doe'..
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.
Similar Reads
How to Update If Row Exists Else Insert in SQL Server
Data update and data insert are two important functions to add and update data in SQL Server Tables. Using SQL queries we can check for specific data if it exists in a table. The update query with the WHERE Clause can be used to update data passed from the front end or any other data generated from
6 min read
NOT IN vs NOT EXISTS in SQLite
When querying a database in SQLite, there are situations where you need to filter out rows based on conditions that involve another set of values or a subquery. This is where the NOT IN and NOT EXISTS operators come into play. While both operators achieve similar results, they do so in different way
5 min read
How to Insert Row If Not Exists in SQL
Managing and manipulating data in SQL is essential, especially when it comes to avoiding duplicate entries in a database. Duplicate records can lead to data inconsistencies and errors that disrupt operations and analysis. The "INSERT IF NOT EXISTS" feature in SQL acts as a safeguard, ensuring that o
6 min read
How to INSERT If Row Does Not Exist in PL/SQL
The database management system (DBMS) stores, processes, and manipulates data in a database. All data in a database can be stored using the INSERT command or updated using the UPDATE command. These two data manipulation language (DML) commands play a key role in adding and maintaining the data. Some
7 min read
Truncate Table if Exists in SQL
When managing databases it is common to encounter scenarios where we need to remove all the data from a table while preserving the table structure. The TRUNCATE statement is a popular SQL command used for this purpose. However, what happens if the table we want to truncate doesnât exist? Executing a
3 min read
How to Insert If Not Exists in SQL SERVER?
Adding Data to a table in SQL Server is a key operation. Data can be inserted into tables using many different scenarios like plain data inserted into a table without checking anything or checking if data already exists in the target table and only if the data does not exist then the new data is ins
7 min read
NOT IN vs NOT EXISTS in SQL
Structured Query Language (SQL) is a domain-specific language used in managing and manipulating data in a relational database. In SQL, we use these two operators i.e. NOT IN and NOT EXISTS to filter out and efficiently retrieve our data from a table. Both of these operators are negations of IN and E
5 min read
PL/SQL INSERT ON DUPLICATE KEY UPDATE
In database management, maintaining data integrity while inserting new records is a common challenge. we may want to insert a new record, but if it already exists based on a unique key, we need to update the existing record. This process is known as "Upsert". In this article, we will explain how to
5 min read
How to Check if a Row Already Exists in SQLite?
SQLite is a widely used relational database management system due to its simplicity, lightweight design and energy efficiency features. When working with SQLite databases, It is very important to ensure data integrity therefore it is necessary to avoid accidentally inserting duplicated records. In t
3 min read
NOT IN vs NOT EXISTS in PL/SQL
PL/SQL is a Procedural Language/Structured Query Language. It allows developers to create robust, modular, and reusable code for implementing data manipulation, and transaction control in databases. Two crucial operators in PL/SQL are NOT IN and NOT EXISTS, which are often used to filter data based
5 min read