LIMIT
Overview
LIMIT
is an optional clause that can be combined with SELECT
statements used for retrieving records from one or more tables. It basically specifies the number of records a query should return after filtering the data.
Syntax
There are two versions available for the LIMIT
clause syntax:
The parameters and arguments for specific version of the syntax are described below:
column_list
: The columns or calculations that you wish to retrieve.table_name
: The tables that you want to retrieve records from.
FROM
clause.ORDER BY
: It is an expression used to order the results as you wish to return. The expression could be ascending (ASC) or descending (DESC)LIMIT row_count
: It specifies a limited number of rows to be returned based on row_count.
💡 Special Case
- If the
row_count
value is NULL, the query will produce a similar outcome because it does not contain theLIMIT
clause. - If
row_count
is zero, the statement will return an empty set.
Examples
Let’s take some examples of the LIMIT
clause.
Here we are creating one new table called comporders using the CREATE TABLE
command and inserting some values into the table using the INSERT
command:
To verify that the values have been inserted successfully, retrieve the result set using the command below:
Case #1: Using LIMIT
with the ORDER BY
Expression
This example uses the LIMIT
clause to get the first four orders sorted by order_id
:
The above query will give the following result:
Case #2: Using LIMIT
with ASC/DESC
You can use the LIMIT
clause to select rows with the highest or lowest values from a table.
- To get the top 5 most expensive orders, you sort orders by the product price in descending order (DESC) and use the
LIMIT
clause to get the first 5 orders.
The following query depicts the idea:
The result of the query is as follows:
- We will fetch the top 5 cheapest orders this time. You sort orders by the product price in ascending order (ASC) and use the
LIMIT
clause to get the first 5 orders.
The following query depicts the idea:
We will get the below output:
#Case 3: Using LIMIT
with OFFSET
In this example, we will use LIMIT
and OFFSET
clauses to get 5 orders using the below query:
After implementing the above command, we will get the below output:
The result above shows that:
- The orders with
order_id
= 1002 & 1003 aren’t displayed because we put theOFFSET
value with 2. So the first 2 lines are ignored. - The orders with
order_id
= 1009 & 1010 aren’t displayed because theLIMIT
value is 5, which will display only 5 rows.