MySQL
MySQL

LIMIT

LIMIT restricts how many rows a query returns, no matter how many rows would otherwise match. SELECT * FROM students LIMIT 1; returns only the first row from the result useful when you only need a sample, or the single top result. LIMIT is especially powerful combined with ORDER BY: SELECT * FROM students ORDER BY age DESC LIMIT 1; returns the single oldest student sort first, then take only the top result. MySQL also supports an offset: LIMIT 5, 10 skips the first 5 matching rows, then returns the next 10. This pattern is the basis of pagination showing "page 2" of results on a website is usually just a LIMIT with a different offset.

Why this matters

  • ·LIMIT stops a query from returning more rows than you actually need.
  • ·Combined with ORDER BY, LIMIT is how you cleanly get the 'top N' or 'most recent N' results.
  • ·LIMIT with an offset is the standard technique behind pagination on real websites.

Common mistakes

  • ·Using LIMIT without ORDER BY gives you 'some' rows, not necessarily the ones you meant, since row order isn't guaranteed.
  • ·A very large offset (LIMIT 100000, 10) can be slow on a big table, since MySQL still has to count through the skipped rows.
  • ·Forgetting LIMIT on an exploratory query against a huge table can return an overwhelming number of rows.
Your codePHP
Expected output
+----+------+-----+
| id | name | age |
+----+------+-----+
| 2  | Sara | 17  |
+----+------+-----+
1 row in set

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Frequently asked questions

It returns only the first row of the result, discarding everything else that would have matched.

Practice questions

Question 1

Write a query that returns only the 2 youngest students.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Question 2

Write a query that skips the first student (by age, oldest first) and returns the next one.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Quick check

Just for this topic answer honestly, then check yourself.

1 / 3

What does LIMIT control?