How to limit rows in PostgreSQL SELECT

SqlPostgresqlSql Limit

Sql Problem Overview


What's the equivalent to SQL Server's TOP or DB2's FETCH FIRST or mySQL's LIMIT in PostgreSQL?

Sql Solutions


Solution 1 - Sql

You can use LIMIT just like in MySQL, for example:

SELECT * FROM users LIMIT 5;

Solution 2 - Sql

You could always add the OFFSET clause along with LIMIT clause.

You may need to pick up a set of records from a particular offset. Here is an example which picks up 3 records starting from 3rd position:

testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;

This would produce the following result:

 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000

Full explanation and more examples check HERE

Solution 3 - Sql

On PostgreSQL, there are two ways to achieve this goal.

SQL Standard

The first option is to use the SQL:2008 standard way of limiting a result set using the FETCH FIRST N ROWS ONLY syntax:

SELECT
    title
FROM
    post
ORDER BY
    id DESC
FETCH FIRST 50 ROWS ONLY

> The SQL:2008 standard syntax is supported since PostgreSQL 8.4.

PostgreSQL 8.3 or older

For PostgreSQL 8.3 or older versions, you need the LIMIT clause to restrict the result set size:

SELECT
    title
FROM
    post
ORDER BY
    id DESC
LIMIT 50

Solution 4 - Sql

Use the LIMIT clause or FETCH FIRST 10 ROWS

Solution 5 - Sql

Apart from limit you could use Fetch First as well. Your question already had the answer

Select * from users FETCH FIRST 5 ROWS ONLY

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan MertzView Question on Stackoverflow
Solution 1 - SqlSinan TaifourView Answer on Stackoverflow
Solution 2 - SqlmongotopView Answer on Stackoverflow
Solution 3 - SqlVlad MihalceaView Answer on Stackoverflow
Solution 4 - SqlHosam AlyView Answer on Stackoverflow
Solution 5 - SqlSarathView Answer on Stackoverflow