Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the total number of MySQL queries used per page?

Tags:

php

mysql

count

Is there a built-in function in PHP or MySQL that will provide the total number of MySQL queries used on a page? I've seen on a lot of sites (mainly forums) they have a message at the bottom saying something like "Page generated in 0.6 seconds with 20 queries".

If there's nothing built in then I'll add something to my database class to count them, but it seems like the kind of functionality that would already be available.

like image 844
DisgruntledGoat Avatar asked May 06 '09 16:05

DisgruntledGoat


People also ask

How do I count the number of queries in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query. Note: NULL values are not counted.

How display total number of records in SQL?

The syntax of the SQL COUNT function:COUNT ([ALL | DISTINCT] expression); By default, SQL Server Count Function uses All keyword. It means that SQL Server counts all records in a table. It also includes the rows having duplicate values as well.

Can I do a SUM of a count in MySQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.

What is the most performant way to get the total number of records from a table?

The best way to get the record count is to use the sys. dm_db_partition_stats or sys. partitions system views (there is also sysindexes, but it has been left for the backward compatibility with SQL Server 2000).


1 Answers

Option one would be to pass all of your queries through a wrapper:

function custom_mysql_query($sql)
{
    $GLOBAL['query_count'] ++;
    return mysql_query($sql);
}

Please note that's for illustration only and without error handling, etc.

You could query MySQL for the number of queries run:

mysql> SHOW STATUS LIKE 'Com_select';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_select    | 2     | 
+---------------+-------+
1 row in set (0.00 sec)

You might want to do something like:

SHOW STATUS LIKE 'Com_%';

and then add together Com_select, Com_update, Com_insert and Com_delete

like image 71
James C Avatar answered Oct 04 '22 03:10

James C