To retrieve a part of rows returned query, use LIMIT
and OFFSET
clauses. The following illustrates the syntax of these clauses:
SELECT
column_list
FROM
table1
ORDER BY column_list
LIMIT row_count OFFSET offset;
In this syntax,
row_count
Determine the number of rows to be returned.OFFSET
Clause skip before starting offset row return line.OFFSET
Clause is optional. If you useLIMIT
andOFFSET
clauses,OFFSET
willLIMIT
skip line before the offset constraint rows.
The following example to explain the above statement:
In use LIMIT
when clause, use ORDER BY
clause ensures that rows are returned by the specified order is very important. The following example is a skip three rows, 4 rows and then returns the result.
note:
Not all database systems support LIMIT
clause, therefore, LIMIT
clause can be used only in certain database systems such as MySQL , PostgreSQL , SQLite , Sybase SQL Anywhere and HSQLDB.
SQL LIMIT clause example
如下面的employees表
To demonstrate LIMIT
clause usage.
The following statement returns the employees
table in terms of first_name
all the rows of columns to sort.
SELECT
employee_id, first_name, last_name
FROM
employees
ORDER BY first_name;
Implementation of the above query, the following results -
+-------------+------------+-----------+
| employee_id | first_name | last_name |
+-------------+------------+-----------+
| 103 | Alexander | Lee |
| 115 | Alexander | Su |
| 114 | Avg | Su |
| 193 | Britney | Zhao |
| 104 | Bruce | Wong |
... ...
| 100 | Steven | Lee |
| 203 | Susan | Zhou |
| 106 | Valli | Chen |
| 206 | William | Wu |
+-------------+------------+-----------+
40 rows in set
If you want to only return to the previous 5
line, use the LIMIT
clause, such as the following statement.
SELECT
employee_id, first_name, last_name
FROM
employees
ORDER BY first_name
LIMIT 5;
Implementation of the above query, the following results -
+-------------+------------+-----------+
| employee_id | first_name | last_name |
+-------------+------------+-----------+
| 115 | Alexander | Su |
| 103 | Alexander | Lee |
| 114 | Avg | Su |
| 193 | Britney | Zhao |
| 104 | Bruce | Wong |
+-------------+------------+-----------+
5 rows in set
To skip the next two rows and acquires five elements, use LIMIT
and OFFSET
clauses, as in the following statement.
SELECT
employee_id, first_name, last_name
FROM
employees
ORDER BY first_name
LIMIT 5 OFFSET 3;
The results shown below -
If you are using MySQL, you can use the LIMIT OFFSET
short form clause.
SELECT
employee_id, first_name, last_name
FROM
employees
ORDER BY first_name
LIMIT 3 , 5;
Reference: https: //www.yiibai.com/sql/sql-limit.html