SQLite add Primary Key

前端 未结 11 2488
你的背包
你的背包 2020-11-28 06:07

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 b

11条回答
  •  天命终不由人
    2020-11-28 06:42

    I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.

    In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).

    Suppose the table looks like:

    CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);
    

    Then I did the following:

    BEGIN;
    CREATE INDEX pk_tab1 ON tab1(i,j);
    pragma writable_schema=1;
    UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
    UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
    COMMIT;
    

    Some tests (in sqlite shell):

    sqlite> explain query plan select * from tab1 order by i,j;
    0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
    sqlite> drop index sqlite_autoindex_tab1_1;
    Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    
    

提交回复
热议问题