SQL | LIMIT Clause
If there are a large number of tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time.
- 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.
Say we have a relation, Student.
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.
SELECT * FROM Student LIMIT 5;
SELECT * FROM Student ORDER BY Grade DESC LIMIT 3;
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 condition statements.
Using LIMIT along with OFFSET
LIMIT x OFFSET y simply means skip the first y entries and then return the next x entries.
OFFSET can only be used with 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 error.
SELECT * FROM Student LIMIT 5 OFFSET 2 ORDER BY ROLLNO;
Using LIMIT ALL
LIMIT ALL implies no limit.
SELECT * FROM Student LIMIT ALL;
The above query simply returns all the entries in the table.
This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.