Sqlite primary key on multiple columns
Solution 1:
According to the documentation, it's
CREATE TABLE something (
column1,
column2,
column3,
PRIMARY KEY (column1, column2)
);
Solution 2:
CREATE TABLE something (
column1 INTEGER NOT NULL,
column2 INTEGER NOT NULL,
value,
PRIMARY KEY ( column1, column2)
);
Solution 3:
Yes. But remember that such primary key allow NULL
values in both columns multiple times.
Create a table as such:
sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));
Now this works without any warning:
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla
Solution 4:
Basic :
CREATE TABLE table1 (
columnA INTEGER NOT NULL,
columnB INTEGER NOT NULL,
PRIMARY KEY (columnA, columnB)
);
If your columns are foreign keys of other tables (common case) :
CREATE TABLE table1 (
table2_id INTEGER NOT NULL,
table3_id INTEGER NOT NULL,
FOREIGN KEY (table2_id) REFERENCES table2(id),
FOREIGN KEY (table3_id) REFERENCES table3(id),
PRIMARY KEY (table2_id, table3_id)
);
CREATE TABLE table2 (
id INTEGER NOT NULL,
PRIMARY KEY id
);
CREATE TABLE table3 (
id INTEGER NOT NULL,
PRIMARY KEY id
);
Solution 5:
Primary key fields should be declared as not null (this is non standard as the definition of a primary key is that it must be unique and not null). But below is a good practice for all multi-column primary keys in any DBMS.
create table foo
(
fooint integer not null
,foobar string not null
,fooval real
,primary key (fooint, foobar)
)
;