The PostgreSQL ORDER BY clause is used to sort the result query set returned by the SELECT statement. As the query set returned by the SELECT statement has no specific order, one can use the ORDER BY clause in the SELECT statement to sort the results in the desired manner.
column_1 [ASC | DESC],
column_2 [ASC | DESC];
Let’s analyze the above syntax:
- Firstly we specify the column or the expression that we want to be sorted. If multiple columns or expressions are to be used in the SELECT statement, we separate them with commas.
- Secondly, The ASC expression is used to sort the result set in ascending order, and DESC expression is used to sort the result set in descending order. By default the ORDER BY clause uses ASC.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.
Using PostgreSQL ORDER BY clause to sort rows by one column in the “customer” table of the sample database
SELECT first_name, last_name FROM customer ORDER BY first_name DESC;
Using PostgreSQL ORDER BY clause to sort rows by multiple columns in the “customer” table. Here we will be sorting the customers by the first name in the ascending order first, and then sort the sorted result set by the last name in descending order.
SELECT first_name, last_name FROM customer ORDER BY first_name ASC, last_name DESC;
The output of the code gets more clear if the first name of the customer is the same as shown below:
Using PostgreSQL ORDER BY clause to sort rows by expressions. In the below example we will be using the ORDER BY clause with the LENGTH() function to sort the rows by the lengths of the first names of customers. The LENGTH() function accepts a string and returns its length.
SELECT first_name, LENGTH(first_name) len FROM customer ORDER BY LENGTH(first_name) DESC;
- PostgreSQL - WHERE clause
- PostgreSQL - HAVING clause
- PostgreSQL - FETCH clause
- PostgreSQL - LIMIT clause
- PostgreSQL - GROUP BY clause
- PostgreSQL - LIMIT with OFFSET clause
- PostgreSQL - SELECT DISTINCT clause
- PostgreSQL - Subquery
- PostgreSQL - Size of value
- PostgreSQL - SERIAL
- PostgreSQL - NOT BETWEEN operator
- PostgreSQL - LIKE operator
- PostgreSQL - Alias
- PostgreSQL - NOT LIKE operator
- PostgreSQL - SELF JOIN
- PostgreSQL - Joins
- PostgreSQL - BETWEEN operator
- Install PostgreSQL on Mac
- What is PostgreSQL - Introduction
- PostgreSQL - SELECT
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.