SQL: Query results limit the number of rows returned

SQL: Query results limit the number of rows returned


foreword

In SQL query, it is a common restriction condition to limit the number of rows returned by the query result. This article mainly introduces how to use limit in SQL to limit.

Part of this article is referenced from: SQL4 query results limit the number of rows returned


1. Limit

One sentence: The Limit clause can be used to force the SELECT statement to return the specified number of records.

There are two ways to use Limit: Limit a and Limit a,b

1.Limit a

Limit a indicates the number of rows to return a record
insert image description here

SQL statements:

select device_id from user_profile limit 2

return result:
insert image description here

2.Limit a,b

LIMIT a,b : Given two parameters, the first parameter specifies the offset of the first returned record row, and the second parameter specifies the maximum number of returned record rows.

Explanation:
(1) In order to retrieve all the record lines from a certain offset to the end of the record set, you can specify the second parameter as -1.
(2) The offset of the initial record line is 0 (instead of 1), that is, the offset of the first record line is 0, the second is 1, and so on.

SELECT * FROM table LIMIT 10,-1 //检索结果为从第11行数据到最后

//适用于MySql
SELECT * FROM table LIMIT 5,5 //检索结果为从第6行到第10行

Note: The Postgres library does not support the Limit a, b syntax!
insert image description here

2. Expansion: Limit a offset b

LIMIT and OFFSET allow you to retrieve only a portion of the rows produced by the remainder of the query:

LIMIT : Limit how many pieces of data to fetch.
OFFSET : How many pieces of data to skip and then fetch subsequent data.

LIMIT and OFFSET keywords can be used alone or in combination when querying. It should be noted that no matter how they are used, the sorting method needs to be determined first, otherwise it does not make much sense (because if the data is out of order, take the first number and not explicit).

//跳过前6行,从第7行开始输出5行的内容
SELECT * FROM table LIMIT 5 offset 6 //检索结果为从第7行到第11行

Guess you like

Origin blog.csdn.net/qq_46119575/article/details/129821347