Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite primary key on multiple columns

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

like image 295
Bogdan Gavril MSFT Avatar asked Apr 09 '09 15:04

Bogdan Gavril MSFT


People also ask

Can primary key be multiple columns?

Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

How do I make two columns a primary key in SQLite?

In SQLite, you can specify the primary key of a table on multiple table columns. Here is the generic syntax: CREATE TABLE table_name ( column1, column2, column3, PRIMARY KEY (column1, column2) );

Can SQLite have multiple primary keys?

A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields.

Can primary key have 3 columns?

Primary Key Declaration In a table, there can only be one primary key. A primary key can have one or as many columns as possible.


3 Answers

According to the documentation, it's

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);
like image 156
Brian Campbell Avatar answered Oct 20 '22 13:10

Brian Campbell


CREATE TABLE something (
  column1 INTEGER NOT NULL,
  column2 INTEGER NOT NULL,
  value,
  PRIMARY KEY ( column1, column2)
);
like image 180
xiwok Avatar answered Oct 20 '22 14:10

xiwok


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
like image 51
jsmarkus Avatar answered Oct 20 '22 14:10

jsmarkus