0

I want to add this into SQLite, but I can't get alter table to work with add foreign key. It looks like this:

create table Medlem
(Mnr integer not null,
Namn varchar(6),
Telefon varchar(10),
primary key (Mnr));

create table Sektion
(Skod char(1) not null,
Namn varchar(14),
Ledare integer,
primary key (Skod));

create table Deltar
(Medlem integer not null,
Sektion char(1) not null,
primary key (Medlem, Sektion));

alter table Sektion
add foreign key (Ledare) references Medlem (Mnr);
alter table Deltar
add foreign key (Medlem) references Medlem (Mnr);
alter table Deltar
add foreign key (Sektion) references Sektion (Skod);

4
  • What error do you get? Commented Mar 13, 2013 at 16:50
  • I get syntax error for "foreign". Commented Mar 13, 2013 at 16:51
  • Do you have foreign key support enabled? (see sqlite.org/foreignkeys.html) Commented Mar 13, 2013 at 17:11
  • @Raad A CREATE TABLE command operates the same whether or not foreign key constraints are enabled Commented Mar 13, 2013 at 17:13

1 Answer 1

2

The only way to implement a foreign key constraint in SQL Lite is during CREATE TABLE:

CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);

It is not possible to use the ALTER TABLE ... ADD COLUMN syntax to add a column that includes a REFERENCES clause, unless the default value of the new column is NULL. Attempting to do so returns an error.

Documentation

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

1 Comment

Thank you, I think I got it now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.