Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite INSERT - ON DUPLICATE KEY UPDATE (UPSERT)

MySQL has something like this:

INSERT INTO visits (ip, hits) VALUES ('127.0.0.1', 1) ON DUPLICATE KEY UPDATE hits = hits + 1; 

As far as I know this feature doesn't exist in SQLite, what I want to know is if there is any way to achive the same effect without having to execute two queries. Also, if this is not possible, what do you prefer:

  1. SELECT + (INSERT or UPDATE) or
  2. UPDATE (+ INSERT if UPDATE fails)
like image 487
Alix Axel Avatar asked Apr 26 '10 23:04

Alix Axel


People also ask

Does SQLite support Upsert?

0 UPSERT is supported by SQLite. From the documentation: UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL.

Is INSERT on duplicate key update Atomic?

So yes it is atomic in the sense that if the data that you are trying to insert will cause a duplicate in the primary key or in the unique index, the statement will instead perform an update and not error out.

How does on duplicate key update work?

ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.

Is used to INSERT new rows into SQLite database tables?

SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.


2 Answers

INSERT OR IGNORE INTO visits VALUES ($ip, 0); UPDATE visits SET hits = hits + 1 WHERE ip LIKE $ip; 

This requires the "ip" column to have a UNIQUE (or PRIMARY KEY) constraint.


EDIT: Another great solution: https://stackoverflow.com/a/4330694/89771.

like image 88
dan04 Avatar answered Oct 21 '22 12:10

dan04


Since 3.24.0 SQLite also supports upsert, so now you can simply write the following

INSERT INTO visits (ip, hits) VALUES ('127.0.0.1', 1) ON CONFLICT(ip) DO UPDATE SET hits = hits + 1; 
like image 21
szmate1618 Avatar answered Oct 21 '22 12:10

szmate1618