Home  >  Article  >  Database  >  Which is More Performant: PDO::rowCount() or COUNT(*) With or Without an Index?

Which is More Performant: PDO::rowCount() or COUNT(*) With or Without an Index?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 07:14:02353browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn