Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite: possible to update row or insert if it doesn't exist?

Tags:

sqlite

I'm sure I can check if a row exists by selecting it but I'm wondering if there's a slicker way that I'm just not aware of -- seems like a common enough task that there might be. This SQLite table looks something like this:

rowID  QID    ANID  value
------ ------ ----- ------
0      axo    1     45
1      axo    2     12

If the combination of QID and ANID already exists, that value should be updated, if the combination of QID and ANID doesn't already exist then it should be inserted. While its simple enough to write:

SELECT * where QID = 'axo' and ANID = 3;

And check if the row exists then branch and either insert/update I can't help but look for a better way. Thanks in advance!

like image 640
Will Avatar asked Aug 16 '10 20:08

Will


1 Answers

Beware: REPLACE doesn't really equal 'UPDATE OR INSERT'...REPLACE replaces the entire row. Therefore if you don't specify values for EVERY column, you'll replace the un-specified columns with NULL or the default values.

In a simple example such as above, it's likely fine, but if you get into the habit of using REPLACE as 'UPDATE OR INSERT' you'll nuke data when you forget to specify a value for every field...just a warning from experience.

like image 163
Dale Avatar answered Oct 26 '22 13:10

Dale