Javatpoint Logo

91-9990449935

 0120-4256464

PostgreSQL ORDER BY clause

The PostgreSQL ORDER BY clause is used for sorting data in ascending or descending order. The data is sorted on the base on one or more columns.

Syntax:


Parameters explanation:

column_list: It specifies the columns or calculations that you want to retrieve.

table_name: It specifies the tables that you want to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions: It is optional. It specifies that the condition must be fulfilled to retrieve records.

ASC: It is also optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).

DESC: It is also optional. It sorts the result set in descending order by expression.

See this example:

Let's take a table "EMPLOYEES" having the following data.

 postgresql order by clause

ORDER BY: ASC

Execute the following query to retrieve the records ORDER BY AGE in ascending order:

Output:

 postgresql order by clause

ORDER BY: DESC

Execute the following query to retrieve the records ORDER BY NAME in descending order:

Output:

 postgresql order by clause

ORDER BY with multiple columns:

You can also fetch the records from table ORDER BY multiple columns.

Execute the following query to fetch the records from table "EMPLOYEES" ORDER BY NAME and ADDRESS in ascending order.

Output:

 postgresql order by clause