Guides 220 pages, all live in your browser
Tableau functions to SQL
Pick a function. Each page runs the Tableau formula on the xmetric engine and the SQL on DuckDB over the same sample rows, shows that both return the same numbers, and shows the tempting SQL that does not.
Convert a whole formula
Paste any calculated field and get SQL, checked on rows in your browser.
Level of detail
FIXED, INCLUDE and EXCLUDE: aggregates at a grain other than the view, and how filters reach them.
- FIXEDA FIXED LOD is computed before dimension filters, so it still sees every row.
- Distinct customers per regionTableau { FIXED [Region] : COUNTD([Customer]) } on every team row, and its SQL join.
- Exclude all view dimensionsTableau EXCLUDE of every view dimension gives the grand total on each mark.
- EXCLUDE with a dimension filterEXCLUDE runs after dimension filters, so { EXCLUDE [Team] : SUM([Revenue]) } adds only the teams left in the view.
- First invoice dateTableau { FIXED [Customer] : MIN([Date]) } is a customer's first invoice date on every row.
- Fixed customer lifetime revenueTableau { FIXED [Customer] : SUM([Revenue]) } is a customer's lifetime revenue on every row.
- Fixed grand totalTableau { FIXED : SUM([Revenue]) } puts the grand total on every mark.
- Fixed region totalTableau { FIXED [Region] : SUM([Revenue]) } repeats each region total on every team.
- FIXED with a context filterMake Region = North a context filter and { FIXED : SUM([Revenue]) } drops to North's 650.
- FIXED with a dimension filterWith Region filtered to North, { FIXED : SUM([Revenue]) } still returns 1,650, the total of every region.
- Invoice count per customerCount each customer's invoices with a Tableau FIXED COUNTD, and the SQL that matches.
- Largest customer revenueThe largest customer per region with Tableau MAX({ INCLUDE [Customer] : SUM([Revenue]) }), as a SQL subquery.
- Mean customer revenueThe average customer per region with Tableau AVG({ INCLUDE [Customer] : SUM([Revenue]) }), as a SQL subquery.
- Mean team revenueThe average team per region with Tableau AVG({ INCLUDE [Team] : SUM([Revenue]) }), as a SQL subquery.
- Median customer revenueThe median customer per region with Tableau MEDIAN({ INCLUDE [Customer] : SUM([Revenue]) }), as a SQL subquery.
- Nested largest customer per regionA nested Tableau FIXED that finds the largest customer total per region.
- Nested smallest customer per regionA nested Tableau FIXED that finds the smallest customer total per region.
- Region share of fixed totalEach region's share of a Tableau FIXED grand total, as a SQL window.
- Region total excluding teamTableau { EXCLUDE [Team] : SUM([Revenue]) } drops Team from the view grain to give region totals.
- Smallest customer revenueThe smallest customer per region with Tableau MIN({ INCLUDE [Customer] : SUM([Revenue]) }), as a SQL subquery.
- Team share within regionTeam revenue over its region total with Tableau EXCLUDE, as a SQL window.
Table calculations
Calculations across the marks in the view: running totals, ranks, windows, lookups.
- Centered three-period averageA centered three-month average in Tableau is WINDOW_AVG with offsets -1 and 1.
- Dense rank within regionDense-ranking months within each region in Tableau is RANK_DENSE computed along Month.
- Difference from first periodDifference from the first month in Tableau is SUM minus LOOKUP at FIRST().
- Difference from last periodDifference from the last month in Tableau is SUM minus LOOKUP at LAST().
- Difference from previous periodMonth-over-month difference in Tableau is SUM minus LOOKUP at -1.
- FIRSTTableau FIRST() counts back to the first mark of the partition.
- INDEXTableau INDEX() numbers the marks of each partition from 1.
- LASTTableau LAST() counts forward to the last mark of the partition.
- LOOKUPTableau LOOKUP reads another mark at an offset.
- Next period revenueNext month's sales in Tableau is LOOKUP with offset 1.
- Percent change from previous periodPercent change from the previous month in Tableau divides the change by ABS of the prior value.
- Percent of regional totalPercent of regional total in Tableau is SUM over TOTAL computed along Month.
- PREVIOUS_VALUETableau PREVIOUS_VALUE reads this calculation's own result on the previous mark.
- RANKTableau RANK gives ties the same rank and skips the next.
- RANK_DENSETableau RANK_DENSE gives ties the same rank without gaps.
- RANK_MODIFIEDTableau RANK_MODIFIED gives ties the lowest shared rank (1, 2, 2, 4).
- RANK_PERCENTILETableau RANK_PERCENTILE scales ranks from 0 to 1, ascending by default.
- RANK_UNIQUETableau RANK_UNIQUE gives every mark its own rank, ties included.
- Regional mark position fractionA mark's position as a fraction of its region in Tableau is INDEX() / SIZE().
- Regional min-max normalizationMin-max normalization per region in Tableau uses WINDOW_MIN and WINDOW_MAX.
- Regional revenue z-scoreA z-score per region in Tableau uses WINDOW_AVG and WINDOW_STDEV.
- Regional running totalA running total per region in Tableau is RUNNING_SUM computed along Month.
- Running percent of totalRunning percent of total in Tableau is RUNNING_SUM over WINDOW_SUM.
- Running revenue productA running product in Tableau is SUM times PREVIOUS_VALUE(1).
- RUNNING_AVGTableau RUNNING_AVG is the average of the marks so far.
- RUNNING_COUNTTableau RUNNING_COUNT counts the non-null marks so far.
- RUNNING_MAXTableau RUNNING_MAX is the highest mark so far.
- RUNNING_MINTableau RUNNING_MIN is the lowest mark so far.
- RUNNING_STDEVTableau RUNNING_STDEV is the sample standard deviation of the marks so far.
- RUNNING_STDEVPTableau RUNNING_STDEVP is the population standard deviation of the marks so far.
- RUNNING_SUMTableau RUNNING_SUM is a cumulative total over the marks in the view.
- RUNNING_VARTableau RUNNING_VAR is the sample variance of the marks so far.
- RUNNING_VARPTableau RUNNING_VARP is the population variance of the marks so far.
- SIZETableau SIZE() is the number of marks in the partition.
- TOTALTableau TOTAL is the aggregate over the whole partition, on every mark.
- Two-period moving averageA two-month moving average in Tableau is WINDOW_AVG with offsets -1 and 0.
- WINDOW_AVGTableau WINDOW_AVG averages the marks in a window, by default the whole partition.
- WINDOW_CORRTableau WINDOW_CORR is the Pearson correlation of two measures across the marks in a window.
- WINDOW_COUNTTableau WINDOW_COUNT counts the non-null marks in a window.
- WINDOW_COVARTableau WINDOW_COVAR is the sample covariance of two measures across the marks in a window.
- WINDOW_COVARPTableau WINDOW_COVARP is the population covariance of two measures across the marks in a window.
- WINDOW_MAXTableau WINDOW_MAX is the highest mark in a window, by default the whole partition.
- WINDOW_MEDIANTableau WINDOW_MEDIAN is the median of the marks in a window.
- WINDOW_MINTableau WINDOW_MIN is the lowest mark in a window, by default the whole partition.
- WINDOW_PERCENTILETableau WINDOW_PERCENTILE interpolates a percentile across the marks in a window.
- WINDOW_STDEVTableau WINDOW_STDEV is the sample standard deviation of the marks in a window.
- WINDOW_STDEVPTableau WINDOW_STDEVP is the population standard deviation of the marks in a window.
- WINDOW_SUMTableau WINDOW_SUM adds up the marks in a window, by default the whole partition.
- WINDOW_VARTableau WINDOW_VAR is the sample variance of the marks in a window.
- WINDOW_VARPTableau WINDOW_VARP is the population variance of the marks in a window.
Aggregates
SUM, AVG, COUNTD and the statistics, including how they treat nulls.
- ATTRTableau ATTR returns a value when a group has only one, and * when it has several.
- AVGTableau AVG is the mean of the non-null values; in SQL it is avg().
- CORRTableau CORR is the Pearson correlation of two fields, from -1 to 1; in SQL it is corr().
- COUNTTableau COUNT counts non-null values, not rows; in SQL it is count(column).
- COUNTDTableau COUNTD counts distinct non-null values; in SQL it is count(DISTINCT x).
- COVARTableau COVAR is the sample covariance of two fields; in SQL it is covar_samp().
- COVARPTableau COVARP is the population covariance of two fields; in SQL it is covar_pop().
- MAXTableau MAX is an aggregate with one argument and a row-level comparison with two.
- MEDIANTableau MEDIAN averages the two middle values of an even group; in SQL it is median() or quantile_cont.
- MINTableau MIN is an aggregate with one argument and a row-level comparison with two.
- PERCENTILETableau PERCENTILE interpolates between values, like quantile_cont.
- STDEVTableau STDEV is the sample standard deviation; in SQL it is stddev_samp().
- STDEVPTableau STDEVP is the population standard deviation; in SQL it is stddev_pop().
- SUMTableau SUM adds the non-null values of a field; in SQL it is sum().
- VARTableau VAR is the sample variance; in SQL it is var_samp().
- VARPTableau VARP is the population variance; in SQL it is var_pop().
Dates
Date parts, truncation, arithmetic and parsing, with week starts and ISO calendars.
- DATETableau DATE turns a string or date-time into a date and reads many formats.
- DATEADDTableau DATEADD adds days, months or years to a date and clamps month ends.
- DATEDIFFTableau DATEDIFF counts date boundaries, not elapsed time.
- DATENAMETableau DATENAME returns a date part as text: "March", "Sunday", "29".
- DATEPARSETableau DATEPARSE reads a date string with an ICU format such as dd/MM/yyyy; DuckDB uses strptime codes.
- DATEPARTTableau DATEPART returns one part of a date as an integer.
- DATETIMETableau DATETIME turns a string or date into a date-time and reads many formats.
- DATETRUNCTableau DATETRUNC rounds a date down to the start of a year, month or week.
- DAYTableau DAY returns the day of the month as an integer; in DuckDB it is day().
- ISDATETableau ISDATE tests whether a string is a valid date in any format it recognises.
- ISOQUARTERTableau ISOQUARTER groups ISO weeks into quarters 1 to 4.
- ISOWEEKTableau ISOWEEK returns the ISO 8601 week, 1 to 53, with Monday starts; in DuckDB it is week().
- ISOWEEKDAYTableau ISOWEEKDAY numbers the days Monday 1 to Sunday 7; in DuckDB it is isodow().
- ISOYEARTableau ISOYEAR returns the ISO 8601 week-based year; in DuckDB it is isoyear().
- MAKEDATETableau MAKEDATE builds a date from year, month and day, and rolls invalid days over.
- MAKEDATETIMETableau MAKEDATETIME joins a date and the time of a second value into a date-time.
- MONTHTableau MONTH returns the month of a date as an integer from 1 to 12; in DuckDB it is month().
- NOWTableau NOW returns the current date and time; in DuckDB it is now() or current_timestamp.
- QUARTERTableau QUARTER returns the calendar quarter of a date, 1 to 4; in DuckDB it is quarter().
- TODAYTableau TODAY returns the current date with no time; in DuckDB it is current_date.
- WEEKTableau WEEK numbers weeks from 1 January with Sunday starts, not ISO weeks.
- YEARTableau YEAR returns the calendar year of a date as an integer; in DuckDB it is year().
Logic
IF, CASE, IIF and null tests.
- CASETableau CASE matches a value against a list and returns the first match; SQL CASE is the same.
- ELSEIFTableau ELSEIF adds a test to an IF chain, and the first true test wins; in SQL it is another WHEN.
- IFTableau IF returns the value of the first true test; in SQL it is CASE WHEN.
- IFNULLTableau IFNULL returns its first argument unless it is null; in SQL it is coalesce().
- IIFTableau IIF returns null when the test is null, unless you pass a fourth argument.
- INTableau IN tests whether a value is in a list; DuckDB IN matches.
- ISNULLTableau ISNULL tests whether a value is null; in SQL it is x IS NULL.
Numbers
Rounding, division, logarithms, trigonometry and null handling.
- ABSTableau ABS returns a number's absolute value; in SQL it's abs().
- ACOSTableau ACOS returns an angle in radians; in SQL it is acos().
- ASINTableau ASIN returns an angle in radians; in SQL it is asin().
- ATANTableau ATAN returns an arctangent in radians; in SQL it is atan().
- ATAN2Tableau ATAN2(y, x) returns the angle of a point in radians; DuckDB atan2(y, x) matches.
- CEILINGTableau CEILING rounds up to the next integer; in SQL it is ceil().
- COSTableau COS takes an angle in radians; in SQL it is cos().
- COTTableau COT is the cotangent of an angle in radians; DuckDB has cot().
- DEGREESTableau DEGREES converts radians to degrees; in DuckDB it is degrees().
- DIVTableau DIV returns the integer part of a division, cut toward zero; in SQL it is trunc(a / b).
- EXPTableau EXP raises e to a power; in SQL it is exp().
- FLOORTableau FLOOR rounds down to the integer below; in SQL it is floor().
- GREATESTTableau GREATEST returns the largest non-null argument; DuckDB greatest() matches.
- GREATESTPROPAGATENULLTableau GREATESTPROPAGATENULL returns null if any argument is null; DuckDB greatest() skips nulls.
- HEXBINXTableau HEXBINX returns the x of the nearest hexagon centre; SQL needs two candidate grids.
- HEXBINYTableau HEXBINY returns the y of the nearest hexagon centre; SQL needs two candidate grids.
- LEASTTableau LEAST returns the smallest non-null argument; DuckDB least() matches.
- LEASTPROPAGATENULLTableau LEASTPROPAGATENULL returns null if any argument is null; DuckDB least() skips nulls.
- LNTableau LN is the natural log, null for zero and negatives; in DuckDB it is ln() with a guard.
- LOGTableau LOG is base 10 unless you pass a base; DuckDB matches with log10() and log(b, x).
- PITableau PI() returns the constant π; in DuckDB it is pi().
- POWERTableau POWER raises a number to a power, like the ^ operator; in SQL it is pow().
- RADIANSTableau RADIANS converts degrees to radians; in DuckDB it is radians().
- ROUNDTableau ROUND rounds halves away from zero; DuckDB round() matches.
- SIGNTableau SIGN returns -1, 0 or 1; in SQL it is sign().
- SINTableau SIN takes an angle in radians; in SQL it is sin().
- SQRTTableau SQRT returns a square root, null for negatives; in DuckDB use sqrt() with a guard.
- SQUARETableau SQUARE multiplies a number by itself; in SQL write x * x or pow(x, 2).
- TANTableau TAN takes an angle in radians; in SQL it is tan().
- ZNTableau ZN turns a null into zero; in SQL it is coalesce(x, 0).
Strings
Search, slicing, case, trimming and regular expressions.
- ASCIITableau ASCII returns the code of the first character; in DuckDB it is ascii().
- CHARTableau CHAR turns a character code into its character; in DuckDB it is chr().
- CONTAINSTableau CONTAINS tests for a substring; in DuckDB use contains(), not LIKE.
- ENDSWITHTableau ENDSWITH tests how a string ends; in DuckDB it is ends_with().
- FINDTableau FIND returns a 1-based position, or 0 when missing; in DuckDB it is strpos().
- FINDNTHTableau FINDNTH finds the nth occurrence of a substring.
- LEFTTableau LEFT returns the first n characters; DuckDB has left() too.
- LENTableau LEN counts characters; in DuckDB it is length(), not strlen().
- LOWERTableau LOWER lower-cases a string; in DuckDB it is lower().
- LTRIMTableau LTRIM removes leading spaces only; in DuckDB it is ltrim().
- MIDTableau MID returns part of a string from a 1-based start; in DuckDB it is substring().
- PROPERTableau PROPER capitalises each word.
- REGEXP_EXTRACTTableau REGEXP_EXTRACT returns the regex match; in DuckDB it is regexp_extract().
- REGEXP_EXTRACT_NTHTableau REGEXP_EXTRACT_NTH returns the nth capture group; in DuckDB, regexp_extract with a group.
- REGEXP_MATCHTableau REGEXP_MATCH is true when the pattern occurs anywhere; in DuckDB it is regexp_matches().
- REGEXP_REPLACETableau REGEXP_REPLACE replaces every match; DuckDB's regexp_replace needs the 'g' flag.
- REPLACETableau REPLACE swaps every literal occurrence; in DuckDB it is replace().
- RIGHTTableau RIGHT returns the last n characters; DuckDB has right() too.
- RTRIMTableau RTRIM removes trailing spaces only; in DuckDB it is rtrim().
- SPACETableau SPACE returns n spaces; in DuckDB it is repeat(' ', n).
- SPLITTableau SPLIT returns the nth token, counting from the end when negative; in DuckDB it is split_part().
- STARTSWITHTableau STARTSWITH tests how a string begins; in DuckDB it is starts_with().
- TRIMTableau TRIM removes leading and trailing spaces; in DuckDB it is trim().
- UPPERTableau UPPER upper-cases a string; in DuckDB it is upper().
Type conversion
Converting between text, integers and decimals.
User functions
Who is viewing: the functions behind row-level security.
- FULLNAMETableau FULLNAME returns the viewer's display name.
- ISFULLNAMETableau ISFULLNAME tests whether the viewer has a given display name.
- ISMEMBEROFTableau ISMEMBEROF tests the viewer's group membership.
- ISUSERNAMETableau ISUSERNAME tests whether the viewer has a given user name.
- USERDOMAINTableau USERDOMAIN returns the viewer's domain.
- USERNAMETableau USERNAME returns the viewer's user name, the core of row-level security.
Pass-through SQL
SQL passed straight to the data source.
- RAWSQL_BOOLTableau RAWSQL_BOOL sends a true/false SQL expression to the database.
- RAWSQL_DATETableau RAWSQL_DATE passes a date SQL expression to the database and reads the result as a date.
- RAWSQL_DATETIMETableau RAWSQL_DATETIME passes a SQL expression to the database and reads the result as a date-time.
- RAWSQL_INTTableau RAWSQL_INT passes an integer SQL expression to the database.
- RAWSQL_REALTableau RAWSQL_REAL passes a numeric SQL expression to the database.
- RAWSQL_STRTableau RAWSQL_STR passes a string SQL expression to the database.
- RAWSQLAGG_BOOLTableau RAWSQLAGG_BOOL sends an aggregate true/false SQL test to the database, per mark.
- RAWSQLAGG_DATETableau RAWSQLAGG_DATE sends a date aggregate SQL expression to the database, per mark, and reads a date.
- RAWSQLAGG_DATETIMETableau RAWSQLAGG_DATETIME sends a date-time aggregate SQL expression to the database, per mark.
- RAWSQLAGG_INTTableau RAWSQLAGG_INT sends an integer aggregate SQL expression to the database, per mark.
- RAWSQLAGG_REALTableau RAWSQLAGG_REAL sends a numeric aggregate SQL expression to the database, per mark.
- RAWSQLAGG_STRTableau RAWSQLAGG_STR sends a string aggregate SQL expression to the database, per mark.
Spatial
Points, lines and WKT geometry.
- MAKELINETableau MAKELINE draws a line between two points, such as origin to destination.
- MAKEPOINTTableau MAKEPOINT builds a map point from latitude and longitude.
- PARSE_WKTTableau PARSE_WKT reads LINESTRING text into a line with every vertex in order.
- PARSE_WKTTableau PARSE_WKT reads Well-Known Text into a spatial object.
Operators
Arithmetic, comparison and logical operators, and their precedence.
- !=Tableau != is true when values differ and null when either is null.
- %Tableau % returns the remainder with the sign of the dividend; DuckDB % matches.
- ( )Parentheses in a Tableau formula force the order of evaluation, as in SQL.
- *Tableau * multiplies numbers and returns null if either side is null; SQL * matches.
- +Tableau + adds numbers and returns null if either side is null; SQL + is the same.
- + (date)Tableau date + number adds days, fractions included.
- + (string)Tableau + joins strings and returns null if any part is null; in DuckDB use ||.
- -Tableau - subtracts numbers and returns null if either side is null; SQL - matches.
- - (date, date)Tableau date - date returns days, with fractions for date-times.
- - (date, days)Tableau date - number moves a date back by days and keeps the time.
- /Tableau / always returns a decimal, even for two integers; DuckDB / does too.
- <Tableau < compares two values and returns null if either is null.
- <=Tableau <= is true when a is at most b, null if either is null; SQL <= matches.
- <>Tableau <> is the same as !=: true when values differ, null when either is null.
- =Tableau = compares two values and returns null if either is null.
- ==Tableau == is the same comparison as =, null when either side is null.
- >Tableau > compares two values and returns null if either is null; SQL > matches.
- >=Tableau >= is true when a is at least b, null if either is null.
- ^Tableau ^ raises to a power, and negation binds tighter than it; DuckDB ^ agrees.
- ANDTableau AND follows three-valued logic: false wins, then null.
- NOTTableau NOT flips true and false and keeps null; SQL NOT matches.
- ORTableau OR follows three-valued logic: true wins, then null.
- precedenceTableau evaluates operators in a fixed order, from negation to OR.
- unary -Tableau unary minus flips the sign and keeps nulls; SQL -x matches.
Looking for SQL or DAX?
- SQL functionsDuckDB examples you can run
- DAX functionsPower BI measures and their SQL