25
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.
Jordan
  • 4,510
  • 7
  • 34
  • 42

2 Answers2

34

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 4
    And it's even possible to name that PK `rowid`. – CL. Jun 08 '13 at 21:04
  • 1
    I have an error saying: _foreign key mismatch - "child_table" referencing "parent_table"_ . I did what u said but still not working .. – McLan Aug 20 '13 at 13:57
  • 4
    On the other hand, `If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID.` from https://www.sqlite.org/autoinc.html – Nils Guillermin Jun 13 '15 at 02:10
8

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.

Ivan
  • 81
  • 1
  • 2