SQLite Insertion Order vs Query Order? - android

Will the order of rows returned by a query will be the same as the order in which the rows were inserted into the table, of SQLite database?
If Yes, Is this behaviour consistent?
If No, Can this be enforced?
I have a requirement of storing approx 500 rows of data, and which requires sorting/ordering from time to time. The data is in proper order, before the insertion.

Given the small number of rows in your table, this is probably what you need:
SELECT * FROM yourtable ORDER BY ROWID
For more information on ROWID, see these two links:
SQLite Autoincrement and ROWIDs and the INTEGER PRIMARY KEY

Even if the order may be consistent in one scenario, there is afaik no guarantee.
That is why SQL has the ORDER BY operator:
SELECT foo,bar FROM Table FOO WHERE frobnitz LIKE 'foo%' ORDER BY baz ASC;

Will the order of rows returned by a
query will be the same as the order in
which the rows were inserted into the
table, of SQLite database?
No, you can't count on that. All query optimizers have a lot of freedom when it comes to speeding up queries. One thing they're free to do is to return rows in whatever order is the fastest. That's true even if a particular dbms supports clustered indexes. (A clustered index imposes a physical ordering on the rows.)
There's only one way to guarantee the order of returned rows in a SQL database: use an ORDER BY clause.

Related

Sqlite order by rows order

I am using this query
"select * from SomeTable group by SomeColumn"
It is returns list with accenting order, but i need to same order like in database.
For example the order in database is:
p
a
s
But result is:
a
i
p
Sample
The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul
In Sqlite, each row of a table has a unique rowid, which you can use for sorting.
select * from SomeTable group by SomeColumn order by rowid;
In your statement, add this line to sort the results:
order by min(rowid)
Your query does not enforce any order with ORDER BY clause so no assumption about row order should be made. If you want specific order add i.e. ORDER BY SomeColumn. See docs about all available order options: https://www.sqlite.org/lang_select.html#orderby
By the rules of SQL, you can't count on getting records back in any specific order without specifying an ORDER BY clause in your SQL query.
In practice servers sometimes return values in the order in which they're inserted, in the order of the first index created, or in the order of the primary key--but you can't count on this behavior, and in fact I've seen the behavior change between database maintenance windows or after the database version is upgraded. You definitely wouldn't want to count on a DB engine to give you back records in any particular order if you write a SELECT statement without an ORDER BY clause.
The only real way to get your records back in the order you inserted them is to create a timestamp column and then sort on it during the SELECT. If you don't want to worry about populating that column on INSERT, have that column auto-populate itself with a timestamp (depending on your DB engine).

Indexes in SQLite and ordering of rows based on PK

Does a PK in SQLite guarantee order of data?
AFAIK indexes implementation store data in-order of PK.
Does this apply for SQLite? Even for a composite PK?
The documentation says:
If a SELECT statement that returns more than one row does not have an ORDER BY clause, the order in which the rows are returned is undefined.
The presence of a primary key or any other index does not change this; there is no guarantee that that index is actually used for the query.
If you want the output of a query to be sorted, you must use an ORDER BY. (If the ordering can be trivially implemented with the index, this will not be any less efficient that the same query without the ORDER BY clause.)
Do you want know the underly implementation about indexes in SQLite and how does SQLite store data on the disk? Maybe help you at File Format For SQLite Databases and Here in chinese.

SQLite too many terms in compound SELECT

In my Android SQLite databese query I have an INSERT INTO statement followed by about 600 ('data1'),('data2')... tags, generated by code.
After db.exec(sql) I got this error: "too many terms in compound SELECT (code1); while compiling INSERT INTO.. "
Is there any way to increase this limitation?
The limit SQLITE_MAX_COMPOUND_SELECT cannot be raised at runtime,
So you need to split your inserts into batches of 500 rows each. This will be more efficient than inserting one row per query. For e.g.
BEGIN TRANSACTION
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
...
END TRANSACTION
Also see Insert Multiple Rows in SQLite

Is 'ORDER BY _id' enough to get rows in insertion order?

I'm using SQLite DB in my Android app.
Now I need to implement data extraction in the same order in which it was inserted.
Is it enough to do SELECT ... ORDER BY _id ... if the _id column is INTEGER PRIMARY KEY AUTOINCREMENT?
Or should I add a column to store the date and time a row has been created?
You can use ORDER BY _id. Make sure you are using a List and not a Set....
No need, an id generated by AUTOINCREMENT is enough.
Yes, if you just need the order, you may use such statement or just simple "SELECT ... FROM sometable". Results will be equals.

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
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
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.
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.
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.

Categories

Resources