LIMIT

LIMIT in SQL is a command used to specify the number of records to be retrieved from a database query. It constrains the total count of results returned, particularly useful for creating pagination in applications where large data sets are involved.

Example

SELECT * FROM employees
LIMIT 5;

Output

+-----------+--------+----------+
| EmployeeID | Name | Position |
+-----------+--------+----------+
| 1 | John | Analyst |
| 2 | Sarah | Designer |
| 3 | Jane | Developer|
| 4 | Bob | Analyst |
| 5 | Alice | Designer |
+-----------+--------+----------+

Explanation

The LIMIT keyword in MySQL is used to specify the maximum number of records to return. In this example, the query is selecting all columns from the “employees” table, but only returns the first 5 records.

Example

SELECT * FROM Employees
LIMIT 5;

Output

| EmployeeID | LastName | FirstName |
|------------|----------|-----------|
| 1 | Brown | Julia |
| 2 | Davis | John |
| 3 | Miller | James |
| 4 | Wilson | Patricia |
| 5 | Moore | Linda |

Explanation

In this SQL query, the LIMIT clause is used to constrain the number of rows returned by the query. This specific query will only return the top 5 records from the ‘Employees’ table.

Example

SELECT * FROM Customers
ORDER BY CustomerName
LIMIT 3;

Output

CustomerName | ContactName | Country
-------------|-------------|---------
Alfreds | Maria | Germany
Anas | Ana | Mexico
Around | Thomas | UK

Explanation

Here, the LIMIT clause restricts the output to only the first three records of the Customers table sorted by the ‘CustomerName’ in ascending order.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.