COUNT(expression) returns how many non-null values the group has. In SQL that is count(Sales), never count(*): count(*) counts rows, including rows where the field is empty. To count each value once, use COUNTD.
Updated · Checked on the xmetric engine
What is the syntax?
COUNT(expression)
expression
a field of any type, or a row-level calculation.
Returns an integer: the number of non-null values. 0 when every value is null.
What does it return, and what is the SQL?
Each example runs on the same 12 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
How many lines have a sales value, per region?
Tableau
COUNT([Sales])
SQL (DuckDB)
SELECT Region, count(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
East has five lines and four sales values. North has two lines and no values, so 0.
Region
Result
East
4
North
0
South
1
West
4
✓ The Tableau formula and the SQL return the same 4 rows.
How many lines name a product?
Tableau
COUNT([Product])
SQL (DuckDB)
SELECT Region, count(Product) AS result
FROM input
GROUPBY Region
ORDERBY Region
COUNT works on text too. The two North lines have no product.
Region
Result
East
5
North
0
South
1
West
4
✓ The Tableau formula and the SQL return the same 4 rows.
Where does a straight translation go wrong?
Common mistake
Why does count(*) give a bigger number?
count(*) counts rows. Tableau's COUNT skips nulls, so East is 4, not 5, and North is 0, not 2.
Tableau
COUNT([Sales])
Tempting SQL
SELECT Region, count(*) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, count(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
4
5
4
North
0
2
0
South
1
1
1
West
4
4
4
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
What does COUNT return for a group with only nulls?
North has two order lines and no sales value on either. COUNT returns 0, not null. Each result column is one mark, by Region.
Case
Tableau, then SQL (DuckDB)
East
North
South
West
all-null group
COUNT([Sales])Region, count(Sales)
4
0
1
4
✓ On every row, each Tableau formula and its SQL return the same value.
How do I write it in Snowflake or BigQuery?
The first example, written for each warehouse from its documentation. These are not run here; DuckDB is.
Snowflake
SELECT Region, COUNT(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region