Re-sorting Sqlite table

I would like to know if there is an SQL command that would re-sort the a table in a SQLite database. I have a table with 4 columns, which gets data added and removed from it frequently.
Just from a neatness point of view (as the messiness of the table does not have any negative impact on SQL queries on the table data), I'd like to be able to sort the table.
I've attached a screen grab of the table where you can see 4 records with Dept_Id value 1 and 4 records with Dept_id value 2. I'd like to sort the table so I get all the Value 1s followed by the Value 2s etc. Screen grab of SQlite table I'd like to sort.
Who is Participating?
jon47Connect With a Mentor Commented:
Actually, here's some SQL that does what you want... it takes four statements-

CREATE TABLE DeptExtsSorted (Dept_Name TEXT, Extn_Name TEXT, Dept_Id NUMERIC, Dept_Ext NUMERIC);
INSERT INTO DeptExtsSorted (Dept_Name, Extn_Name, Dept_Id, Dept_Ext) SELECT Dept_Name, Extn_Name, Dept_Id, Dept_Ext FROM DeptExts ORDER BY Dept_Id, Extn_Name;
ALTER TABLE DeptExtsSorted RENAME TO DeptExts;

- you'll need to  check that the DeptExtsSorted table is created to match DeptExts, and check I've got the column names right too.
This creates a new table, sorts the data and inserts it into that new table, deletes the original, renames the sorted table to replace the original.

It's a bit warped, but appears to work ;-)

There isn't an SQL command which reorders the records stored in a table.  What you can do is pull the data out sorted in whatever way you choose- so rather than browsing the table, use the "Execute SQL" tab in your sqlite browser and use a query like this:

SELECT * FROM DeptExts ORDER BY `Dept Id`, `Extn Name`

(Those a back-ticks around the column names)


kalbarrimanAuthor Commented:
Thanks Jon. Yes, no problem pulling the data from the table in any sort order I want, but sorry to hear, (although not surprised as I've been checking on the NET and reading books and can't find anything) that I can't actually re-sort the table itself.
I'll leave the question open for a bit longer just in case someone else can magic up a solution but otherwise, thanks for your input.
kalbarrimanAuthor Commented:
Thanks Jon. Yes, I was thinking along similar lines (except I was going to suck out the data into an array, and then delete all the entries, and then re-insert them in sorted order), but I think your solution is better.
Apppreciate it. I'll close the Question now.
kalbarrimanAuthor Commented:
There doesn't appear to be any way to do what I want with a single SQL command, but the solution resolves the issue in as good a way as possible.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.