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:
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.
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.
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.
SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With