Conditional COUNT in SQL

Level 393 keystrokes

COUNT with CASE counts only rows that meet a condition.

SQL code

1SELECT
-- COUNT(*) counts every row of the table
2 COUNT(*) AS total,
-- CASE gives 1 for active rows and NULL otherwise (no ELSE)
-- COUNT(expr) skips NULLs, so only active users are counted
3 COUNT(CASE WHEN status = 'active' THEN 1 END) AS active
-- Both counts come from one pass over the users table
4FROM
5 users;

Output

+-------+--------+
| total | active |
+-------+--------+
|    10 |      7 |
+-------+--------+
1 row in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • '× 2
  • (× 2
  • )× 2
  • ,× 1
  • ;× 1
  • *× 1
  • =× 1

More SQL examples at level 3

← SQL typing practice