I need to make an sql query which tries to update a row by primary key and if it doesn’t exist insert it. The solution needs to be universal for most databases (MySQL, H2, Postgres, Oracle, DB2, MSSQL, Hsql, Derby).
For code examples please consider a simple table consisting of two columns: id (Pr.Key) and txt
You want SQL’s
MERGEstatement, but it doesn’t work everywhere:The other solution is to try and insert anyway, handle the error, detect whether it is a constraint violation and if so update instead.