5

I want to update a row if it exists in the table else insert it in SQLite in single query. From SQLite documentation I found out that we can use REPLACE command for achieving this.

I want to know how to use REPLACE if there are two or more conditions:

Example:
If I have table TABLE1 with following records:

  Name   Type   InitialValue  FinalValue
   A      1          20           40
   B      2          23           50
   A      3          40           60
   C      3          54           70 

Here Combination of Name and Type will be unique.

I want to set initialvalue = 50 and finalvalue = 90 where name = A and Type = 3 if it exists, else insert it.

I am using this command but it's giving this error:

REPLACE INTO table1 (Name,Type,InitialValue,FinalValue) VALUES ('A',3,50,90 ) WHERE Name='A' AND Type = 3 ;

Error is:

near "WHERE": syntax error Unable to execute statement

How can I achieve my objective? Please help.

Sam R.
  • 16,027
  • 12
  • 69
  • 122
Maverick
  • 3,053
  • 6
  • 24
  • 30

1 Answers1

7

replace is just like insert, it just checks if there is duplicate key and if it is it deletes the row, and inserts the new one, otherwise it just inserts

you can do this if there is for example unique index of (Name,Type) and if you type the following command

REPLACE INTO table1 (Name,Type,InitialValue,FinalValue) VALUES ('A',3,50,90 )

and there already exists a row with Name = 'A' and Type = 3 it will be replaced

http://www.sqlite.org/lang_createindex.html

CREATE UNIQUE INDEX idx_name_type ON table1(Name,Type)

EDIT: a quick note - REPLACE always DELETES and then INSERTs, so it is never a very good idea to use it in heavy load because it needs exclusive lock when it deletes, and then when it inserts

some of the database engines have

INSERT ... ON DUPLICATE KEY UPDATE ...

sqlite 3 does not, but you can do try {} catch if insert fails

http://blog.client9.com/2007/11/sqlite3-and-on-duplicate-key-update.html

SQLite UPSERT - ON DUPLICATE KEY UPDATE

Community
  • 1
  • 1
jackdoe
  • 1,846
  • 1
  • 15
  • 13
  • ..I have used your above query REPLACE INTO test (Name,Type,InitialValue,FinalValue) VALUES ('A',3,50,90 ); but it is inserting in the table but not updating.. – Maverick Dec 07 '11 at 06:12
  • Does this mean that it's just as fast if I do DELETE then INSERT? – sudo Jun 04 '14 at 02:36
  • but without any "into table"? i just want replace all "word1" to "word2" in all tables? – user25 Jul 16 '16 at 16:54