views:

6192

answers:

3

What is the syntax for specifying a primary key on more than 1 column in SQLITE ?

+13  A: 

According to the documentation, it's

CREATE TABLE something (column1, column2, PRIMARY KEY (column1, column2));
Brian Campbell
Brian: see the edit summary if you are wondering why I revised.
TheTXI
@TheTXI No problem. Didn't mean to be condescending, but I see how it could sound that way, so thanks for the edit.
Brian Campbell
+3  A: 

I don't have karma to edit yet, but the documentation link in the answer above returned 404.

On inspection, the link above is correct, but Stack Overflow replaces the _ with %5F which breaks sqlite.org somehow. The link below appears to work.

http://www.sqlite.org/lang_createtable.html

Carl Coryell-Martin
It worked when I tested it…
Donal Fellows
A: 

Yes. But remember that such primary key allows to have 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> 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
NULL|NULL|bla-bla
NULL|NULL|bla-bla
Nixmrak