Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which MySQL query is effective to get the total number of records

Tags:

php

mysql

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)?

like image 520
Fredy Avatar asked Oct 11 '12 03:10

Fredy


People also ask

How can we get total number of records by query in MySQL?

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

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

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.

Which SQL command is used to get total number of records of a table?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.

How do I count the number of records in SQL?

The COUNT() function returns the number of rows that matches a specified criterion.


2 Answers

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.

like image 90
John Woo Avatar answered Sep 22 '22 16:09

John Woo


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.

like image 28
Grijesh Chauhan Avatar answered Sep 23 '22 16:09

Grijesh Chauhan