Forum Moderators: open

Message Too Old, No Replies

SELECT with LIMIT but counting all matching rows

Is it possible (yet easy) in just one clever query?

         

trafficms

3:57 pm on Apr 20, 2007 (gmt 0)

10+ Year Member



I'm using MySQL and I want to select a bunch of rows that match some criteria.
However I only want to return, say, the 10 first of them.

Is there a clever query that will just return the 10 rows along with a counter of how many matching rows were found?

coopster

2:54 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



MySQL?
Yes, FOUND_ROWS [dev.mysql.com]

trafficms

9:30 pm on Apr 21, 2007 (gmt 0)

10+ Year Member



That was a very short answer, but OK, I managed to look that up in the MySQL reference manual
[dev.mysql.com...]

It appears that you still need two statements though - one with
SELECT SQL_CALC_FOUND_ROWS
to count the number of rows and save that for later and
SELECT FOUND_ROWS()
to get the number.

But at least it means that you don't have to run the whole query again without the LIMIT.

coopster

3:37 am on Apr 24, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



That was a very short answer

What? You wanted me to write it for you? ;)

I figured you might work it out from the link provided and you did. Yes, you have it correct, that is exactly how it works. Nice job.

smagdy

9:28 am on Apr 24, 2007 (gmt 0)

10+ Year Member



Is this way faster than

select count(*) from table1 where ......

then

select field1, field2 from table1 where ...... LIMIT 100

Please i would like to know the answer cause i am already using the method i wrote, so i would change it if your method is better & faster!

Thanks in advance

stajer

4:41 pm on Apr 24, 2007 (gmt 0)

10+ Year Member



I don't know which is faster, but I do know:

SELECT count(*) is slower than SELECT count(ID)

smagdy

5:13 pm on Apr 24, 2007 (gmt 0)

10+ Year Member



SELECT count(*) is slower than SELECT count(ID)!

you mean the opposite?
I think SELECT count(*) is faster than SELECT count(ID)

smagdy

8:24 am on Apr 27, 2007 (gmt 0)

10+ Year Member



So anybody knows if
SELECT SQL_CALC_FOUND_ROWS
SELECT FOUND_ROWS()

Faster than select count(*) then select with LIMIT?

Thanks