To get the total number of records, I usually use this query:
$total= mysql_num_rows(mysql_query("SELECT id FROM t_statistic WHERE pageid = $pid"));
but I got one the other query like below:
$data = mysql_fetch_object(mysql_query("SELECT COUNT(id) AS num_rows FROM t_statistic WHERE pageid = $pid"));
$total = $data->num_rows;
Between the two queries above. Which is more quickly and effectively (when the total number of records in the millions)?
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query. Note: NULL values are not counted.
This is by far the most performant option for counting the number of records in a table, as the count is performed on the server. Use the COUNT function in SQL (ODBC/JDBC). Using SQL with the COUNT function is significantly faster than using the ABL to count records in a table prior to OpenEdge Release 12.4.
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
The COUNT() function returns the number of rows that matches a specified criterion.
I prefer the second query. It gives you already the record count, while the first query gives you the list of IDs (not the count), although it has been filtered but there are some cases when ID exist more than once in the table.
The Second query is quick and efficient:
SELECT COUNT(id) AS num_rows FROM t_statistic WHERE pageid = $pid
If you know about query optimisation. The query will only keeps only count in memory while calculating the answer. And directly gives number of rows.
Where as first query:
SELECT id FROM t_statistic WHERE pageid = $pid
Keeps all the selected rows in memory. then number of rows are calculated in further operation.
So second
query is best in both ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With