A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/postgresql-order-by-clause/ below:

PostgreSQL - ORDER BY clause

PostgreSQL - ORDER BY clause

Last Updated : 12 Jul, 2025

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.

Syntax: SELECT column_1, column_2 FROM table_name ORDER BY column_1 [ASC | DESC], column_2 [ASC | DESC];

Let's analyze the above syntax:

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.

Example 1:

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;
Output: Example 2:

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;
Output:

The output of the code gets more clear if the first name of the customer is the same as shown below:

E

xample 3:

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;
Output:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4