Upsert SQL

Galaxy Glossary

How can I efficiently insert or update a row in a table based on whether it already exists?

Upsert is a SQL operation that combines INSERT and UPDATE statements into a single operation. It's useful for handling situations where you need to add a new row if it doesn't exist or update an existing one if it does.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

In database management, you often encounter scenarios where you need to add a new record to a table if it doesn't already exist, or update an existing record if it does. Performing these actions separately can be inefficient and prone to errors, especially in concurrent environments. The upsert operation addresses this by combining both INSERT and UPDATE statements into a single, atomic operation. This ensures data consistency and avoids potential conflicts. Upsert is particularly valuable when dealing with data synchronization or when ensuring data integrity across multiple systems. It's a powerful tool for maintaining data accuracy and consistency in your database applications. The exact syntax for upsert varies slightly across different database systems, but the fundamental concept remains the same.

Why Upsert SQL is important

Upsert operations are crucial for maintaining data integrity and consistency in applications. They streamline data synchronization and reduce the risk of errors associated with separate INSERT and UPDATE statements. This is especially important in high-volume, concurrent environments where multiple processes might try to modify the same data.

Example Usage


-- Create a sample table
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255)
);

-- Insert or update a user
INSERT INTO users (id, name, email)
VALUES (1, 'John Doe', 'john.doe@example.com')
ON DUPLICATE KEY UPDATE name = VALUES(name), email = VALUES(email);

-- Check the result
SELECT * FROM users WHERE id = 1;

-- Insert a new user
INSERT INTO users (id, name, email)
VALUES (2, 'Jane Doe', 'jane.doe@example.com')
ON DUPLICATE KEY UPDATE name = VALUES(name), email = VALUES(email);

-- Check the result
SELECT * FROM users WHERE id = 2;

-- Attempt to insert a duplicate user
INSERT INTO users (id, name, email)
VALUES (1, 'New John Doe', 'new.john.doe@example.com')
ON DUPLICATE KEY UPDATE name = VALUES(name), email = VALUES(email);

-- Check the result
SELECT * FROM users WHERE id = 1;

Common Mistakes

Want to learn about other SQL terms?