The Wayback Machine - https://web.archive.org/web/20240930153415/https://www.geeksforgeeks.org/sql-limit-clause/
Open In App

SQL LIMIT Clause

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The LIMIT clause in SQL allows users to control the amount of data retrieved and displayed in the result set.

It is useful when only a subset of records is needed for analysis or display purposes in large databases with thousands of records.

Syntax

The Syntax to use LIMIT in SQL is:

SELECT column1, column2, …
FROM table_name
WHERE condition
ORDER BY column
LIMIT [offset,] row_count;

Here,

  • offset: number of rows to skip before returning the result set.
  • row_count: number of rows to return in the result set.

SQL LIMIT Examples

Let’s look at some examples of the LIMIT clause in SQL to understand it’s working:

We will use the sample table name “Student” and write some LIMIT queries. 

student table

Student Table

To create this table in your system, write the following queries:

SQL
CREATE TABLE student (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  age INT
);

INSERT INTO student (id, name, age)
VALUES (1, 'Shubham Thakur', 18),
       (2, 'Aman Chopra', 19),
       (3, 'Bhavika uppala', 20),
       (4,'Anshi Shrivastava',22);

LIMIT Clause Example

In this example, we will only retrieve 3 rows from the student table using LIMIT.

Query:

SELECT * FROM student 
LIMIT 3;

Output:

LIMIT Clause Example

LIMIT with ORDER BY Clause

In this example, we will use the LIMIT clause with ORDER BY clause

Query:

SELECT * FROM Student
ORDER BY Grade DESC
LIMIT 3;

Output:

LIMIT with ORDER BY Clause

The LIMIT operator can be used in situations such as the above, where we need to find the top 3 students in a class and do not want to use any conditional statements.

SQL LIMIT OFFSET

LIMIT OFFSET parameter skips a specified number of rows before returning the result set.

OFFSET can only be used with the ORDER BY clause. It cannot be used on its own.

OFFSET value must be greater than or equal to zero. It cannot be negative, else returns an error. 

Syntax

SELECT * FROM table_name ORDER BY column_name LIMIT X OFFSET Y;

OR

SELECT * FROM table_name ORDER BY column_name LIMIT X,Y;

The first value X is the offset value and the second value Y is the LIMIT value.

SQL LIMIT OFFSET Example

In this example, we will skip first 2 values using offset and print only 3 rows.

Query:

SELECT * FROM Student 
ORDER BY ROLLNO LIMIT 2,5;

Output:

sql limit offset example output

SQL LIMIT OFFSET Example Output

SQL LIMIT to Get the nth Highest or Lowest Value

Now we will look for LIMIT use in finding highest or lowest value we need to retrieve the rows with the nth highest or lowest value. In that situation, we can use the subsequent LIMIT clause to obtain the desired outcome.

Syntax:

SELECT column_list  
FROM table_name  
ORDER BY expression  
LIMIT n-1, 1;  

Example

In this example, we will retrieve third highest age of student table.

Query:

SELECT age FROM Student  
ORDER BY age LIMIT 2, 1; 

Output:

sql limit to get the nth highest value example output

SQL LIMIT to Get the nth Highest Value Example Output

LIMIT with WHERE Clause

The WHERE clause can also be used with LIMIT. It produces the rows that matched the condition after checking the specified condition in the table.

Example

In this example, we will use SQL LIMIT with WHERE Clause

Query:

SELECT age
FROM Student
WHERE id<4
ORDER BY age
LIMIT 2, 1;

Output:

limit with where clause example output

LIMIT with WHERE Clause Example Output

Restrictions on the LIMIT clause

There are several limitations of SQL LIMIT. The following situations do not allow the LIMIT clause to be used:

  • With regard to defining a view
  • The use of nested SELECT statements
  • Except for subqueries with table expressions specified in the FROM clause.
  • Embedded SELECT statements are used as expressions in a singleton SELECT (where max = 1) within an SPL routine where embedded SELECT statements are used as expressions. 

Important Points About SQL LIMIT

  • The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL.
  • It is important to note that this clause is not supported by all SQL versions.
  • The LIMIT clause can also be specified using the SQL 2008 OFFSET/FETCH FIRST clauses.
  • The limit/offset expressions must be a non-negative integer.


