Home >Database >Mysql Tutorial >Which is More Performant: PDO::rowCount() or COUNT(*) With or Without an Index?
PDO::rowCount vs. COUNT(*) Performance Comparison
Question:
Which performs better in a SELECT query with a row count check: using PDO::rowCount() or including COUNT(*) in the query? Additionally, which option is more efficient when an index is set on the id field?
Answer:
1st Question: Count(*) vs. PDO::rowCount()
Internally, COUNT() in MySQL allocates minimal memory to store only the count result, while PHP processes the entire result set in PDO::rowCount(), allocating memory for all retrieved results. Hence, COUNT() is faster in MySQL.
2nd Question: COUNT(id) vs. COUNT(*) with Index
COUNT() is preferred over COUNT(id) even when an index is set on the id field. This is because COUNT() is optimized to count values quickly, reducing the need to fetch every row, whereas COUNT(id) requires accessing each row, potentially decreasing performance.
The above is the detailed content of Which is More Performant: PDO::rowCount() or COUNT(*) With or Without an Index?. For more information, please follow other related articles on the PHP Chinese website!