Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an entire SQLite table

Tags:

sorting

sqlite

I have an SQLite table that I need to sort. I am familiar with the ORDER BY command but this is not what I am trying to accomplish. I need the entire table sorted within the database.

Explanation:

My table uses a column called rowed which sets the order of the table (a key?). I need to sort the table by another column called name and then re-assign rowid numbers in alphabetical order according to name. Can this be done?

like image 952
Kyle Mills Avatar asked Dec 31 '10 04:12

Kyle Mills


People also ask

How do I sort a table in SQLite?

Use the ORDER BY keyword and the name of the column by which you want to sort. This way, you'll sort the data in ascending order by this column. You could also use the ASC keyword to make it clear that the order is ascending (the earliest date is shown first, the latest date is shown last, etc.).

What is collate in SQLite?

Collating sequences are used by SQLite when comparing TEXT values to determine order and equality. You can specify which collation to use when creating columns or per-operation in SQL queries. SQLite includes three collating sequences by default.

How do I sort SQLite data in Python?

You can sort the results in desired order (ascending or descending) using the Order By clause. By default, this clause sorts results in ascending order, if you need to arrange them in descending order you need to use “DESC” explicitly.


2 Answers

Assuming you created your original table like so:

CREATE TABLE my_table (rowid INTEGER PRIMARY KEY, name TEXT, somedata TEXT) ;

You can create another sorted table like so:

CREATE TABLE my_ordered_table (rowid INTEGER PRIMARY KEY, name TEXT, somedata TEXT) ;
INSERT INTO my_ordered_table (name, somedata) SELECT name,somedata FROM my_table 
ORDER BY name ;

And if you then want to replace the original table:

DROP TABLE my_table ;
ALTER TABLE my_ordered_table RENAME TO my_table;
like image 57
Sasq Avatar answered Nov 12 '22 00:11

Sasq


I think this issue relates to wanting the primary key to mean something. Avoid that trap. Choose an arbitrarily generated primary key that uniquely identifies a row of data and has no other meaning. Otherwise you will eventually run into the problem of wanting to alter the primary key values to preserve the meaning.

For a good explanation of why you should rely on ORDER BY to retrieve the data in the desired order instead of assuming the data will otherwise appear in a sequence determined by the primary key see Cruachan's answer to a similar question

like image 29
d5e5 Avatar answered Nov 12 '22 00:11

d5e5