YOUR AD GOES HERE

How to use CASE inside SUM in SQL for conditional counts | Ep 16

Published 08, Nov 2026

VisualSQL


Description:
COUNT(CASE WHEN ... THEN 1 ELSE 0 END) looks right, but it counts every row.

What does this return?

SELECT COUNT(
CASE WHEN dept = 'IT'
THEN 1 ELSE 0 END
)
FROM employees;

The fix:
SELECT SUM(CASE WHEN dept = 'IT' THEN 1 ELSE 0 END) AS it
FROM employees;

How SQL runs it, step by step:
1. FROM employees: FROM loads six employees.
2. SELECT SUM(CASE WHEN dept = 'IT' THEN 1 ELSE 0 END) AS it: Swap COUNT for SUM. SUM adds the column, so the zeros add nothing. Zero plus one plus one, and so on, gives three.

Takeaway: Count by condition with SUM(CASE). Or COUNT with no ELSE. Never COUNT a 0.

Follow @visual.sql101 for a new visual SQL lesson every Monday, Wednesday and Friday.

#sql #learnsql #sqlforbeginners #sqlcase #dataanalyst #sqlinterview #interviewprep #shorts

Releted More Videos

  • Sorry!!! Nothing to show

You May Also Like

YOUR AD GOES HERE

YOUR AD GOES HERE