PostgreSQL – LIMIT Clause

In Postgres, you can use ‘LIMIT’ clause to return only a certain number of rows by a query.

Syntax:

SELECT * from table1 LIMIT 10;

Above statement will return only 10 rows if there are more than 10 rows in the table.

If the table has fewer than 10 rows, all the rows will be returned.

Consider the employee table as shown below:

idfirst_namelast_namedepartmentsalary
101bryanwalkersales50,000
102alexcarpenteraccounts55,000
103samwhitesales60,000
104johnbarrysales54,000
105billwoodaccounts65,000
106roberthopkinssupport70,000
107davidleesupport72,000
108jacksearssupport65,000
109tomyoungsales55,000
employee
SELECT * FROM employee LIMIT 2;

Above sql query will return any 2 rows from the employee table. There is no control on which 2 rows will be returned. And, each time the query is executed, you might get a different data set. The output is unpredictable.

To obtain a predictable result set, you should use ORDER BY clause with the LIMIT clause.

Example: Below query will return the top 2 rows from the employee table sorted by salary in the descending order. Thus the 2 rows returned are the top 2 employees with highest salary amounts.

SELECT * FROM employee ORDER BY salary DESC LIMIT 2;

Also check out OFFSET Clause.