【MySQL】Limiting the Range of Data with LIMIT

本記事にはプロモーションが含まれています。

軽くて安いのに大容量!カフェ作業も捗る!プログラミングに最適なPCをお探しなら【おすすめはこちら

Large websites often contain massive amounts of data, such as tens or even hundreds of thousands of customer records.

Imagine the challenge if a web system were to display all this data at once – it would be overwhelming.

I can’t keep up with the scrolling!

This is where the ‘LIMIT’ clause becomes handy, as it allows you to restrict the range of data being retrieved.

Take Google search, for example, which typically displays about 10 results per page from a vast number of websites.

In this article, we will explain how to use this ‘LIMIT’ clause.

▼youtube

youtube
【知識0からMySQL】データの検索①データベース作成

youtube
【MySQL】データの検索|WHERE句 LIKE 集計関数 AS GROUP BY ORDER BY LIMIT サブクエリ

Basics of LIMIT in SQL Syntax

The syntax for LIMIT is:

The LIMIT clause allows you to select and retrieve a specific number of rows, starting from a particular ‘start_position’ in the search results.

The Starting Position for LIMIT is ‘0’

When retrieving data using the LIMIT clause, the starting position begins from ‘0’.

For example, if you want to retrieve data starting from the third item, you would write:

となります。

It’s similar to an ‘array’ in Java, isn’t it?

The ‘0’ in LIMIT Can Be Omitted

To retrieve the first five rows of data, you would normally write:

However, the initial ‘0,’ in this statement can be omitted.

Therefore, you can simply use:

This is sufficient to retrieve the first five rows.

Displaying the Information of the Student with the Highest Score

To show the student with the highest score, you can use the following SQL query:

By using ORDER BY along with DESC, the data is sorted in descending order.

Then, by applying LIMIT 1, it retrieves only the top record, which displays the student with the highest score.

Displaying the Name of the Student with the Highest Score

You can use a subquery for this purpose

In this way, you can insert a SELECT statement within the WHERE clause.

A SQL statement within another SQL statement is referred to as a subquery.

Summary: Limiting the Range of Data with MySQL LIMIT

The LIMIT clause is quite a commonly used SQL statement.

By utilizing it, you could create your own search system, or even a system to record and retrieve only the top-rated restaurants based on their scores.

タイトルとURLをコピーしました