Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does referencing a SQLite rowid cause foreign key mismatch?

SQLite version 3.7.9 2011-11-01 00:52:41
sqlite> PRAGMA foreign_keys = 1;
sqlite> CREATE TABLE foo(name);
sqlite> CREATE TABLE bar(foo_rowid REFERENCES foo(rowid));
sqlite> INSERT INTO foo VALUES('baz');
sqlite> SELECT rowid, name FROM foo;
1|baz
sqlite> INSERT INTO bar (foo_rowid) VALUES (1);
Error: foreign key mismatch

Why does this error occur? It is a DML error, but I don't know what's wrong because:

  • foo exists.
  • foo.rowid exists.
  • foo.rowid is the primary key of foo and therefore constrained to uniqueness.
  • bar.foo_rowid is one column, which matches the fact that foo.rowid is one column.
like image 981
Jordan Avatar asked Jun 08 '13 17:06

Jordan


People also ask

Does Rowid change in SQLite?

A rowid is assigned to a row upon insert and is imutable (never changing) unless the row is deleted and re-inserted (meaning it is another row, not the same row!)

Does SQLite support foreign keys True or false?

SQLite foreign key constraint supportSQLite has supported foreign key constraint since version 3.6.

What does foreign key mismatch mean?

The error message "foreign key mismatch" does not indicate a constraint violation, but that your database schema is wrong.


2 Answers

SQLite documentation is quite clear on foreign keys:

The parent key must be a named column or columns in the parent table, not the rowid.

(See here.)

You can't use rowid for this, so just define your own auto incrementing primary key for the table.

like image 108
Gordon Linoff Avatar answered Oct 04 '22 15:10

Gordon Linoff


You can not use rowid if not defined in your table, but if you define it as follows:

CREATE TABLE IF NOT EXISTS Clase(
ROWID INTEGER NOT NULL,
nombre  VARCHAR(50) NOT NULL,
PRIMARY KEY(ROWID));

The ROWID column can be used to make foreign references, and when you insert a record into the table, the ROWID column behaves like an autoincrement field, it is why that sqlite recommended don't have autoincrement fields.

Note: The ROWID column can be called otherwise only it has to be of type INTEGER and primary key of the table.

like image 23
Ivan Avatar answered Oct 04 '22 15:10

Ivan