How to limit the results on a SQL query

天涯浪子 提交于 2019-12-01 18:11:23

问题


I'm wondering is it possible to limit the result of a SQL request?

For example, only return up to 50 rows from:

  SELECT * FROM <table>

thanks.


回答1:


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

Postgres:

SELECT * FROM <table> LIMIT 50

SQL Server:

SELECT TOP 50 * FROM <table> 

...




回答2:


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.




回答3:


Yes of course is possibile, in MYSQL:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.




回答4:


In MySQL you would use a LIMIT clause

 SELECT * FROM <table> LIMIT 50



回答5:


SQL Standard

As I explained in this article, the SQL:2008 Standard provides the following syntax to limit the SQL result set:

SELECT
    title
FROM
    post
ORDER BY
    id DESC
FETCH 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
    title
FROM
    post
ORDER BY
    id DESC
OFFSET 0 ROWS
FETCH FIRST 50 ROWS ONLY

On older SQL Server versions, you can use TOP:

SELECT TOP 50
    title
FROM
    post
ORDER 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
    title
FROM
    post
ORDER BY
    id DESC
LIMIT 50


来源:https://stackoverflow.com/questions/3128043/how-to-limit-the-results-on-a-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!