Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Table Insert if not exist otherwise update

Tags:

mysql

insert

UPDATE AggregatedData SET datenum="734152.979166667",  Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667"; 

It works if the datenum exists, but I want to insert this data as a new row if the datenum does not exist.

UPDATE

the datenum is unique but that's not the primary key

like image 959
OHLÁLÁ Avatar asked May 17 '11 11:05

OHLÁLÁ


People also ask

Will MySQL 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.

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.

Can we use insert instead of update?

No. Insert will only create a new row.

How do I use Upsert in MySQL?

We can perform MySQL UPSERT operation mainly in three ways, which are as follows: UPSERT using INSERT IGNORE. UPSERT using REPLACE. UPSERT using INSERT ON DUPLICATE KEY UPDATE.


1 Answers

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp) VALUES ("734152.979166667","2010-01-14 23:30:00.000") ON DUPLICATE KEY UPDATE    Timestamp=VALUES(Timestamp) 
like image 174
Ike Walker Avatar answered Sep 17 '22 03:09

Ike Walker