TechnicalEloquent performance

Eloquent performanceLesson 5 of 28

Calculate Totals Using Conditional Aggregates

Several totals? One query with conditional aggregates.

1 min readIntermediateLesson

Eloquent performance05

The problem

A page shows counts for each status (requested, planned, completed). One count() query per status adds up as statuses grow.

The fix

Get every total in one query by putting a condition inside count().

✕ Instead of this

$requested = Feature::where('status', 'requested')->count();
$planned   = Feature::where('status', 'planned')->count();
$completed = Feature::where('status', 'completed')->count();
// one query per status

✓ Do this

$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();

The benefit

One query no matter how many statuses you add.

Results

Count queries

31

67% lower

and it stays 1 as statuses grow

More detail

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

Why it works

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.

Watch out

  • toBase() returns a plain object of numbers instead of a Feature model. first() because the result is one row.
  • On Postgres, count(*) filter (where status = 'requested') is neater and can be faster.

Frame from lesson 5

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.

Key takeaway

Several totals? One query with conditional aggregates.

Check yourself

Why does count(case when ... then 1 end) only count matching rows?

Reveal answer

✓ Answer

Non-matching rows produce NULL, and count() ignores NULLs.