Reputation: 65
It has long been known that PDO does not support COUNT(*) and a query like below would fail as it doesn't return any affected rows,
$q = $dbc -> prepare("SELECT COUNT(*) FROM table WHERE id = ?");
$q -> execute(array($id));
echo $q -> rowCount();
Doing some research I found that you can also get the row count using other methods of count and not using count at all, for example the following query is supposed be the same as above but will return correct for PDO,
$q = $dbc -> prepare("SELECT 1 FROM table WHERE id = ?");
$q -> execute(array($id));
echo $q -> rowCount();
There are various sources on the internet claiming that;
"SELECT COUNT(*)
"SELECT COUNT(col)
"SELECT 1
Are all the same as each other (with a few differences) so how come using mysql which PDO cannot properly return a true count, does
"SELECT 1
work?
Methods of count discussion
Why is Select 1 faster than Select count(*)?
Upvotes: 3
Views: 5300
Reputation: 8546
Best way I think to test if a line exist in your database is to perform.
SELECT 1 FROM table WHERE condition LIMIT 1
If it find a row it will stop and tell you there is a line. If it don't and you have an index on your where clause column it will also goes very fast to see there are none available.
Upvotes: 0
Reputation: 3368
PDO does not support COUNT(*)
WTF? Of course PDO supports COUNT(*)
, you are using it the wrong way.
$q = $dbc->prepare("SELECT COUNT(id) as records FROM table WHERE id = ?");
$q->execute(array($id));
$records = (int) $q->fetch(PDO::FETCH_OBJ)->records;
If you are using a driver other than MySQL, you might have to test rowCount
first, like this.
$records = (int) ($q->rowCount()) ? $q->fetch(PDO::FETCH_OBJ)->records : 0;
Upvotes: 6
Reputation: 157887
Oh. You are confusing everything.
COUNT(*)
you shouldn't use rowcount at all, as it just makes no sense. You have to retreive the query result instead.COUNT(*)
and COUNT(col)
(and even COUNT(1)
) are the same and the only proper way to get count of records when you need no records themselves.COUNT is an aggregate function, it counts rows for you. So, it returns the result already, no more counting required. Ad it returns just a scalar value in the single row. Thus, using rowcount
on this single row makes no sense
SELECT 1
is not the same as above, as it selects just literal 1
for the every row found in the table. So, it will return a thousand 1s
if there is a thousands rows in your database. So, rowcount will give you the result but it is going to be an extreme waste of the server resources.
there is a simple rule to follow:
If you need the count of rows - request count of rows. Not a thousand of 1s to count them later.
Sounds sensible?
Upvotes: 6