DEV Community

Malik M
Malik M

Posted on

USE of ORDER BY in PostgreSQL

In this article I will share how Order By clause can be used in the PostgreSQL.
Let's get started...
When a query is run to return the rows as output in a SELECT statement, it returns data in unspecified order. So ORDER BY clause is used to sort the data of the output.

Syntax of ORDER BY clause

SELECT
    select_list
FROM
    table_name
ORDER BY
    sort_expression1 [ASC | DESC];
Enter fullscreen mode Exit fullscreen mode

As from the syntax, it can be seen that first step is to specify a sort expression that can be a column or expression which you want to sort just after the ORDER BY clause.
After specifying the sort expression, ASC or DESC is used to sort the rows of output in ascending or descending order based on the desired output you want.
It is noted that if you miss writing the ASC or DESC option then by default ASC is used.

Example
Suppose we have the customer table with following attributes in the database:

Image description

1. Using ORDER BY to sort rows by column:

SELECT
       first_name,
       last_name
FROM
       customer
ORDER BY
       last_name DESC;
Enter fullscreen mode Exit fullscreen mode

The above query returns the rows after those rows by values in the last name column in descending order.

OUTPUT:
Image description

2. Using ORDER BY to sort rows by expressions:

SELECT 
    first_name,
    LENGTH(first_name) len
FROM
    customer
ORDER BY 
    len DESC;
Enter fullscreen mode Exit fullscreen mode

The above query returns first select the first names and their length. And then It sorts the rows by the lengths of the first names in descending order. The name with highest length will be on the top and so on.

OUTPUT:
Image description

Conclusion
In this tutorial we learnt about the use of ORDER BY clause in PostreSQL by column as well as by expressions.

Top comments (0)