Latest web development tutorials

SQLite Order By

SQLiteORDER BY clause is used a column in ascending or descending order based on one or more of data.

grammar

The basic syntax of the ORDER BY clause is as follows:

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

You can use multiple columns in the ORDER BY clause. Make sure you are using the sort column in the column list.

Examples

Suppose COMPANY table has the following records:

ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0

Here is an example, it will be sorted by ascending SALARY:

sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;

This produces the following results:

ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
7 James 24 Houston 10000.0
2 Allen 25 Texas 15000.0
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0

Here is an example, it will be sorted by NAME and SALARY ASC:

sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;

This produces the following results:

ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
5 David 27 Texas 85000.0
7 James 24 Houston 10000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0

Here is an example, it will sort the results in descending order by NAME:

sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;

This produces the following results:

ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
3 Teddy 23 Norway 20000.0
1 Paul 32 California 20000.0
4 Mark 25 Rich-Mond 65000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
5 David 27 Texas 85000.0
2 Allen 25 Texas 15000.0