We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL intermediate

How to Perform Upsert Operations in SQL?

Upsert operations allow you to insert a new row or update an existing one seamlessly, ensuring data integrity and efficiency.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Insert a row if it doesn't exist, or update it if it does, using INSERT ON CONFLICT (PostgreSQL) or REPLACE INTO (MySQL)"

SQL
INSERT INTO table_name (column1, column2) VALUES (value1, value2) ON CONFLICT (unique_column) DO UPDATE SET column1 = excluded.column1; -- PostgreSQL

This SQL command inserts a new row or updates an existing row based on a unique constraint.

Step-by-step breakdown

  1. Identify the target table and columns for insertion.
  2. Specify the values to be inserted into the columns.
  3. Define the unique constraint that triggers the update.
  4. Use the DO UPDATE clause to specify how to update existing rows.

Edge cases & warnings

  • Trying to upsert with null values in unique columns.
  • Conflicting unique constraints on multiple columns.
  • Inserting/updating with data types that do not match the column types.

Examples

Prompt

"INSERT INTO users (id, name) VALUES (1, 'Alice') ON CONFLICT (id) DO UPDATE SET name = 'Alice Updated';"

SQL
Inserts Alice if id 1 does not exist, otherwise updates her name.
Prompt

"REPLACE INTO products (id, price) VALUES (2, 19.99);"

SQL
Inserts a new product with id 2 or updates the price if it already exists.

Frequently asked questions

What is the difference between INSERT and REPLACE?

INSERT adds a new row, while REPLACE deletes the existing row with the same primary key before inserting.

Can I use upsert with multiple columns?

Yes, you can specify multiple columns in the unique constraint for upsert operations.

What happens if the upsert fails?

If the upsert fails due to a constraint violation, an error will be raised and no changes will be made.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.