# ORDER BY in PostgreSQL

PostgreSQL ORDER BY
PostgreSQL ORDER BY clause is used to sort or re-arrange the records in the result set. It is used with the PostgreSQL SELECT statement. It however does not have a mandatory existence with the PostgreSQL SELECT statement.

Syntax:

SELECT expressions
FROM table_name
WHERE conditions;
ORDER BY expression [ ASC | DESC ];


Parameters:
expressions: It is used to specify the columns or calculations to be retrieved.
table_name: It is used to specify the name of the table from which you want to retrieve the records.
conditions: It is used to specify the conditions to be strictly followed for selection.
ASC: It is used to specify the sorting order to sort records in ascending order, but is an optional parameter.
DESC: It is used to specify the sorting order to sort records in descending order, and is also an optional parameter.

Example: Selecting specific fields from a table in default order.
Employment table:

 ID STATE RATE 1 A 60 2 B 70 3 C 65 4 D 80 5 E 78

Query:

SELECT * FROM “EMPLOYMENT” WHERE “ID” &gt; 2 ORDER BY “RATE”;

Output:

 ID STATE RATE 3 C 60 5 E 78 4 D 80

Explanation:
The EMPLOYMENT is an already existing table. Here the rearrangement are done after the selection of the records from the table. The sorting here is done in default order by the RATE column. The default sorting order is ascending order.

Example: Selecting specific fields from a table in ascending order.
Employment table:

 ID STATE RATE 1 A 60 2 B 70 3 C 65 4 D 80 5 E 78

Query:

SELECT * FROM “EMPLOYMENT” WHERE “ID” &gt; 2 ORDER BY “RATE” ASC;

Output:

 ID STATE RATE 3 C 65 5 E 78 4 D 80

Explanation:
The EMPLOYMENT is an already existing table. Here the rearrangement are done after the selection of the records from the table. The sorting here is done in ascending order by the RATE column.

Example: Selecting specific fields from a table in descending order.

Employment table:

 ID STATE RATE 1 A 60 2 B 70 3 C 65 4 D 80 5 E 78

Query:

SELECT * FROM “EMPLOYMENT” WHERE “ID” &gt; 2 ORDER BY “RATE” DESC;

Output:

 ID STATE RATE 4 D 80 5 E 78 3 C 65

Explanation:
The EMPLOYMENT is an already existing table. Here the rearrangement are done after the selection of the records from the table. Here, the sorting is done in descending order by the RATE column.