SQL
Performing Upsert Operations in SQL (INSERT OR UPDATE)
Master SQL upsert operations to either insert new records or update existing ones, preventing duplicate entries and ensuring data integrity in your database.
INSERT INTO users (email, username, last_login) VALUES ('[email protected]', 'testuser', NOW())
ON CONFLICT (email) DO UPDATE SET
username = EXCLUDED.username,
last_login = EXCLUDED.last_login;
How it works: This code snippet illustrates an 'upsert' operation, which is an 'INSERT' that on conflict ('ON CONFLICT') will instead perform an 'UPDATE'. It attempts to insert a new user. If a user with the same `email` already exists (due to a unique constraint on the email column), it updates their `username` and `last_login` fields. `EXCLUDED` refers to the row that would have been inserted, providing a way to use its values in the update.