Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite3: how to reorder columns in a table?

Tags:

It seems that it is not straightforward for reordering columns in a sqlite3 table. At least the sqlite manager in firefox does not support this feature. For example, move the column2 to column3 and move column5 to column2. Is there a way to reorder columns in sqlite table, either with a sqlite management software or a script? Thanks.

like image 251
user938363 Avatar asked Dec 13 '13 19:12

user938363


People also ask

Does column order matter in SQLite?

No. This can make no possible difference.

How do I sort two columns in SQLite?

In case you want to sort the result set by multiple columns, you use a comma (,) to separate two columns. The ORDER BY clause sorts rows using columns or expressions from left to right. In other words, the ORDER BY clause sorts the rows using the first column in the list.

How do I reorder columns in SQL?

Using SQL Server Management StudioIn Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.


2 Answers

This isn't a trivial task in any DBMS. You would almost certainly have to create a new table with the order that you want, and move your data from one table to the order. There is no alter table statement to reorder the columns, so either in sqlite manager or any other place, you will not find a way of doing this in the same table.

If you really want to change the order, you could do:

Assuming you have tableA:

create table tableA( col1 int, col3 int, col2 int); 

You could create a tableB with the columns sorted the way you want:

create table tableB( col1 int, col2 int, col3 int); 

Then move the data to tableB from tableA:

insert into tableB SELECT col1,col2,col3  FROM tableA; 

Then remove the original tableA and rename tableB to TableA:

DROP table tableA; ALTER TABLE tableB RENAME TO tableA; 

sqlfiddle demo

like image 167
Filipe Silva Avatar answered Oct 04 '22 18:10

Filipe Silva


You can always order the columns however you want to in your SELECT statement, like this:

SELECT column1,column5,column2,column3,column4 FROM mytable WHERE ... 

You shouldn't need to "order" them in the table itself.

like image 39
BWS Avatar answered Oct 04 '22 19:10

BWS