SQL
Perform Upsert Operations (Insert or Update)
Learn how to perform an upsert (insert new data or update existing data) using SQL's `INSERT ... ON CONFLICT` statement, crucial for data synchronization.
INSERT INTO configurations (key_name, value, last_updated)
VALUES ('theme_color', '#336699', NOW())
ON CONFLICT (key_name) DO UPDATE SET
value = EXCLUDED.value,
last_updated = EXCLUDED.last_updated;
How it works: This query attempts to insert a new configuration record. If a record with the same `key_name` already exists (as defined by a unique constraint on `key_name`), it instead updates the `value` and `last_updated` columns of the existing record with the new values. `EXCLUDED` refers to the values that would have been inserted had there been no conflict. This pattern is commonly known as "upsert" (update or insert).