WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MySQL · Intermediate · question 37 of 100

What is an upsert operation, and how do you perform it using the INSERT ... ON DUPLICATE KEY UPDATE statement in MySQL?

📕 Buy this interview preparation book: 100 MySQL questions & answers — PDF + EPUB for $5

An upsert operation, also known as a merge operation, combines insert and update operations into a single statement. An upsert operation is used when you want to insert a row into a table if it does not exist, or perform an update on the row if it already exists.

In MySQL, you can perform an upsert operation using the ‘INSERT ... ON DUPLICATE KEY UPDATE‘ statement. This statement works by specifying the columns to be inserted, followed by the keyword ‘VALUES‘, which contains the values to be inserted. If there is a conflict with an existing row, the ‘ON DUPLICATE KEY UPDATE‘ clause is executed, updating the existing row.

Here is an example of using the ‘INSERT ... ON DUPLICATE KEY UPDATE‘ statement to perform an upsert operation in MySQL:

Suppose we have a table named ‘users‘ with columns ‘id‘, ‘name‘, and ‘email‘. We want to insert a new user record if the ‘id‘ does not exist in the table or update the ‘name‘ and ‘email‘ columns if the ‘id‘ already exists.

INSERT INTO users (id, name, email)
VALUES (1, 'John Smith', 'john.smith@example.com')
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    email = VALUES(email);

In this statement, we first specify the columns to be inserted (‘id‘, ‘name‘, and ‘email‘) followed by the ‘VALUES‘ keyword, which contains the values to be inserted (‘1‘, ‘’John Smith’‘, and ‘’john.smith@example.com’‘).

If the ‘id‘ already exists in the ‘users‘ table, the ‘ON DUPLICATE KEY UPDATE‘ clause is executed, updating the ‘name‘ and ‘email‘ columns with the values specified in the ‘VALUES‘ clause. The ‘VALUES()‘ function is used to reference the values originally intended to be inserted.

Note that for this upsert operation to work, the ‘id‘ column must be defined as a unique key or primary key in the ‘users‘ table.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MySQL interview — then scores it.
📞 Practice MySQL — free 15 min
📕 Buy this interview preparation book: 100 MySQL questions & answers — PDF + EPUB for $5

All 100 MySQL questions · All topics