views:

2538

answers:

3

Hi,

I have a database in SQLlite and I'd like to sort my table in an alphabetical order. How can I do it? Is there a way to sort entries using only SQLite or do I have first to read a table into an array, sort it and afterwards to write it into a database?

Here is my query: "SELECT entry FROM table WHERE id=?" I need to get data from the table using this statement in order to get only one entry at a time.

Thank you in advance, Ilya.

+9  A: 
'Select name from table order by name asc'

'asc' is ascending, will give you the text field in alphabetical order, conversely 'desc' will give it to you in reverse alphabetical order.

Edit: as a general rule, you should let the database do the sorting. The below post is related, and arguably, almost the same. You might find it helpful:

http://stackoverflow.com/questions/655226/php-sql-order-by-or-sortarray

karim79
Thank you, this helps.But how can I assign new IDs to each row after sorting? So that changes will appear in my table. If I want to get an entry with an ID=0, it will give me a word starting from A and so on.
Ilya
@Ilya: ID keys are not row numbers. They need to be unique, but they are not in any order (nor contiguous). Sort based on the `name` column, and use the ID value only as a way to reference the row.
Bill Karwin
Do you mean you want to re-order the data alphabetically such that the the first (alphabetical) entry is assigned the lowest id number? You can insert into a new table, and then delete the old one, e.g.SELECT nameINTO table2FROM table order by name asc
karim79
watch out for case sensitive sorting with names. I'd prefer to use 'order by upper(name) asc'
Martlark
A: 

If you want to sort table without case sensitivity or with specific locale (not english) you have to add collation to your sqlite. Here is example how to do it.

klew
+1  A: 

It is also worth emphasising that the order of data in any SQL database table, or retrieved from such using a query that does not include a order by clause, is not defined.

In practice a straight read of a table without an order by will retrieve data in some fixed order and it's often the order of insert. However to rely on this is always an error, although one that is seen alarmingly often.

Cruachan