Bootstrap FreeKB - SQLite - Add a new column to a table
SQLite - Add a new column to a table

Updated:   |  SQLite articles

alter table can be used to add a column to a table.The .schema command can be used to list the columns in a table.

~]$ sqlite3 /path/to/example.db
SQLite version 3.34.1 2021-01-20 14:10:07
Enter ".help" for usage hints.

sqlite> .schema users
CREATE TABLE users (
        id INTEGER NOT NULL,
        date_created DATETIME,
        email VARCHAR(100) NOT NULL,
        password VARCHAR(200) NOT NULL,
        PRIMARY KEY (id),
        UNIQUE (id),
        UNIQUE (email)
);

 

Here is an example of how to add a column to the table.

AVOID TROUBLE

If you want to set the column as NOT NULL make sure to include a default value such as DEFAULT 1

sqlite> ALTER TABLE users ADD COLUMN new_column VARCHAR(100) NOT NULL DEFAULT 1;

 

Or like this, as a oneliner command.

~]$ sqlite3 /path/to/example.db "ALTER TABLE users ADD COLUMN new_column VARCHAR(100) NOT NULL DEFAULT 1"

 

Then you'll probably want to update the value to the newly added column.

sqlite> UPDATE users SET new_column = 'foo' WHERE id = '1';
sqlite> UPDATE users SET new_column = 'bar' WHERE id = '2';

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 70184c in the box below so that we can be sure you are a human.