SQLite - Rename a column in a table
by
Jeremy Canfield |
Updated: July 04 2023
| SQLite articles
The .schema command can be used to list the columns in a table. In this example, the columns in the users table in example.db are listed.
~]$ 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)
);
Or like this, as a oneliner command.
~]$ sqlite3 /path/to/example.db ".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)
);
The sqlite3 command can be used to list the version of SQLite.
~]$ sqlite3
SQLite version 3.7.17 2013-05-20 00:56:22
If running SQLite version 3.25.0 of higher, the alter table <tablename> rename column <current column name> to <new column name> command can be used to rename a column in a table.
~]$ sqlite3 /path/to/example.db "ALTER TABLE users RENAME COLUMN email TO email_address"
If below SQLite version 3.25.0, you will need to.
- Begin a transaction
- Create a temp table
- Copy records from the table to the temp table
- Drop the original table
- Rename the temp table
- Commit
First, begin a new transaction.
~]$ sqlite3 /path/to/example.db "BEGIN TRANSACTION"
Create a temporary table, where the temp table has the new column name.
~]$ sqlite3 /path/to/example.db "CREATE TABLE userstmp (id INTEGER NOT NULL, date_created DATETIME,email_address VARCHAR(100) NOT NULL,password VARCHAR(200) NOT NULL,PRIMARY KEY (id),UNIQUE (id),UNIQUE (email));
Copy the records from the original table into the temp table.
~]$ sqlite3 /path/to/example.db "INSERT INTO userstmp (date_created, email_address) SELECT date_created, email FROM users"
Drop the original table.
~]$ sqlite3 /path/to/example.db "DROP TABLE users"
Rename the temp table.
~]$ sqlite3 /path/to/example.db "ALTER TABLE userstmp RENAME users"
And finally, commit.
~]$ sqlite3 /path/to/example.db "COMMIT"
Did you find this article helpful?
If so, consider buying me a coffee over at