Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column index order SQLite creates table

Tags:

android

sqlite

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

like image 581
Rigotti Avatar asked Mar 31 '13 18:03

Rigotti


People also ask

How do I sort a column in SQLite?

The ORDER BY clause comes after the FROM clause. It allows you to sort the result set based on one or more columns in ascending or descending order. In this syntax, you place the column name by which you want to sort after the ORDER BY clause followed by the ASC or DESC keyword. The ASC keyword means ascending.

Does SQLite create index on primary key?

In an ordinary SQLite table, the PRIMARY KEY is really just a UNIQUE index. The key used to look up records on disk is the rowid. The special "INTEGER PRIMARY KEY" column type in ordinary SQLite tables causes the column to be an alias for the rowid, and so an INTEGER PRIMARY KEY is a true PRIMARY KEY.

Does SQLite automatically create index?

By the same token, you should also omit explicit declaration of indexes on columns declared unique or unique constraints in the table definition. SQLite3 will create these indexes automatically.

What is the correct format for creating an ID column for the vehicles table in SQLite?

What is the correct format for creating an ID column for the Vehicles table in SQLite? CREATE TABLE vehicles (VehicleID INTEGER PRIMARY KEY);


2 Answers

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

like image 179
Simon Dorociak Avatar answered Oct 28 '22 21:10

Simon Dorociak


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.

like image 39
Barak Avatar answered Oct 28 '22 21:10

Barak