8. MySQL: LIMIT Clause

8. MySQL: LIMIT Clause

The LIMIT clause in MySQL is an essential component of the query language that allows you to constrain the number of results returned by a SELECT statement. This clause is especially useful when dealing with large tables with thousands of records and when you only want to return a certain number of results.

Point To Remember:

The clause has two parameters: the offset number and the limit number. The offset number is the number of rows to skip before returning the results, and the limit number is the maximum number of rows to return.

LIMIT Clause:

For every language, there is a different way to limit the number of records to be returned; in MySQL, we use the LIMIT clause to return a specific number of records.

The clause has two parameters: the offset number and the limit number. The offset number is the number of rows to skip before returning the results, and the limit number is the maximum number of rows to return.

Syntax:

SELECT * 
FROM table_name
WHERE condition1
LIMIT number
offset number;

Example:

We need to get the first five rows of the actor table.

SELECT * 
FROM actor
order actor_id
limit 5;

Output:

As we see, we have the results from actor_id = 1 to actor_id = 5. What if we want five records but want the results starting from actor_id=4?

To achieve the above result, we need to use the offset parameter.

SELECT * 
FROM actor
ORDER BY actor_id
LIMIT 5
OFFSET 3;

Output: So, as we can see, if we use the offset parameter 3, it will tell the system to leave the first three entries and start from the fourth.

We will meet again on Monday! :)

References: https://campus.datacamp.com/courses/intermediate-sql-queries/selecting-columns?ex=8