Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create if an entry doesn't exist, otherwise update?

Tags:

php

mysql

Kinda strange to put it into words that short, heh.

Anyway, what I want is basically to update an entry in a table if it does exist, otherwise to create a new one filling it with the same data.

I know that's easy, but I'm relatively new to MySQL in terms of how much I've used it :P

like image 439
unrelativity Avatar asked Mar 30 '09 06:03

unrelativity


People also ask

What happens if you update a record that doesn't exist SQL?

Update won't insert records if they don't exist, it will only update existing records in the table.

Does update insert if not exists?

Often you have the situation that you need to check if an table entry exists, before you can make an update. If it does not exist, you have to do an insert first. Unfortunately, this the 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns.

How do you insert a new record in a table if not exists?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

Which command insert rows that do not exist and update the rows that exist?

The alternative (and generally preferred) method for INSERTING into rows that may contain duplicate UNIQUE or PRIMARY KEY values is to use the INSERT ... ON DUPLICATE KEY UPDATE statement and clause.


1 Answers

A lot of developers still execute a query to check if a field is present in a table and then execute an insert or update query according to the result of the first query. Try using the ON DUPLICATE KEY syntax, this is a lot faster and better then executing 2 queries. More info can be found here

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;

if you want to keep the same value for c you can do an update with the same value

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=6;

the difference between 'replace' and 'on duplicate key':

replace: inserts, or deletes and inserts

on duplicate key: inserts or updates

if your table doesn't have a primary key or unique key, the replace doesn't make any sense.

You can also use the VALUES function to avoid having to specify the actual values twice. E.g. instead of

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=6;

you can use

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(c);

Where VALUES(c) will evaluate to the value specified prevously (6).

like image 126
Kennethvr Avatar answered Sep 24 '22 10:09

Kennethvr