Bootstrap FreeKB - SQLite - Rename a column in a table
SQLite - Rename a column in a table

Updated:   |  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.

  1. Begin a transaction
  2. Create a temp table
  3. Copy records from the table to the temp table
  4. Drop the original table
  5. Rename the temp table
  6. 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 Buy Me A Coffee



Comments


Add a Comment


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