@peppy posted a new topic, subject "SQL COUNT vs mysql_num_rows - what is more efficient?". It read:

   Greetings,
    
    I am trying to save resources on my web server and was wondering what will be more efficient when it comes to just counting the number of rows:
    [code] 
        $query = "SELECT COUNT(*) as num FROM table'";
        $total_rows = mysql_fetch_array(mysql_query($query));
        $finalcount = $total_rows['num'];
        
        
    [/code]
    
    or
    [code] 
        $query = "SELECT COUNT(id) as num FROM table'";
        $total_rows = mysql_fetch_array(mysql_query($query));
        $finalcount = $total_rows['num'];
        
        
    [/code]
    
    or
    [code] 
        $count = mysql_num_rows(mysql_query("SELECT id FROM table"));
        
        
    [/code]
    
    I was searching on Google but kept getting conflicting answers. In all cases, “id” is a primary auto-incrementing key that cannot be null. In the first two SQL Count examples, they are the same except “*” vs “id”.
    
    I thought the “id” would use less resources because “*” selects all the data in the table, but I heard this is not the case though.
    
    The last example is 1 line and selects just “id” and counts.
    
    Please explain which one is most effective in terms of saving web hosting resources (both PHP and MySQL resources) and/or load time. If you know of an even more efficient method, please post it!
    
    Thanks

To which @PhilipToop replied

    There is not much difference between the first two. They will probably be reduced to much the same request. The third one requires that a recordset be formed of all the ids in the table, true you are not transferring the recordset over the network but on the database server it is more inefficient.

So @r937 replied

    PhilipToop:
    
    > you are not transferring the recordset over the network
    
    actually, you are 
    
    the 3rd query is by far the worst, IF all you want is the count
    
    however, if you're going to list all rows anyway, as well as the count, then doing an extra query (1st or 2nd) just to get the count is unnecessary overhead

Then @peppy said

    Thanks a lot for the help Philip and r937. I will go ahead and use the 1st method then as this sounds like the more efficient one to use.
    
    Kind regards


{'source': 'discourse', 'url': 'https://www.sitepoint.com/community/t/sql-count-vs-mysql-num-rows-what-is-more-efficient/85754', 'title': 'SQL COUNT vs mysql_num_rows - what is more efficient?', 'views': 4691, 'has_accepted_answer': False, 'word_count': 328, 'like_count': 0, 'reply_count': 1, 'participant_count': 3, 'posts': 4, 'tags': '', 'author': '@peppy', 'participants': '@peppy, @PhilipToop, @r937', 'image_url': [None], 'created_at': '2011-06-12T19:32:48.000Z', 'last_posted_at': '2011-06-12T23:33:57.000Z'}