43

I know that SQLite does not enforce foreign keys natively, but that's not my primary concern. The question is: If I declare

CREATE TABLE invoice ( invoiceID INTEGER PRIMARY KEY, clientID INTEGER REFERENCES client(clientID), ... ) 

will sqlite at least use the information that clientID is a foreign key to optimize queries and automatically index invoice.clientID, or is this constraint a real no-op?

1
  • SQLite does enforce foreign keys, and it can do so without an index Commented Jun 3, 2023 at 13:58

2 Answers 2

56

In the SQLite Documentation it says:

... "an index should be created on the child key columns of each foreign key constraint"

ie. the index is not automatically created, but you should create one in every instance.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm not sure why they say this. Surely it depends how you are using the child table? For example, if you only search the child table (some other column) and then use the child column (of foreign key) to lookup parent table.
@Mark They explain it: each time an application deletes a row from the artist table (the parent table), it performs the equivalent of the following SELECT statement to search for referencing rows in the track table (the child table).
@jwalker that's true, but what if you are not deleting from the parent table?
@Mark Then you don't have to create it, but then again, it won't hurt to have it in case you ever start deleting
it's updates as well as deletes
52

Even if it is not actually a no-op (a data structure describing the constraint is added to the table), foreign key related statement doesn't create any index on involved columns. Indexes are implicitly created only in the case of PRIMARY KEY and UNIQUE statements. For more details, check it out build.c module on the sqlite source tree: http://www.sqlite.org/cvstrac/rlog?f=sqlite/src/build.c https://www.sqlite.org/src/file?name=src/build.c&ci=tip

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.