Site icon TestingDocs.com

SQLite ORDER BY Clause

Overview

In this tutorial, we will learn about SQLite ORDER BY clause. The ORDER BY clause is used to sort the result set of a query based on one or more columns.

SQLite ORDER BY Clause

The ORDER BY specifies the order in which rows appear in the query result. The ORDER BY clause sorts and displays the results in order based on the specified columns. The default order is the ascending order.

Syntax

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

SELECT * FROM table_name
 ORDER BY column  ASC | DESC;

You can specify one or more columns in the ORDER BY clause, and each column can be sorted in ascending (ASC) or descending (DESC) order.

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

The ASC keyword specifies that you want the data to appear in ascending order; this is the default if no sequence is specified. The DESC keyword specifies that you want the data to appear in descending order.

Examples

Let’s understand the concept with the help of examples. Consider the following table:

CREATE TABLE IF NOT EXISTS voter (
voter_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER CHECK ( age > 21 AND age < 100 )
);

 

We can use the following query to display the results in ascending order based on the age column.

sqlite> SELECT * FROM voter
      …> ORDER BY age;

We can use the following query to display the results in descending order based on the age column.

sqlite> SELECT * FROM voter
      …> ORDER BY age DESC;

 

If you use ORDER BY, it must be the last clause in the entire statement. Any columns named after ORDER BY must also be named after SELECT.

SQLite Tutorials

SQLite tutorials on this website:

https://www.testingdocs.com/sqlite-database-tutorials/

For more information on SQLite, visit the official website:

https://www.sqlite.org/

 

Exit mobile version