Sql Limit clause

Sql Limit clause

Blog Bustle 22/03/2020

Sql limit clause is used to fetch 'N' records from one or more sql tables in database where 'N' is a number between 0 and all positive integers. Sql limit clause is used with mysql select query.

Sql Limit clause syntax

SELECT * from table_name LIMIT N ;

Select N records from sql table after M records

SELECT * from table_name LIMIT M,N ;

Note: Here M and N is number between 0 and all positive integers.

Sql Limit clause with Where and Order By clause

Select * from table_name
WHERE condition
ORDER BY column ASC|DESC
LIMIT N ;

Sql Limit clause examples

Let's look at some examples to understand use of Sql Limit clause.

I have employee table.

id name salary country
1 justin 10000 US
2 robin 12000 US
3 jessie 13000 England
4 chris 15000 England

Select 3 records from employee table and sql query will be

SELECT * from employee LIMIT 3;

After running this sql query, result will be

id name salary country
1 justin 10000 US
2 robin 12000 US
3 jessie 13000 England

Select 3 records from employee table in descending order and sql query will be

SELECT * from employee ORDER BY id desc LIMIT 3;

After running this sql query, result will be

id name salary country
4 chris 15000 England
3 jessie 13000 England
2 robin 12000 US

Select 2 records from employee table after first record and sql query will be

SELECT * from employee LIMIT 1,2 ;

After running this sql query, result will be

id name salary country
2 robin 12000 US
3 jessie 13000 England

Find second highest salary from employee table and sql query will be

SELECT salary from employee ORDER BY salary desc LIMIT 1,1 ;

or

SELECT MAX(salary) from employee where salary < (SELECT MAX(salary) from employee) ;

After running this sql query, result will be

MAX(salary)
13000

Find third highest salary from employee table and sql query will be

SELECT salary from employee ORDER BY salary desc LIMIT 2,1 ;

After running this sql query, result will be

salary
12000

After looking at these examples, we can easily use sql limit clause. Hope you like this tutorial.

Other important links

Sql Order By clause

Sql Aggregate Functions

Sql NOT IN operator

Sql IN operator

Sql LIKE Operator

Sql Limit clause searches:

Tags: #mysql