Sqlite Order By
# SQLite Order By
The SQLite **ORDER BY** clause is used to sort the data in one or more columns in ascending or descending order.
## Syntax
The basic syntax of ORDER BY clause is as follows:
SELECT column-list FROM table_name [ORDER BY column1, column2, .. columnN] [ASC | DESC];
* **ASC** is the default value, sorting from smallest to largest, in ascending order.
* **DESC** sorts from largest to smallest, in descending order.
You can use multiple columns in the ORDER BY clause. Ensure that the columns you use for sorting are in the column list:
SELECT select_list FROM table ORDER BY column_1 ASC, column_2 DESC;
If you don't specify the sorting rule after column_1 and column_2, it defaults to ASC (ascending). The above statement sorts by column_1 ascending and column_2 descending, which is equivalent to the following statement:
SELECT select_list FROM table ORDER BY column_1, column_2 DESC;
## Examples
Assume the COMPANY table has the following records:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ----------1 Paul 32 California 20000.02 Allen 25 Texas 15000.03 Teddy 23 Norway 20000.04 Mark 25 Rich-Mond 65000.05 David 27 Texas 85000.06 Kim 22 South-Hall 45000.07 James 24 Houston 10000.0
Here is an example that sorts the result in ascending order by SALARY:
sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;
This will produce the following result:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ----------7 James 24 Houston 10000.02 Allen 25 Texas 15000.01 Paul 32 California 20000.03 Teddy 23 Norway 20000.06 Kim 22 South-Hall 45000.04 Mark 25 Rich-Mond 65000.05 David 27 Texas 85000.0
Here is an example that sorts the result in ascending order by NAME and SALARY:
sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
This will produce the following result:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ----------2 Allen 25 Texas 15000.05 David 27 Texas 85000.07 James 24 Houston 10000.06 Kim 22 South-Hall 45000.04 Mark 25 Rich-Mond 65000.01 Paul 32 California 20000.03 Teddy 23 Norway 20000.0
Here is an example that sorts the result in descending order by NAME:
sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;
This will produce the following result:
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ----------3 Teddy 23 Norway 20000.01 Paul 32 California 20000.04 Mark 25 Rich-Mond 65000.06 Kim 22 South-Hall 45000.07 James 24 Houston 10000.05 David 27 Texas 85000.02 Allen 25 Texas 15000.0
YouTip