Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite - alter a table's column type?

I am starting a project involving a small database and I am considering to use SQLite. If I create a table and I defined one of the columns as text, but all the values stored are integers - is there a way to change the data type of a column? I am using SQLite Manager and I can't find a function that allows me to do that. Can I do it using a SQL command, or is it a restriction of SQLite? Probably, even with this restriction, one can find some way around and create a new table with the required column types and then import data into it.

Regards, Nick

like image 742
Nick_F Avatar asked Jan 18 '14 02:01

Nick_F


People also ask

Does ALTER TABLE work in SQLite?

Overview. SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows these alterations of an existing table: it can be renamed; a column can be renamed; a column can be added to it; or a column can be dropped from it.

How do I change a column constraint?

ALTER TABLE table_name MODIFY COLUMN column_name datatype; The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows. ALTER TABLE table_name MODIFY column_name datatype NOT NULL; The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.

How do I change the schema of 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

SQLite does not fully support ALTER TABLE statements. The only thing you can do is rename a table and/or add columns. If you want to rename a column, your best option is to create a new table with the new columns datatype/names, and to drop the old table in order to rename the new one.

Lets say, you have a table and need to rename "field-1" to "field-2": First ==>> rename the old table:

    ALTER TABLE original RENAME TO tmp; 

Now create the new table based on the old table but with the updated column name:
==>> create a table with the updated columns

    CREATE TABLE original(     field_a INT    , field_b INT     ); 

Then copy the contents across from the original table.

   INSERT INTO origignal(field_a, field_b)    SELECT field_a, field_b    FROM tmp; 

Lastly, drop the old table.

   DROP TABLE tmp; 
like image 171
z atef Avatar answered Oct 03 '22 01:10

z atef