SQL SELECT limit clause

The LIMIT clause is commonly used in SQL SELECT statements to restrict the number of rows returned from a query. It allows you to specify the maximum number of rows to be displayed in the result set.

Syntax

The syntax for using the LIMIT clause in SQL is as follows:

SELECT column1, column2, ...
FROM table_name
LIMIT number_of_rows;

The table_name is the name of the table from which you want to fetch the data. column1, column2, ... represents the columns you want to retrieve. The number_of_rows specifies the maximum number of rows to be returned.

Example

Consider a table employees with columns id, name, and salary. We can use the LIMIT clause to retrieve a subset of records as follows:

SELECT id, name, salary
FROM employees
LIMIT 10;

The above query selects the first 10 rows from the employees table and returns only the id, name, and salary columns.

Pagination

The LIMIT clause is often used in conjunction with other keywords like OFFSET to implement pagination. This allows you to retrieve a specific range of rows from a result set.

To fetch records starting from a specific offset, you can use the OFFSET keyword. For example, to retrieve the 11th to 20th rows in the employees table, you can use:

SELECT id, name, salary
FROM employees
LIMIT 10 OFFSET 10;

This query skips the first 10 rows and then returns the next 10 rows from the employees table.

Conclusion

The LIMIT clause is a powerful tool in SQL statements that allows you to control the number of rows returned. By using it wisely in your SELECT statements, you can efficiently manage the amount of data retrieved and implement pagination in your applications.

#SQL #SELECT #LIMIT #Pagination