SQL LIMIT Clause – A Comprehensive Guide

Filed Under: SQL
SQL LIMIT CLAUSE

Hey, readers. In this article, we will be focusing on SQL LIMIT clause in detail.

So, let us begin.


Working of SQL LIMIT clause

Before beginning with the concept of SQL LIMIT, I would want everyone to have a basic understanding of its necessity through the below scenario–

We often come across situations wherein we want only a particular portion of the data records to be displayed out of the entire database. This is when LIMIT clause comes into picture.

The LIMIT clause enables us to display only a particular set of data records as an output. The clause helps us customize the value of the records to be displayed.

Let us now understand the structure of LIMIT clause in the below section.


Syntax of LIMIT clause

The LIMIT clause is used alongside the SELECT query to represent the selected records–

Syntax:

SELECT columns 
from Table
LIMIT offset;

Here, we need to make sure that the offset is always a positive value. The offset represents the limit upto which the records need to the displayed.

Now, we will implement the LIMIT clause in the upcoming section through examples.


Implementing the concept of LIMIT clause in SQL

Let us first create a table and insert records into it using INSERT command as shown below–

create table Info(id integer, Cost integer);
insert into Info(id, Cost) values(1, 100);
insert into Info(id, Cost) values(2, 50);
insert into Info(id, Cost) values(3, 65);
insert into Info(id, Cost) values(4, 97);
insert into Info(id, Cost) values(5, 12);

After creating a table with records, let us now try to represent only the first two records as output setting 2 as the offset for the limit clause.

SELECT * FROM Info
LIMIT 2

Output:

id    Cost
1     100
2     50

Now, in this example, we have clubbed ORDER BY clause with a LIMIT clause to represent the first 3 data records which have been arranged in descending order as shown below–

SELECT * FROM Info
ORDER BY Cost DESC
LIMIT 3

Output:

id        Cost
1         100
4         97
3         65

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

Till then, Stay tuned @ SQL with JournalDev for more such tech-savvy posts and Keep Learning!!


References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages