Adding a Primary Key Column in SQLite

The Android platform utilizes the functionality of SQLite databases.  This is extremely useful for data driven apps.  There is one problem that I came across in developing apps, and that is that SQLite does not allow you to add a primary key column to an existing table.

After looking at this tutorial, I derived a way for adding a primary key column to an existing table by creating two temporary tables, and joining the data back together into the final table.

CREATE TABLE KEYTEMP (ID INTEGER PRIMARY KEY AUTOINCREMENT, @UNIQUEFIELD DATETIME)
INSERT INTO KEYTEMP (@UNIQUEFIELD) SELECT @UNIQUEFIELD FROM @TABLENAME
CREATE TABLE DATATEMP AS SELECT KEYTEMP.ID, @TABLENAME.* FROM @TABLENAME INNER JOIN KEYTEMP ON KEYTEMP.@UNIQUEFIELD=@TABLENAME.@UNIQUEFIELD
DROP TABLE @TABLENAME
CREATE TABLE @TABLENAME AS SELECT * FROM DATATEMP
DROP TABLE DATATEMP
DROP TABLE KEYTEMP

In the code above, you will need to replace @TABLENAME with the name of your existing table, and replace @UNIQUEFIELD with the name of an existing column in your database that contains unique values in each row.  If you want to be safe, you can remove the line “DROP TABLE DATATEMP” to preserve a copy of your original table in case of problems.