PostgreSQL Order By Clause

PostgreSQL Order By Clause causes the result rows to be sorted according to the specified expression. PostgreSQL Order By Clause is used to sort rows either in ascending or descending order based on one or more columns. Default sort order is ascending.

PostgreSQL Order By Syntax

SELECT COLUMNSLIST FROM TABLE_NAME WHERE CONDITION ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...];

PostgreSQL Order By Examples

Below table ’emp’ used for below examples:

1. Find the list of employees working as CLERK and arrange result as hiredate in descending order.

select * from emp where job='CLERK' order by hiredate desc;

PostgreSQL Order By Clause

2. Get the employees sorted by sal from highest to lowest(desc).

select * from emp order by sal desc;

PostgreSQL Order By Clause

3. Get the employees who is working in dept no 30 and sort in salary from lowest to highest.

select * from emp where deptno = 20 order by sal asc;