COUNT(id) vs. COUNT(*) in MySQL

前端 未结 3 1022
醉梦人生
醉梦人生 2020-12-03 07:17

Is there a difference between the following queries, assuming there is a primary field \'id\' in the table (as in speed, etc)?

SELECT COUNT(id) 
  FROM table         


        
相关标签:
3条回答
  • 2020-12-03 07:25

    COUNT(*) with InnoDB is slower than COUNT(ID) because InnoDB doesn’t cache the row count.

    On the other hand, with MyISAM, count(*) query would be faster and return result in no time because MyISAM maintains the count of rows.

    It is easy for MyISAM to maintain the count of rows since only one transaction executes at any time, because MyISAM does table-level locking. After a transaction commits, it is easy for MyISAM to update the row count for a table (taking into account inserts and deletes done by the transaction) before the next transaction starts.

    However, with InnoDB, which uses row-level locking, there are multiple concurrently executing (and as-yet uncommitted) transactions. To ensure consistency, each transaction has to see the table (including the number of rows in the table) as of the beginning of the transaction, plus its own changes. Thus the number of rows in the table is obviously potentially different for each concurrent transaction. Therefore there is no single “correct” total number of rows at any given time (unless there are no update transactions running). With multiple concurrent transactions, it is not really possible to cache the total number of rows in a table.

    0 讨论(0)
  • 2020-12-03 07:28

    I know the question is about MySQL, but for what it's worth, count(*) is recommended for Oracle: which goes to show that this is database specific (see comment above from BalusC). Since a lot of databases (MS-SQL, MySQL) have information schema tables that hold various types of metadata, there are bound to be differences if one syntax is simply looking up a readily-available value, and another is going straight to the table. At the end of day: try different options, an see what EXPLAIN is telling you is going on behind the scenes.

    0 讨论(0)
  • 2020-12-03 07:37

    Count(*) Count(Ename) Can show diff outputs because Ename is not a column with Not null constraint and it surely be having some null values Which are not being counted.

    Hope it helps..!

    0 讨论(0)
提交回复
热议问题