0

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 ! ^_^

Ay1ton
  • 1
  • Does this answer your question? [Best way to test if a row exists in a MySQL table](https://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table) – Devsi Odedra Jan 27 '22 at 09:56
  • That link may be useful, but may not be relevant since `OFFSET` is not mentioned. – Rick James Jan 27 '22 at 16:37

2 Answers2

0

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)
P.Salmon
  • 17,104
  • 2
  • 12
  • 19
0
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.

Rick James
  • 135,179
  • 13
  • 127
  • 222