Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite SELECT default order with PRIMARY KEY ASC

Tags:

select

sqlite

I've created a SQLite table using:

CREATE TABLE T1 (
  CN INTEGER PRIMARY KEY ASC,
  Name TEXT
);

If I do:

SELECT * FROM T1

Will I get the rows order by CN even without specifying a ORDER BY clause? Is CN an alias to ROWID?

like image 864
Pablo Yabo Avatar asked Jan 28 '14 22:01

Pablo Yabo


People also ask

How do I get ascending order in SQLite?

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. And the DESC keyword means descending.

Which SQLite clause is used to sort the data in an ascending or descending order based on one or more columns?

SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.

What is the default ordering of rows returned from a select query?

When you issue a SELECT , the rows often get returned in the same order they were inserted in the table. You can change the order of the rows by adding an ORDER BY clause at the end of your query, with a column name after. By default, the ordering will be in "ascending order", from lowest value to highest value.

What is the default sorting order in mysql?

The SQL ORDER BY Keyword The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


Video Answer


2 Answers

There is no such thing as a default order, if you need your results ordered add an explicit order by clause.

The dbms is simply optimised to look for the best way to quickly get the required data based on the query. In this case it's the primary key on CN, but that's only because your example is so simple. Never ever rely on the dbms choosing the order you want.

like image 151
Tony Hopkinson Avatar answered Jan 04 '23 05:01

Tony Hopkinson


The second question might be useful to others.

From the SQLite documentation:

Except for WITHOUT ROWID tables, all rows within SQLite tables have a 64-bit signed integer key that uniquely identifies the row within its table. This integer is usually called the "rowid".
... if a rowid table has a primary key that consists of a single column and the declared type of that column is "INTEGER" in any mixture of upper and lower case, then the column becomes an alias for the rowid.

This also holds for columns that are declared of type "INTEGER PRIMARY KEY ASC", so in your table CN is an alias for "rowid"

Further information can be found here: http://www.sqlite.org/lang_createtable.html#rowid

like image 35
Baqs Avatar answered Jan 04 '23 04:01

Baqs