Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite add Primary Key

Tags:

sqlite

I created a table in Sqlite by using the CREATE TABLE AS syntax to create a table based on a SELECT statement. Now this table has no primary key but I would like to add one.

Executing ALTER TABLE table_name ADD PRIMARY KEY(col1, col2,...) gives a syntax error "near PRIMARY"

Is there a way to add a primary key either during table creation or afterwards in Sqlite?

By "during creation" I mean during creation with CREATE TABLE AS.

like image 803
Jack Edmonds Avatar asked Jun 03 '09 17:06

Jack Edmonds


People also ask

How do I add a primary key to a column in SQLite?

Syntax. The syntax to add a primary key to a table in SQLite is: PRAGMA foreign_keys=off; BEGIN TRANSACTION; ALTER TABLE table_name RENAME TO old_table; CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL | NOT NULL ], ... CONSTRAINT constraint_name PRIMARY KEY (pk_col1, pk_col2, ...

Is there primary key in SQLite?

A primary key is a field in a table which uniquely identifies the each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.

Can we update primary key in SQLite?

Unless you can change the database structure you need to add the correct values in that other table to change your primary key value. That is "insert into table constraintingTable(key,val) values (A,B)" and then execute update tbl set a1 = A where a1 = KEY.


2 Answers

You can't modify SQLite tables in any significant way after they have been created. The accepted suggested solution is to create a new table with the correct requirements and copy your data into it, then drop the old table.

here is the official documentation about this: http://sqlite.org/faq.html#q11

like image 147
Nathan Ridley Avatar answered Oct 10 '22 05:10

Nathan Ridley


As long as you are using CREATE TABLE, if you are creating the primary key on a single field, you can use:

CREATE TABLE mytable ( field1 TEXT, field2 INTEGER PRIMARY KEY, field3 BLOB, ); 

With CREATE TABLE, you can also always use the following approach to create a primary key on one or multiple fields:

CREATE TABLE mytable ( field1 TEXT, field2 INTEGER, field3 BLOB, PRIMARY KEY (field2, field1) ); 

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

This answer does not address table alteration.

like image 41
Asclepius Avatar answered Oct 10 '22 07:10

Asclepius