Insert new column into table in sqlite?
I have a table with columns name
, qty
, rate
. Now I need to add a new column COLNew
in between the name
and qty
columns. How do I add a new column in between two columns?
Solution 1:
You have two options. First, you could simply add a new column with the following:
ALTER TABLE {tableName} ADD COLUMN COLNew {type};
Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:
ALTER TABLE {tableName} RENAME TO TempOldTable;
Then create the new table with the missing column:
CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);
And populate it with the old data:
INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;
Then delete the old table:
DROP TABLE TempOldTable;
I'd much prefer the second option, as it will allow you to completely rename everything if need be.
Solution 2:
You don't add columns between other columns in SQL, you just add them. Where they're put is totally up to the DBMS. The right place to ensure that columns come out in the correct order is when you select
them.
In other words, if you want them in the order {name,colnew,qty,rate}
, you use:
select name, colnew, qty, rate from ...
With SQLite, you need to use alter table
, an example being:
alter table mytable add column colnew char(50)
Solution 3:
You can add new column with the query
ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)
But it will be added at the end, not in between the existing columns.