Different ways to count record numbers in MySQL

6

There's a difference in performance if you do:

//seleciona todos os itens da tabela
$cmd = "SELECT * FROM produtos";
$produtos = mysql_query($cmd);

//conta o total de itens
$total = mysql_num_rows($produtos);

instead of executing a query: SELECT count(*) FROM produtos to count the number of occurrences in the bank? NOTE: disregard the use of mysql / mysqli

    
asked by anonymous 23.01.2015 / 14:42

4 answers

16

The basic technique for counting records is:

SELECT COUNT(*) FROM tabela

It has two reasons:

  • This will only traffic the count (a single short line) and not all the data in the table. This makes a huge difference.
  • And it's still optimized in MySQL. It will not even do any counting operation in this case, it takes the cache number it already holds with this information.

I've already done a question about this.

    
23.01.2015 / 14:46
4

There is. When you run SELECT * FROM produtos , in terms of performance you have to wait for the database to load all the data and deliver it to PHP. Then PHP will count the data. The second case% with% of the bank itself gives only the amount of data in the bank. Much more efficient in terms of counting.

    
23.01.2015 / 14:46
4

Answer based on Ricardo's comment on Big's answer. If you want to return a limit of records and know the total as you used: SELECT count(nome),duracao FROM produtos , alternatively I think in this question you can find some help.

mysql> SELECT SQL_CALC_FOUND_ROWS duracao FROM produtos LIMIT 10;
mysql> SELECT FOUND_ROWS();

The output will be something like the array below - note that it returns the total of records regardless of the limit reported in the query:

Array(
    [0] => 50
    [1] => Array(
            [0] => Array( [duracao] => 1 )
            [1] => Array( [duracao] => 2 )
            ...
        )
)
    
23.01.2015 / 17:11
3

Absolutely. Imagine the memory used to get 1000 products just to know the quantity. Running a count will return only one record, representing a large improvement in memory consumption.

    
23.01.2015 / 14:47