Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the primary key of a table in SQLite

I have the following table:

[id,lang,data]

Where the primary key is id

I want to change the primary key to id,lang without losing the content of the table. What is the query I must run to change it

Thanks

like image 294
Addev Avatar asked Jun 03 '13 15:06

Addev


1 Answers

As per the comment by @GarnerJosh, you can't run a single command to change it - SQLite doesn't permit changing existing table structures. Instead, create a new table with a composite primary key and copy the data over:

CREATE TABLE my_table_copy( 
    id INTEGER, 
    lang INTEGER,
    data TEXT,
    PRIMARY KEY (id, lang)
);
INSERT INTO my_table_copy (id, lang, data)
   SELECT id, lang, data FROM my_table;
DROP TABLE my_table;
ALTER TABLE my_table_copy RENAME TO my_table;
like image 148
PinnyM Avatar answered Oct 27 '22 06:10

PinnyM