How to Write Upsert in SQL?
Last Updated :
26 Mar, 2024
In SQL, the "upsert" operation is a combination of "insert" and "update" operations. It allows you to add new rows if they do not exist in the table, or to replace existing rows if they exist. The Upsert function is useful when you need to synchronize data between different sites, maintain data consistency, or manage collaboration efficiently.
In this article, we'll explore the introduction of SQL's "upsert" operation, which combines insertion and updating. We'll cover its syntax and provide examples to illustrate its functionality in data management.
Upsert in SQL
Upsert, a combination of "update" and "insert," is a database operation that inserts a new record into a table if it doesn't exist, or updates an existing record if it does. It simplifies data maintenance by ensuring seamless insertion or modification of records based on a specified condition, enhancing data integrity and efficiency.
Syntax:
SQL syntax for advanced operations may vary depending on the database system. Commonly used syntax includes:
1. Using MERGE statement:
MERGE INTO target_table AS target
USING source_table AS source
ON (target.id = source.id)
WHEN MATCHED THEN
UPDATE SET target.column1 = source.new_value1,
target.column2 = source.new_value2
WHEN NOT MATCHED THEN
INSERT (id, column1, column2)
VALUES (source.id, source.new_value1, source.new_value2);
2 . Using INSERT ON DUPLICATE KEY UPDATE (MySQL):
INSERT INTO table_name (column1, column2)
VALUES (value1, value2)
ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2;
3. Using INSERT ON CONFLICT DO UPDATE (PostgreSQL):
INSERT INTO table_name (column1, column2)
VALUES (value1, value2)
ON CONFLICT (column1)
DO UPDATE SET column2 = EXCLUDED.column2;
Examples of Upsert in SQL
Example 1: Upserting User Information
Step 1: Create the Users Table and Insert Initial Values
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100)
);
INSERT INTO users (user_id, username, email)
VALUES
(1, 'rohit', '[email protected]'),
(2, 'rohan', '[email protected]');
Output:
output of insertExplanation: The SQL code creates a table named "users" with columns for user ID, username, and email. It then inserts two rows of user data. The output confirms the successful insertion of the provided user information.
Step 2: Perform Upsert Operation
INSERT INTO users (user_id, username, email)
VALUES
(3, 'sumit', '[email protected]'),
(1, 'ayush', '[email protected]')
ON DUPLICATE KEY UPDATE
username = VALUES(username),
email = VALUES(email);
Output:
Output after UPSERT operationExplanation: The SQL statement inserts new user data into the "users" table. If a duplicate key conflict arises, it updates the existing record's username and email. The output confirms the successful insertion and potential updates.
Example 2: Upserting Product Prices
Step 1: Create the Users Table and Insert Initial Values
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL(10, 2)
);
INSERT INTO products (product_id, product_name, price)
VALUES
(101, 'Laptop', 1200.00),
(102, 'Smartphone', 800.00);
Output:
The output of insert operationExplanation: The SQL code creates a "products" table with columns for product ID, name, and price. It then inserts two rows of product data. The output confirms the successful creation and insertion of product information into the table.
Step 2: Perform Upsert Operation
INSERT INTO products (product_id, product_name, price)
VALUES
(103, 'Tablet', 500.00),
(102, 'Updated Smartphone', 850.00)
ON DUPLICATE KEY UPDATE
product_name = VALUES(product_name),
price = VALUES(price);
Output:
output after UPSERT operationExplanation: The SQL code inserts new product data into the "products" table. If a conflict arises due to duplicate keys, it updates the existing entry with the provided values for product name and price. The output confirms the successful insertion of new data and updates to existing records, ensuring data integrity.
Benefits of Upsert in SQL
Upsert in SQL is a combination of "insert" and "update" operations, enabling:
- Efficiency: Reduces the need for conditional checks before inserting or updating data.
- Simplicity: Streamlines data management by handling both insertion and updating in a single operation.
- Data Integrity: Helps maintain consistency by ensuring existing data is updated or new data is inserted appropriately.
- Concurrency: Facilitates concurrent access to data, minimizing conflicts in multi-user environments.
Conclusion
In conclusion, the upsert operation in SQL seamlessly combines insertion and updating, ensuring data consistency and efficiency. It allows for the insertion of new records or updates to existing ones based on specified conditions. By simplifying data management, upserts facilitate tasks such as synchronizing data across multiple sites and maintaining collaboration. This operation enhances data integrity and streamlines database operations for improved performance.
Similar Reads
How to Update All Rows in SQL?
Updating records in an SQL database is a fundamental operation used to modify existing data. The UPDATE command is the go-to method for making such modifications, whether for all rows in a table or a subset based on specific conditions. In this article, we will explain how to update all rows in SQL
4 min read
SQL | UPDATE with JOIN
In SQL, the UPDATE with JOIN statement is a powerful tool that allows updating one table using data from another table based on a specific JOIN condition. This technique is particularly useful when we need to synchronize data, merge records, or update specific columns in one table by referencing rel
4 min read
How to use Relational Operators in MySQL
In the database management area, relational operators are the building blocks for data filtering and querying. MySQL, one of the most popular relational database management systems that are widely used across the world, features a wide range of relational operators that are highly efficient in handl
6 min read
MySQL IN Operator
The MySQL IN operator is used to filter data based on a specified set of values. It is a shorthand for multiple OR conditions which allows us to specify a list of values in a WHERE clause to match records that have any of those values. This makes your SQL queries more concise and easier to read. MyS
3 min read
How to Use the IN Operator With a SubQuery?
The IN Operator in SQL allows to specifies multiple values in WHERE clause, it can help you to easily test if an expression matches any value in the list of values. The use of IN Operator reduces the need for multiple OR conditions in statements like SELECT, INSERT, UPDATE, and DELETE. Sub Queries:T
2 min read
How to Declare a Variable in SQL?
Variables in SQL are fundamental for building efficient and scalable database applications. They enhance the flexibility and efficiency of database queries by acting as placeholders for data. Understanding how to declare and use variables in SQL is crucial for writing dynamic and effective queries I
3 min read
How to Update Top 100 Records in SQL?
As our systems get more complex and complex, there is often a need to update the underlying data to accommodate the evolution of the system. SQL provides a variety of ways to update the data so that the system developer can manipulate the data in whatever way necessary. In this article, we will be l
5 min read
How to Update Top N Records in MySQL
MySQL is a free and open-source relational database management system written in C and C++ that is extremely popular among developers. Like other relational database management systems, MySQL provides a variety of rich features to create databases and tables, insert data in them, and further manipul
6 min read
MySQL UPDATE JOIN
A widely used open-source relational database management system that allows you to efficiently store, organize, and retrieve data. Developed by Oracle, My SQL is widely used for building and managing databases that handle interactive websites and applications. We'll discuss the syntax, and demonstra
6 min read
How UPDATE JOIN Works in PostgreSQL?
In PostgreSQL, updating records in one table based on values in another is a common scenario in relational databases. While PostgreSQL does not have a direct UPDATE JOIN syntax like other databases (e.g., MySQL). Hence, it provides a powerful alternative by using the FROM clause in the UPDATE statem
6 min read