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
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read