Home > Mobile >  How do I check whether the result row of given mysql query exceeds a certain number without using co
How do I check whether the result row of given mysql query exceeds a certain number without using co

Time:01-28

Now my problem is to know a mysql query will fetch result which exceeds a certain row count (like 5000 rows). I know it can use select * ... limit 5001 to replace count() for performance optimization in terms of time effeciency, but it still return 5001 row of records which is totally useless in my scenario, becasue all I want is a sample 'yes/no' answer. Is there any better approach? big thanks ! ^_^

CodePudding user response:

The accepted answer in the link provided by Devsi Odedra is substantially correct but if you don't want a big result set select a column into a user defined variable and limit 1 for example

MariaDB [sandbox]> select * from dates limit 7;
 ---- ------------ 
| id | dte        |
 ---- ------------ 
|  1 | 2018-01-02 |
|  2 | 2018-01-03 |
|  3 | 2018-01-04 |
|  4 | 2018-01-05 |
|  5 | 2018-01-06 |
|  6 | 2018-01-07 |
|  7 | 2018-01-08 |
 ---- ------------ 

SELECT SQL_CALC_FOUND_ROWS ID INTO @ID FROM DATES WHERE ID < 5 LIMIT 1;
SELECT FOUND_ROWS();  

 -------------- 
| FOUND_ROWS() |
 -------------- 
|            4 |
 -------------- 
1 row in set (0.001 sec)

CodePudding user response:

SELECT 1 FROM tbl
    WHERE ... ORDER BY ...
    LIMIT 5000, 1;

will give you either a row or no row -- This indicates whether there are more than 5000 row or not. Wrapping it in EXISTS( ... ) turns that into "true" or "false" -- essentially the same effort, but perhaps clearer syntax.

Caution: If the WHERE and ORDER BY are used but cannot handled by an INDEX, the query may still read the entire table before getting to the 5000 and 1.

When paginating, I recommend

LIMIT 11, 1

to fetch 10 rows, plus an indication that there are more rows.

  •  Tags:  
  • Related