LIMIT clause in SQL is used to restrict the number of rows returned by a query. It is particularly useful when you want to retrieve only a specific number of records from a large dataset, such as the top 5 highest-paid employees or the first 10 students with the highest scores.
Key Points
- Restricting Rows: The
LIMITclause specifies the maximum number of rows to return. - Offset Support: You can use the
OFFSETkeyword to skip a specified number of rows before starting to return rows. - Applicability: The
LIMITclause is commonly used with theSELECTstatement. - Performance: Using
LIMITcan improve query performance by reducing the amount of data processed and returned.
Syntax
column1, column2, ...: The columns you want to retrieve.table_name: The table from which to retrieve data.number_of_rows: The maximum number of rows to return.
Syntax with OFFSET
offset_value: The number of rows to skip before starting to return rows.
Examples
Suppose you have a table namedEmployees that stores employee details.
Table: Employees
To retrieve the top 5 highest-paid employees:
Using LIMIT with OFFSET
TheOFFSET keyword is used to skip a specified number of rows before starting to return rows. For example, to retrieve the next 5 highest-paid employees after the top 5:
Practical Use Case
Suppose you have a table namedStudents that stores student details, and you want to retrieve the top 3 students with the highest percentages.
Table: Students
Combining LIMIT with WHERE Clause
You can combine theLIMIT clause with the WHERE clause to filter and restrict the number of rows returned. For example, retrieve the top 2 students from Tamil Nadu with the highest percentages.
Key Takeaways
- The
LIMITclause restricts the number of rows returned by a query. - It is often used with
ORDER BYto retrieve the top or bottom records. - The
OFFSETkeyword skips a specified number of rows before returning results. - Combining
LIMITwithWHEREallows you to filter and restrict rows simultaneously. - Using
LIMITimproves query performance by reducing the amount of data processed.