Search code examples
sqlsqlitesqflite

SQLite - add a column if it does not exist


I am new to SQLite. I want to add a column if it does not exist.

How to check if the column name exists and then add if it does not?

I tried

ALTER TABLE table ADD COLUMN colname INTEGER ON CONFLICT IGNORE

But it shows an error

Result: near "ON": syntax error

Any advice how it can be achieved?

Thanks in advance.


Solution

  • First get a list of table column names - as list - with something like:

    select group_concat(c.name) from pragma_table_info('table_name') c;
    

    Then do a CASE expression on whether the new column name you want to add exists in the list above. More info at: https://www.sqlite.org/lang_expr.html