SQL reference

SQL COUNT: count rows, values and blanks

In Excel, you'd reach for
fx=COUNTA() for rows, =COUNT() for filled cells, =COUNTIF() with a filter

Three counts that look alike and answer different questions:

  • COUNT(*): how many rows. "How many tickets?"
  • COUNT(closed_at): how many rows where that column isn't blank. "How many tickets are closed?"
  • COUNT(DISTINCT customer_id): how many different values. "How many customers raised a ticket?"

Syntax

COUNT(*)            -- every row
COUNT(column)       -- rows where column has a value
COUNT(DISTINCT col) -- different values
Try itEdit the query, then Run
ticketsclosedstill_opencustomers_with_tickets
52048931293

1 row

Count per group with GROUP BY, and count with a condition with WHERE or SUM(CASE WHEN … THEN 1 ELSE 0 END), the SQL COUNTIF.

Your turn

In one row: total subscriptions, how many are cancelled (have a cancelled_at), and how many different customers have one.

This page on one card

SQL COUNT: count rows, values and blanks: the Excel way (=COUNTA() for rows) and the SQL query, side by side
SQL COUNT: count rows, values and blanks, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows