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
.
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, ...
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With