Shafizadeh
Shafizadeh

Reputation: 10340

fetchColumn() vs rowCount() just for check existing

I need to check a row exists or not. and here is my query:

$smt = $dbh->prepare("SELECT EXISTS(SELECT 1 FROM table WHERE col = ? LIMIT 1)");
$smt->execute(array($var));

Now I want to know which one is more faster: (I use PDO)

if($stmt->fetchColumn()){}
if($stmt->rowCount()){}

And again, I don't want to fetch any row, I just want to check existing ...

Upvotes: 3

Views: 981

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157893

Doesn't matter.

If you're selecting only one row, both methods will be equally fast.

BTW, your query is superfluous.

SELECT 1 FROM table WHERE col = ? LIMIT 1

is more than enough

Well, regarding speed difference. Given your code, in five minutes i will find several spots which are hundred times less efficient/slower than this negligible difference. Just to show you that your concern about single trifle operation is superfluous. Interpreted web languages are not about microsecond optimizations.

Your real concern should be index for the col field. As long as you have it, your code is fast either way. If not - no PDO function will be able to make it fast.

But if you still want a choice, I'd stick to fetchColumn(), as it seems answer the question more directly

Upvotes: 2

Related Questions