Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

Tags:

sqlite

upsert

I've never seen the syntax INSERT OR REPLACE INTO names (id, name) VALUES (1, "John") used in SQL before, and I was wondering why it's better than UPDATE names SET name = "John" WHERE id = 1. Is there any good reason to use one over the other. Is this syntax specific to SQLite?

like image 709
nevan king Avatar asked Feb 12 '10 12:02

nevan king


People also ask

Does SQLite have Upsert?

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. UPSERT in SQLite follows the syntax established by PostgreSQL. UPSERT syntax was added to SQLite with version 3.24.

Which method is used to insert update and modify data in SQLite?

The data modification clauses in SQLite are INSERT, UPDATE, and DELETE statements. It is used for inserting new rows, updating existing values, or deleting rows from the database.

What does insert or ignore do SQLite?

The INSERT OR IGNORE INTO statement ignores the error message. The SELECT statement shows that the last two statements did not modify the fourth row. Since SQLite version 3.7. 11 it is possible to insert multiple rows using one INSERT statement.

What does SQLite update return?

Returns the current database page size, in bytes.


2 Answers

UPDATE will not do anything if the row does not exist.

Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.

like image 84
Adriaan Stander Avatar answered Sep 21 '22 17:09

Adriaan Stander


I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

like image 34
cybergen Avatar answered Sep 18 '22 17:09

cybergen