sqlite
  1. sqlite-order-by

SQLite Clauses/Conditions: ORDER BY

The ORDER BY clause is used to sort the result set in either ascending or descending order based on one or more columns. This clause can be used in conjunction with the SELECT statement to sort data in a specific order.

Syntax

The syntax for the ORDER BY clause is:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;

Here, column1, column2 etc. are the columns that you want to sort on. You can specify the sorting order for each column by using the keywords ASC (ascending order) or DESC (descending order).

Example

Suppose we have a table called employees with the columns id, name, salary, and age, and we want to sort the result set by the salary column in descending order. We can use the following query:

SELECT * FROM employees
ORDER BY salary DESC;

Output

The output of the above query would be a result set of all employees sorted by their salary in descending order:

id | name      | salary | age
---+-----------+--------+-----
5  | John Doe  | 65000  | 31
3  | Jane Smith| 55000  | 25
1  | Bob Johnson| 45000  | 27
4  | Susan Brown| 40000  | 20
2  | Joe Davis | 35000  | 22

Explanation

In the example above, we select all columns from the employees table and use the ORDER BY clause to sort the result set by the salary column in descending order. The result set is then displayed with all columns and their respective values.

Use

The ORDER BY clause is useful when you want to sort the result set in a specific order. This can be useful when you want to display the data in a specific way or when you want to perform calculations on the data based on a certain order.

Important Points

  • The ORDER BY clause is always the last clause in a SELECT statement.
  • You can order by multiple columns by separating them with a comma.
  • Columns are sorted in ascending order by default.
  • To sort in descending order, you need to explicitly specify the DESC keyword.
  • You can use numeric column positions instead of column names in the ORDER BY clause.

Summary

In this tutorial, we learned about the ORDER BY clause in SQLite and how to use it with the SELECT statement to sort the result set in a specific order. We saw an example of sorting data by the salary column in descending order and learned about important points to keep in mind while working with the ORDER BY clause.

Published on: