Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

newbie360's avatar

->count() VS select count(*) As count

CaseA:

$count = App\Flight::where('active', 1)->count();

CaseB:

$collections = App\Flight::selectRaw('COUNT(*) AS count')->where('active', 1)->first();
$count = $collections->count;

CaseB should be faster than CaseA ?

0 likes
11 replies
Cronix's avatar

They basically produce the same sql. Count(*) is a bit slower than count(active) or specifying a field, just like select a, b, c is faster than select *.

newbie360's avatar

hmmm just for example, i know the column name, COUNT(id) count

and there is 5,000,000 rows in the collections

so is database return a count number VS use count(the array has 5,000,000 rows)

what the method ->count() used in Laravel , just use count(array()) ?

Cronix's avatar

No, it's selecting the count in the query just as you are in your 2nd one. There's lots of shortcuts in eloquent. Like ->latest() produces "ORDER BY created_at DESC".

Install a tool like laravel debugbar, so you can see all of the actual queries being run. It's quite useful. https://github.com/barryvdh/laravel-debugbar

1 like
newbie360's avatar

i have installed laravel-debugbar, tested on 350,000 rows data

CaseB is faster than CaseA

i think because in CaseA need to use php count(if many elements means need more time)

Cronix's avatar

Then what are the queries both produce? You're 2nd one uses ->first(), which adds "LIMIT 1".

Cronix's avatar

It shows using count in the query, so it's not using php's count(result set). And yes, limit 1 will slightly make it faster as you're explicitly limiting the result set.

newbie360's avatar

so means if i use CaseB is better than use CaseA ?

because i tested on a table has 350,000 rows data only

on another table has 3,200,000 rows, so i want to write a model, but donno which case is more better

Cronix's avatar

It's up to you. There was only a 15ms difference in time, which is pretty trivial. So, it might take ~137ms, which is still pretty trivial. It's not even .25 seconds.

BrandonSurowiec's avatar

The difference seems negligible. I'd use the one that is easiest to work with. (Case A)

Please or to participate in this conversation.