Previous Article
Next Article

Similar Reads

SQL TOP, LIMIT, FETCH FIRST Clause
SQL TOP, LIMIT, and FETCH FIRST clauses are used to retrieve a specific number of records from a table. These clauses are especially useful in large datasets with thousands of records. Each of these SQL clauses performs a similar operation of limiting the results returned by a query, but they are supported by different database management systems:
7 min read
Difference Between Having Clause and Group by Clause
GROUP BY clause is used to aggregate rows with identical values appearing in specified columns. This clause is often used with aggregate functions like SUM, COUNT, MAX, MIN,Group etc. The HAVING clause filters groups of the GROUP BY clause and makes it possible to filter rows at the group level without destroying the information in the groups. In t
5 min read
PHP | MySQL LIMIT Clause
In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count.The value of both the parameters can be zero or positive integers. Offset:It is used to specify the offset of the first row to be returned. Count:It is used to specify
3 min read
Python MariaDB - Limit Clause using PyMySQL
The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of the OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows. Syntax : S
2 min read
SQL | Intersect & Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 …… FROM table 1 WHERE….. INTERSECT SELECT column-1, column-2 …… FROM table 2 WHE
1 min read
SQL | USING Clause
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive. It should not have a q
2 min read
SQL | With Ties Clause
This post is a continuation of SQL Offset-Fetch Clause Now, we understand that how to use the Fetch Clause in Oracle Database, along with the Specified Offset and we also understand that Fetch clause is the newly added clause in the Oracle Database 12c or it is the new feature added in the Oracle database 12c. Now consider the below example: Suppos
4 min read
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.The correlation variables from the relations in from clause cannot be used in the sub-queries in
2 min read
SQL | ON Clause
The join condition for the natural join is basically an EQUIJOIN of all columns with same name. To specify arbitrary conditions or specify columns to join, the ON Clause is used. The join condition is separated from other search conditions. The ON Clause makes code easy to understand. ON Clause can be used to join columns that have different names.
2 min read
Combining aggregate and non-aggregate values in SQL using Joins and Over clause
Prerequisite - Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:Table - EMPLOYEE TABLE NameNullTypeEMPNONOT NULLNUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESA
2 min read
SQL Full Outer Join Using Left and Right Outer Join and Union Clause
An SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL. In this article, we will discuss FULL OUTER JOIN using LEFT OUTER Join, RIGHT OUTER JOIN, and UNION clause. Consider the two tables below: Sample Input Table 1: Pu
3 min read
Difference between From and Where Clause in SQL
1. FROM Clause: It is used to select the dataset which will be manipulated using Select, Update or Delete command.It is used in conjunction with SQL statements to manipulate dataset from source table.We can use subqueries in FROM clause to retrieve dataset from table. Syntax of FROM clause: SELECT * FROM TABLE_NAME; 2. WHERE Clause: It is used to a
2 min read
Distinct clause in MS SQL Server
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values and sometimes we only want to list the different (distinct) values. Consider a simple database and we will be discussing distinct clauses in MS SQL Server. Suppose a table has a maximum of 1000 rows constit
3 min read
Where clause in MS SQL Server
In this article, where clause will be discussed alongside example. Introduction : To extract the data at times, we need a particular conditions to satisfy. 'where' is a clause used to write the condition in the query. Syntax : select select_list from table_name where condition A example is given below for better clarification - Example : Sample tab
1 min read
Having clause in MS SQL Server
In this article, we will be discussing having clause in MS SQL Server. There are certain instances where the data to be extracted from the queries is done using certain conditions. To do this, having clause is used. Having clause extracts the rows based on the conditions given by the user in the query. Having clause has to be paired with the group
2 min read
Group by clause in MS SQL Server
Group by clause will be discussed in detail in this article. There are tons of data present in the database system. Even though the data is arranged in form of a table in a proper order, the user at times wants the data in the query to be grouped for easier access. To arrange the data(columns) in form of groups, a clause named group by has to be us
3 min read
SQL Full Outer Join Using Union Clause
In this article, we will discuss the overview of SQL, and our main focus will be on how to perform Full Outer Join Using Union Clause in SQL. Let's discuss it one by one. Overview :To manage a relational database, SQL is a Structured Query Language to perform operations like creating, maintaining database tables, retrieving information from the dat
3 min read
SQL Full Outer Join Using Where Clause
A SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL. In this article, we will discuss about FULL OUTER JOIN using WHERE clause. Consider the two tables below: Sample Input Table 1 : PURCHASE INFORMATIONProduct_IDMobil
3 min read
Difference Between JOIN, IN and EXISTS Clause in SQL
SEQUEL widely known as SQL, Structured Query Language is the most popular standard language to work on databases. We can perform tons of operations using SQL which includes creating a database, storing data in the form of tables, modify, extract and lot more. There are different versions of SQL like MYSQL, PostgreSQL, Oracle, SQL lite, etc. There a
4 min read
SQL HAVING Clause with Examples
The HAVING clause was introduced in SQL to allow the filtering of query results based on aggregate functions and groupings, which cannot be achieved using the WHERE clause that is used to filter individual rows. In simpler terms MSSQL, the HAVING clause is used to apply a filter on the result of GROUP BY based on the specified condition. The condit
4 min read
How to Use NULL Values Inside NOT IN Clause in SQL?
In this article, we will see how to use NULL values inside NOT IN Clause in SQL. NULL has a special status in SQL. It represents the absence of value so, it cannot be used for comparison. If you use it for comparison, it will always return NULL. In order to use NULL value in NOT IN Clause, we can make a separate subquery to include NULL values. Mak
2 min read
How to Escape Square Brackets in a LIKE Clause in SQL Server?
Here we will see, how to escape square brackets in a LIKE clause. LIKE clause used for pattern matching in SQL using wildcard operators like %, ^, [], etc. If we try to filter the record using a LIKE clause with a string consisting of square brackets, we will not get the expected results. For example: For a string value Romy[R]kumari in a table. If
2 min read
How to Custom Sort in SQL ORDER BY Clause?
By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted. In this article let us see how we can custom sort in a table using order by using MSS
2 min read
Frame Clause in SQL
Prerequisites: Window functions in SQL FRAME clause is used with window/analytic functions in SQL. Whenever we use a window function, it creates a 'window' or a 'partition' depending upon the column mentioned after the 'partition by' clause in the 'over' clause. And then it applies that window function to each of those partitions and inside these p
4 min read
SQL | INTERSECT Clause
The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset returned by the INTERSECT statement will be the intersection of the data sets of the two SELECT statements. In simple words, the INTERSECT statement will return only those rows which will be common to both of the SELECT statements. Syntax: SELECT column1 , column2
2 min read
SQL | OFFSET-FETCH Clause
OFFSET and FETCH Clause are used in conjunction with SELECT and ORDER BY clause to provide a means to retrieve a range of records. OFFSET The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records. Note: OFFSET can only be used with ORDER BY clause. It cannot be used o
2 min read
How to Solve Must Appear in the GROUP BY Clause in SQL
SQL error “Must Appear in GROUP BY Clause” is one of the most common SQL errors encountered by database developers and analysts alike. This error occurs when we attempt to run queries that include grouping and aggregation without taking proper account of the structure of the SELECT statement. In this article, we’ll look at the source of the SQL GRO
5 min read
Difference between Where and Having Clause in SQL
WHERE and HAVING clauses play an important role in refining the result set of a query. While both clauses are used for filtering data, they serve distinct purposes and are applied at different stages of query execution. Let's explore the details of each and their differences with examples. WHERE ClauseWHERE Clause is used to filter the records from
2 min read
Difference between order by and group by clause in SQL
ORDER BY clause is used to sort the result set either in ascending or descending order and GROUP BY the statement is used to group the rows that have the same value and it is used with aggregate functions like SUM(), AVG(), MAX(), etc. In this article, we are going to discuss both of these clauses in detail. Let's start with Order by first. Order B
3 min read
Parameterize SQL IN Clause
The 'IN' clause in SQL filters query results based on a specified list of values. It retrieves rows where a particular column matches any value within a provided list. Parameterizing the 'IN' clause adds flexibility to SQL queries, allowing for dynamic values, enhanced security, and efficient code reuse. Before delving into the specifics of "Parame
4 min read
Article Tags :