Forum Moderators: open

Message Too Old, No Replies

MySQL, getting "Rows Examined"

         

csdude55

7:01 am on Nov 21, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I notice in my slow log that it includes this:

# Query_time: 6.225232 Lock_time: 0.000122 Rows_sent: 21 Rows_examined: 8366

Is there a way for me to retrieve that "Rows examined" value without doing a separate query? There obviously MUST be a way for it to be in the log, but how do I find it? Specifically in PHP, and I'm using MySQLi procedural style.

Note that this isn't the number of rows returned, but the number of rows examined. So when there are 8366 potential rows but I have LIMIT 21, I want to show the 8366.

federicorazzoli

8:13 pm on Dec 15, 2021 (gmt 0)



You can use mysqli::$affected_rows:
[php.net...]

In stored procedures and triggers, you can use ROW_COUNT():
[mariadb.com...]

robzilla

10:34 pm on Dec 15, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You can use mysqli::$affected_rows:

This will return the number of rows in the result set, not the rows examined. As noted in the PHP docs, it "works like mysqli_num_rows() for SELECT statements."

I assume you're trying to avoid having to do a count of all rows in addition to the limited query. This has always felt inefficient to me as well (especially because a count can be very slow), but I've not yet found another way to do it, although in some cases it's possible and helpful (i.e. much faster) to store a count somewhere and update that when necessary. So if you're counting private messages, cache the number of messages and update it whenever a message is added or removed.

I think "examined rows" may also take into account any rows from joined tables, but I haven't checked.

csdude55

11:57 pm on Dec 15, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I assume you're trying to avoid having to do a count of all rows in addition to the limited query.

Zackly :-/ There are several scripts where I find myself doing a second query just to get the count, and since the data is in the error log then it must exist somewhere! But I guess it's just not accessible to the user for some reason.

federicorazzoli

12:11 am on Dec 16, 2021 (gmt 0)



I've read too fast sorry.

But the number of examined rows is not what you're looking for. It's a number of rows internally read by MySQL while running the query, no matter if they're relevant or not. That information helps you find out why a query is slow, but it doesn't do what you want.

What you're looking for is SQL_CALC_FOUND_ROWS + FOUND_ROWS(), but it is deprecated in MySQL 8 (not in MariaDB):
[dev.mysql.com...]

Why did they deprecate it? Because it's a hack, and it's not more efficient than running two queries.