SQLite ORDER BY Clause
To sort the fetched data in ascending or descending order, the SQLite ORDER BY clause is used. The sorting can be done based on one or more column.
Syntax:
SELECT column-list FROM table_name WHERE condition ORDER BY column1, column2, .. column_N [ASC | DESC];
Example 1:
TEACHERS Table:
ID | NAME | AGE | SUBJECT |
1 | Jim | 27 | English |
2 | John | 30 | Geology |
3 | Watson | 28 | French |
4 | Holmes | 40 | Chemistry |
5 | Tony | 35 | Physics |
SELECT * FROM TEACHERS ORDER BY NAME ASC; |
Output:
ID | NAME | AGE | SUBJECT |
1 | Jim | 27 | English |
2 | John | 30 | Geology |
5 | Tony | 35 | Physics |
3 | Watson | 28 | French |
Explanation:
In the above example, all the records from the TEACHERS table after fetching are sorted in ascending order based on the NAME column.
Example 2:
TEACHERS Table:
ID | NAME | AGE | SUBJECT |
1 | Jim | 27 | English |
2 | John | 30 | Geology |
3 | Watson | 28 | French |
4 | Holmes | 40 | Chemistry |
5 | Tony | 35 | Physics |
SELECT * FROM TEACHERS WHERE ID > 2 ORDER BY SUBJECT DESC; |
Output:
ID | NAME | AGE | SUBJECT |
5 | Tony | 35 | Physics |
3 | Watson | 28 | French |
4 | Holmes | 40 | Chemistry |
Explanation:
In the above example, all the records from the TEACHERS table where ID is greater than 2, are fetched first and are then sorted in descending order based on the SUBJECT column.