Count performance

in Yii2, between
Model::find()->where(…)->count();
and
Model::find()->select([‘COUNT(*) AS value’])->where(…)->asArray()->all()[0][‘VALUE’];

I confuse what is faster.
if get rawSQL, the first case 'll get “Select * from …” query. After it, Yii count the result row;
In the second case, I get query “Select count(*) from…”.

In sql, the second case is better, so what in Yii?
tks :stuck_out_tongue:

if get rawSQL, the first case 'll get “Select * from …” query. After it, Yii count the result row;

It’s not true, Yii generates the “COUNT” statement just like in the second case.

Your analysis of the first case is wrong. You need to profile the actual query that is executed based on that approach and it is not as you describe. Yii is smarter than that!

Say I perform the following
echo Employees::find()->where(['Active' => 0])->count();

If you review the actual query performed is:
SELECT COUNT(*) FROM employees WHERE Active=0

So I’d simply use the simplest syntax to build the query which would be the first case.

Use debug mode to review the logs and see what is actually happening in the background and how you code is actually translated into queries … it can be very informative.