Although I am using mySQL (for now), I dont want any DB specific SQL.
I am trying to insert a record if it doesn’t exist, and update a field if it does exist. I want to use ANSI SQL.
The table looks something like this:
create table test_table (id int, name varchar(16), weight double) ;
//test data
insert into test_table (id, name, weight) values(1,'homer', 900);
insert into test_table (id, name, weight) values(2,'marge', 85);
insert into test_table (id, name, weight) values(3,'bart', 25);
insert into test_table (id, name, weight) values(4,'lisa', 15);
If the record exists, I want to update the weight (increase by say 10)
For a long time this operation required two separate commands plus some framework to handle it. Hence the name UPSERT (UPdate or inSERT). But more recent versions of some flavours of DBMS support more elegant solutions.
The ANSI standard defines a MERGE syntax. This has been supported in Oracle since version 9i and in MS SQL Server since 2005. MERGE statements can be somewhat verbose.
I think the MERGE statement was primarily envisaged as a data migration tool, so its syntax demands that we select data from a table, in the USING clause. we can get around this limitation by selecting literals and pseudo-columns from a row-generating device (such as dual in Oracle).
MySQL has a sightly different syntax, INSERT … ON DUPLICATE KEY UPDATE.