How to limit rows in PostgreSQL SELECT

Viewed 133768

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

5 Answers

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

SELECT * FROM users LIMIT 5;

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
Related