A page shows counts for each status (requested, planned, completed). One count() query per status adds up as statuses grow.
Count queries
31
67% lower
and it stays 1 as statuses grow
Eloquent performanceLesson 5 of 28
Several totals? One query with conditional aggregates.
1 min readIntermediateLesson
A page shows counts for each status (requested, planned, completed). One count() query per status adds up as statuses grow.
Get every total in one query by putting a condition inside count().
$requested = Feature::where('status', 'requested')->count();
$planned = Feature::where('status', 'planned')->count();
$completed = Feature::where('status', 'completed')->count();
// one query per status
$statuses = Feature::toBase()
->selectRaw("count(case when status = 'requested' then 1 end) as requested")
->selectRaw("count(case when status = 'planned' then 1 end) as planned")
->selectRaw("count(case when status = 'completed' then 1 end) as completed")
->first();
One query no matter how many statuses you add.
Count queries
31
67% lower
and it stays 1 as statuses grow
In SQL:
select count(case when status = 'requested' then 1 end) as requested,
count(case when status = 'planned' then 1 end) as planned,
count(case when status = 'completed' then 1 end) as completed
from features
count() skips NULLs. The CASE returns 1 when the row matches and NULL when it doesn't, so each column only counts its own status.
toBase() returns a plain object of numbers instead of a Feature model. first() because the result is one row.count(*) filter (where status = 'requested') is neater and can be faster.
All three status badges (44 / 6 / 10) come from the single conditional-aggregate query at the top of the Queries tab, so the page runs 3 queries in total.
Several totals? One query with conditional aggregates.
Why does count(case when ... then 1 end) only count matching rows?
✓ Answer
Non-matching rows produce NULL, and count() ignores NULLs.