Alex
Alex

Reputation: 75

How to stop looking in a database after X rows are found?

I have a query to a database that returns a number X of results. I am looking to return a maximum of 10 results. Is there a way to do this without using LIMIT 0,9? I'll use LIMIT if I have to, but I'd rather use something else that will literally stop the searching, rather than look at all rows and then only return the top 10.

Upvotes: 2

Views: 2757

Answers (2)

Marc B
Marc B

Reputation: 360772

If you're not doing any ordering in the query, then "LIMIT 10" will stop after the first 10 matching rows. But as soon as you do ordering, then all the rows will have to be processed, sorted, and THEN the first 10 rows will be returned.

Think of it as the difference between "ok, first 10 people in line can come in", and "ok, the 10 tallest people in line can come in". First one you just open the door and let in 10 people. Second one you have to through the whole line to find the 10 tallest people.

Upvotes: 5

OMG Ponies
OMG Ponies

Reputation: 332681

The LIMIT syntax is the most reliable means of returning a specified number of rows. For ten rows, use:

LIMIT 10

Using LIMIT 0, 9 will return 9 rows, not 10. And there's no benefit to specifying the offset if you're going to start at zero anyways.

Upvotes: 5

Related Questions