i have a query use PDO, count the row first, if row >1 than fetch data
SELECT * WHERE id=:id $row=$SQL->rowCount(); if($row>0){ while($data=$SQL->fetch(PDO::FETCH_ASSOC)){... } } else{echo "no result";}
or
SELECT COUNT(*), * WHERE id=:id $data=fetch(POD::FETCH_NUM); $row=data[0]; if($row>0){ //fetch data } else{echo "no result";}
Which will be better performance?
2nd. question, if I have set up index on id
which one is better COUNT(id)
or COUNT(*)
So, @@RowCount is used to check number of rows affected only after a query execution. But Count(*) is a function, which will return number of rows fetched from the SELECT Query only. After SELECT statement also giving number of row retrived from the query.
PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement. print("Return number of rows that were deleted:\n"); $count = $del->rowCount();
rowcount. This read-only property returns the number of rows returned for SELECT statements, or the number of rows affected by DML statements such as INSERT or UPDATE .
Data manipulation language (DML) statements set the @@ROWCOUNT value to the number of rows affected by the query and return that value to the client. The DML statements may not send any rows to the client. DECLARE CURSOR and FETCH set the @@ROWCOUNT value to 1. EXECUTE statements preserve the previous @@ROWCOUNT.
1st question:
Using count COUNT()
, internally the server(MySQL) will process the request differently.
When doing COUNT()
, the server(MySQL) will only allocate memory to store the result of the count.
When using $row=$SQL->rowCount();
the server (Apache/PHP) will process the entire result set, allocate memory for all those results, and put the server in fetching mode, which involves a lot of different details, such as locking.
Take note that PDOStatement::rowCount()
returns the number of rows affected by the last statement, not the number of rows returned. If the last SQL statement executed by the associated PDOStatement
was a SELECT
statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
On my analysis, if you use COUNT()
, the process would be divided to both MySQL and PHP while if you use $row=$SQL->rowCount();
, the processing would be more for PHP.
Therefore COUNT()
in MySQL is faster.
2nd question:
COUNT(*)
is better than COUNT(id)
.
Explanation:
The count(*)
function in mysql is optimized to find the count of values. Using wildcard means it does not fetch every row. It only find the count. So use count(*)
wherever possible.
Sources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With