Rigotti
Rigotti

Reputation: 2872

Column index order SQLite creates table

This is the query that I use to create a table

create table site_table(
   _id integer primary key autoincrement,
   name_site text,
   url text,
   login text,
   pass text
);

I called Cursor.getColumnNames() and noticed that columns order are id, login, pass, name, url.

So, if I want a value I have to get it by the index Cursor.getString(index). Until I debugged I was messing up calling the wrong index, but now I wonder, why SQLite saves that way? Why it does not follow that way I created id, name_site, url, login and pass?

Thanks

Upvotes: 5

Views: 2724

Answers (4)

Nantoka
Nantoka

Reputation: 4243

I just made the experience first hand:

The indices of the columns of the cursor as a result of a

SELECT * FROM mytable WHERE ...

query have sometimes (not always) a different order that what SQLITE Database Browser shows as column order in the Database Structure tab. So referencing the columns via getColumnIndex seems to be the only safe way.

Upvotes: 0

Simon Dorociak
Simon Dorociak

Reputation: 33515

So, if I want a value I have to get it by the index Cursor.getString(index)

So for example for this reason you should always use

c.getString(c.getColumnIndex("ColName")); // or better getColumnIndex(CONSTANT)

This method saves all of us and ensure that you never get wrong results. Generally this method is recommended and also storing COLUMN_NAMES as CONSTANTS in separated class is very, very useful and efficient practise.

Note: Order depends on projection i.e. select name, lastname from table

Upvotes: 5

Leszek
Leszek

Reputation: 6598

Columns order in your cursor depends on projection. To be sure you use correct column index use c.getString(c.getColumnIndexOrThrow("COLUMN_NAME")) where c is your cursor.

Upvotes: 1

Barak
Barak

Reputation: 16393

That data is ordered by the order your requested it in your query, not the order you created the table with. So you probably changed the order in your query that generated said cursor.

Upvotes: 1

Related Questions