MEDIAN(expression) is the middle non-null value of the group. With an even count it is the average of the two middle values, which is what DuckDB's median() and quantile_cont(x, 0.5) return. quantile_disc picks one of the two instead.
Updated · Checked on the xmetric engine
What is the syntax?
MEDIAN(expression)
expression
a numeric field or row-level calculation.
Returns a number: the middle value, interpolated between the two middle values when the count is even. Null when the group has no values.
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.
What is the median sale in each region?
Tableau
MEDIAN([Sales])
SQL (DuckDB)
SELECT Region, median(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
West has 150, 200, 250 and 400: the median is halfway between 200 and 250, 225. East's four values put 100 and 100 in the middle.
Region
Result
East
100
North
null
South
80
West
225
✓ The Tableau formula and the SQL return the same 4 rows.
Where does a straight translation go wrong?
Common mistake
Why does quantile_disc(x, 0.5) return 200 for West?
quantile_disc returns an actual value from the data, the lower middle one. Tableau interpolates, so West's median is 225.
Tableau
MEDIAN([Sales])
Tempting SQL
SELECT Region, quantile_disc(Sales, 0.5) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, median(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
100
100
100
North
null
null
null
South
80
80
80
West
225
200
225
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
What does MEDIAN return for a group with only nulls?
North has two order lines and no sales value on either. MEDIAN returns null there. Each result column is one mark, by Region.
Case
Tableau, then SQL (DuckDB)
East
North
South
West
all-null group
MEDIAN([Sales])Region, median(Sales)
100
null
80
225
✓ 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, MEDIAN(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region