How to limit the results on a SQL query How to limit the results on a SQL query sql sql

How to limit the results on a SQL query


Yes, this is possible. This differs between db engines.

Postgres:

SELECT * FROM <table> LIMIT 50

SQL Server:

SELECT TOP 50 * FROM <table> 

...


SQL Standard

The SQL:2008 Standard provides the following syntax to limit the SQL result set:

SELECT    titleFROM    postORDER BY    id DESCFETCH FIRST 50 ROWS ONLY

The SQL:2008 Top-N records clause is supported in Oracle since 12c, SQL Server since 2012, and PostgreSQL since 8.4.

SQL Server

While SQL Server supports the SQL:2008 Top-N standard syntax, you need to provide the OFFSET clause as well:

SELECT    titleFROM    postORDER BY    id DESCOFFSET 0 ROWSFETCH FIRST 50 ROWS ONLY

On older SQL Server versions, you can use TOP:

SELECT TOP 50    titleFROM    postORDER BY    id DESC

Oracle 11g and older versions

Prior to version 12c, to fetch the Top-N records, you had to use a derived table and the ROWNUM pseudocolumn:

SELECT *FROM (    SELECT        title    FROM        post    ORDER BY        id DESC)WHERE ROWNUM <= 50

MySQL and PostgreSQL 8.3 or older

Traditionally, MySQL and PostgreSQL use the LIMIT clause to restrict the result set to the Top-N records:

SELECT    titleFROM    postORDER BY    id DESCLIMIT 50


You could use the TOP clause:

SELECT TOP 50 * FROM <table>

If your database doesn't support it you may try also LIMIT and ROWNUM but once again this will depend on the database you are using.