views:

35

answers:

2

How can I implement a foreign key in SQLite? I was thinking something like this:

CREATE TABLE job (_id INTEGER PRIMARY KEY AUTOINCREMENT, employer_id INTEGER, ...);
CREATE TABLE employer(_id INTEGER, employer_name TEXT NOT NULL, ...);

Where employer_id is the _id from the table employer. Would this work? Is there another fast, maybe less prone to error way? Maybe with triggers?

+2  A: 

Maybe I don't understand the question, but if it's the constraint you want, just do this:

ALTER TABLE Job
  ADD FOREIGN KEY (employer_id)
    REFERENCES Employer(_id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;
Willem van Rumpt
Is that legal SQLite code? I thought SQLite doesn't support foreign keys constraints?
Mohit Deshpande
@Mohit Deshpande: At least SQLite3 does, I don't know about earlier versions.
Willem van Rumpt
@Mohit: I was suprised too, but SQLite has foreign key support see http://www.sqlite.org/foreignkeys.html
Lars
@Mohit: If you're using SQLite 3.6.19 or later, foreign keys are supported. See http://www.hwaci.com/sw/sqlite/foreignkeys.html for details and how to enable it.
Nicholas Knight
A: 

SQLite (3.6.19) Foreign Key Support

pst