Rename Column if Exists sqlite? Rename Column if Exists sqlite? sqlite sqlite

Rename Column if Exists sqlite?


As far as I know there is no way to do what you ask. However you can use

SELECT sql FROM sqlite_masterWHERE tbl_name = 'table_name' AND type = 'table'

to check whether the column exists or not. However since you just have to rename the column once I do not know what the issue is with the recreation of the table. Recreation does NOT mean data loss.

The procedure would be along the lines of:

  1. BEGIN TRANSACTION;
  2. ALTER TABLE table RENAME TO tmp_table;
  3. CREATE TABLE table (columnNames);
  4. INSERT INTO table(columnNames) SELECT columnNamesWrong FROM tmp_table;
  5. DROP TABLE tmp_table_name;
  6. COMMIT;

If this is to much fuss use a tool to do it.

About the best practice part, it is best practice to get your tables named properly. Since you usually build all your queries around the field names renaming columns means breaking those queries. I do not know what you are looking for but the sqlite manual states:

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

Note what is NOT possible.


It is actually possible to rename columns in SQLite:

  1. Read the table definition by executing this query:

    SELECT sql FROM sqlite_master WHERE type='table' AND name='MyTable'

    This will give you the entire CREATE TABLE statement.

    You then have to check, in your code, whether this table definition contains the old or the new column name.If it already has the new name, stop.If not, replace the old name with the new name.

  2. Execute the following magic command to allow changing the table definition:

    PRAGMA writable_schema = on
  3. Update that record in the sqlite_master table with the new table definition:

    UPDATE sqlite_master SET sql = ? WHERE type='table' AND name='MyTable'
  4. Switch the dangerous setting back:

    PRAGMA writable_schema = off

Please note that this is a very dangerous mechanism;SQLite uses the text in the sql column to determine how the data is stored in the database file, so changing almost anything except the column name will definitely result in a corrupted database.