MySQL: SELECT LIMIT Statement

MySQL select limit statement

In this guide, we will explain how to use the SELECT LIMIT statement in MySQL with syntax and examples.

Description

The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.

Syntax

The syntax for the SELECT LIMIT statement in MySQL is:

SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count;

Parameters or Arguments

expressionsThe columns or calculations that you wish to retrieve.tablesThe tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.WHERE conditionsOptional. The conditions that must be met for the records to be selected.ORDER BY expressionOptional. It is used in the SELECT LIMIT statement so that you can order the results and target those records that you wish to return.LIMIT row_countSpecifies a limited number of rows in the result set to be returned based on row_count. For example, LIMIT 10 would return the first 10 rows matching the SELECT criteria. This is where sort order matters so be sure to use an ORDER BY clause appropriately.

Example – Using LIMIT keyword

Let’s look at how to use a SELECT statement with a LIMIT clause in MySQL.

For example:

SELECT contact_id, last_name, first_name
FROM contacts
WHERE website = 'adglob.in'
ORDER BY contact_id DESC
LIMIT 5;

This MySQL SELECT LIMIT example would select the first 5 records from the contacts table where the website is ‘adglob.in’. Note that the results are sorted by contact_id in descending order so this means that the 5 largest contact_id values will be returned by the SELECT LIMIT statement.

If there are other records in the contacts table that have a website value of ‘adglob.in’, they will not be returned by the SELECT LIMIT statement in MySQL.

If we wanted to select the 5 smallest contact_id values instead of the largest, we could change the sort order as follows:

SELECT contact_id, last_name, first_name
FROM contacts
WHERE website = 'adglob.in'
ORDER BY contact_id ASC
LIMIT 5;

Now the results would be sorted by contact_id in ascending order, so the first 5 smallest contact_id records that have a website of ‘adglob.in’ would be returned by this SELECT LIMIT statement. No other records would be returned by this query.

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply