Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

We've recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has already been altered, we want to leave it alone. Unfortunately, SQLite doesn't support an IF NOT EXISTS clause on ALTER TABLE.

Our current workaround is to execute the ALTER TABLE statement and ignore any "duplicate column name" errors, just like this Python example (but in C++).

However, our usual approach to setting up database schemas is to have a .sql script containing CREATE TABLE IF NOT EXISTS and CREATE INDEX IF NOT EXISTS statements, which can be executed using sqlite3_exec or the sqlite3 command-line tool. We can't put ALTER TABLE in these script files because if that statement fails, anything after it won't be executed.

I want to have the table definitions in one place and not split between .sql and .cpp files. Is there a way to write a workaround to ALTER TABLE ADD COLUMN IF NOT EXISTS in pure SQLite SQL?

like image 994
dan04 Avatar asked Aug 30 '10 21:08

dan04


People also ask

How do I add a column to a table in SQLite?

Syntax. The syntax to ADD A COLUMN in a table in SQLite (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition; table_name.

How do I add multiple columns in SQLite?

SQLite does not support adding multiple columns to a table using a single statement. To add multiple columns to a table, you must execute multiple ALTER TABLE ADD COLUMN statements.

How do I edit a table in SQLite?

Summary. Use the ALTER TABLE statement to modify the structure of an existing table. Use ALTER TABLE table_name RENAME TO new_name statement to rename a table. Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table.


1 Answers

I have a 99% pure SQL method. The idea is to version your schema. You can do this in two ways:

  • Use the 'user_version' pragma command (PRAGMA user_version) to store an incremental number for your database schema version.

  • Store your version number in your own defined table.

In this way, when the software is started, it can check the database schema and, if needed, run your ALTER TABLE query, then increment the stored version. This is by far better than attempting various updates "blind", especially if your database grows and changes a few times over the years.

like image 87
MPelletier Avatar answered Sep 23 '22 06:09

MPelletier