2

I found this post explaining the difference between UPDATE and "INSERT OR REPLACE INTO". It explains that

INSERT OR REPLACE INTO names (id, name) VALUES (1, "John")

will insert a new row if no record with id =1 exists, and will replace the row with id = 1 if it does exist. My question is: how does SQLite know or decide that 'id' is the field whose values determine if records already exist or not?

In other words, why wouldn't sqlite search for a record with name = "John" and replace the id value? Does this depend on an index that's not being talked about in the above example, or does SQLite give special treatment to fields named 'id' or fields named first in a row of field names?

Community
  • 1
  • 1
Wytze
  • 7,844
  • 8
  • 49
  • 62

1 Answers1

4

See the CONFLICT clause documentation for how this is dealt with. Essentially, it is based on UNIQUE and NOT NULL constraints (primary keys being rather usual as a constraint to select whether to update or insert).

When a UNIQUE constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting or updating the current row and the command continues executing normally. If a NOT NULL constraint violation occurs, the REPLACE conflict resolution replaces the NULL value with he default value for that column, or if the column has no default value, then the ABORT algorithm is used. If a CHECK constraint violation occurs, the REPLACE conflict resolution algorithm always works like ABORT.

When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

The update hook is not invoked for rows that are deleted by the REPLACE conflict resolution strategy. Nor does REPLACE increment the change counter. The exceptional behaviors defined in this paragraph might change in a future release.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
  • 3
    Okay, so SQLite doesn't use any column to select specific rows that it will try to update. It simply tries to add a record, and if that fails because of a constraint then it will try to update whatever record is causing the constraint to kick in. – Wytze Sep 11 '12 at 10:00