Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

Functions, Operators, & Data Types

This section explains how to use and combine the various data types supported by Tableau. In
addition, this section discusses how to format and use the building blocks of formulas in
Tableau. These parts include literal expressions, functions, and operators.
All of these features are important to understand when you create custom fields such as
calculations.
Data Types
Formatting Literals
Functions
Operators

Data Types
Tableau supports string, date/datetime, number, and boolean data types. These data types are
automatically handled in the proper fashion. However, if you create calculated fields of your
own, you need to be aware of how to use and combine the different data types in formulas. For
example, you cannot add a string to a number. Also, many functions that are available to you
when you define a calculation only work when they are applied to specific data types. For
example, the DATEPART() function can accept only a date/datetime data type as an argument. So,
you can write DATEPART('year',#April 15,2004#) and expect a valid result: 2004. You
cannot write DATEPART('year',"Tom Sawyer") and expect a valid result. In fact, this example
returns an error because "Tom Sawyer" is a string, not a date/datetime.
Note:

Although Tableau will attempt to fully validate all calculations, some data type errors cannot be
found until the query is run against the database. These issues appear as error dialogs at the time
of the query rather than in the calculation dialog box.
The data types supported by Tableau are described below. Refer to Type Conversion to learn
about converting from one data type to another.

STRING
A sequence of zero or more characters. For example, "Wisconsin", "ID-44400", and "Tom
Sawyer" are all strings. Strings are recognized by single or double quotes. The quote character
itself can be included in a string by repeating it. For example, O''Hanrahan.

DATE/DATETIME
A date or a datetime. For example "January 23, 1972" or "January 23, 1972 12:32:00
AM". If you would like a date written in long-hand style to be interpreted as a a date/datetime,
place the # sign on either side of it. For instance, January 23, 1972 is treated as a string data
type but #January 23, 1972# is treated as a date/datetime data type.

BOOLEAN
A field that contains the values TRUE or FALSE. An unknown value arises when the result of a
comparison is unknown. For example, the expression 7 > Null yields unknown. Unknown
booleans are automatically converted to Null

Formatting Literals
When you are using functions you will sometimes want to use literal expressions to represent
numbers, strings, dates, and more. A literal expression signifies a constant value that is
represented as is. For example, you may have a function where your input is a date. Rather
then just type May 1, 2005, which would be interpreted a a string, you would type #May 1,
2005#, which is equivalent to using a date function to convert the argument from a string to a
date (refer to Date Functions ). You can use numeric, string, date, boolean, and Null literals. The
way to format each of these literals is described below.

Numeric Literals
A numeric literal is written exactly like you usually write numbers. If you want to input the
number one as a numeric literal you would type 1. Subsequently, if you want to input the number
3.1415 as a numeric literal you would type 3.1415.

String Literals
A string literal can be written either using single quotations or double quotations. If your string
has a single or double quotation within it, simply type the symbol twice. For example, if you
wanted to input the string cat as a string literal you could type cat or cat. Additionally, if
you want to type the string Shes my friend. as a string literal you could type Shes my
friend. or Shes my friend.

Date Literals
Date literals are signified by the pound symbol (#). If you wanted to input the date August 22,
2005 as a literal date you would type #August 22, 2005#.

Boolean Literals
Boolean literals are written as either true or false. If you wanted to input true as a boolean
literal you would type true.

Null Literals
Null literals are written simply as Null. If you wanted to input Null as a Null literal you would
type Null.

Functions
The calculation functions are grouped into categories. These are the same categories used in the
Calculation dialog box. The aggregate functions such as sum, average, and so on are described in
Aggregations.
Number Functions
String Functions
Date Functions
Type Conversion
Logical Functions
Aggregate Functions
Pass-Through Functions (RAWSQL)
User Functions
Table Calculation Functions

Number Functions
ABS(number)
Returns the absolute value of the given number.
Examples
ABS(-7) = 7
ABS([Budget Variance])

The second example returns the absolute value for all the numbers contained in the Budget
Variance field.

ACOS(number)
Returns the arc cosine of the given number. The result is in radians.
Example
ACOS(-1) = 3.14159265358979

ASIN(number)
Returns the arc sine of a given number. The result is in radians.
Example
ASIN(1) = 1.5707963267949

ATAN(number)
Returns the arc tangent of a given number. The result is in radians.
Example
ATAN(180) = 1.5652408283942

ATAN2(y number, x number)


Returns the arc tangent of two given numbers (x and y). The result is in radians.

Example
ATAN2(2, 1) = 1.10714871779409

COS(number)
Returns the cosine of an angle. Specify the angle in radians.
Example
COS(PI( ) /4) = 0.707106781186548

COT(number)
Returns the cotangent of an angle. Specify the angle in radians.
Example
COT(PI( ) /4) = 1

DEGREES(number)
Converts a given number in radians to degrees.
Example
DEGREES(PI( )/4) = 45.0

EXP(number)
Returns e raised to the power of the given number.
Examples
EXP(2) = 7.389
EXP(-[Growth Rate]*[Time])

LN(number)
Returns the natural logarithm of a number. Returns Null if number is less than or equal to 0.

LOG(number [, base])
Returns the logarithm of a number for the given base. If the base value is omitted, base 10 is
used.

MAX(number, number)
Returns the maximum of the two arguments, which must be of the same type. Returns Null if
either argument is Null. MAX can also be applied to a single field in an aggregate calculation.
Examples
MAX(4,7)
MAX(Sales,Profit)
MAX([First Name],[Last Name])

MIN(number, number)
Returns the minimum of the two arguments, which must be of the same type. Returns Null if
either argument is Null. MIN can also be applied to a single field in an aggregate calculation.
Examples
MIN(4,7)
MIN(Sales,Profit)
MIN([First Name],[Last Name])

PI( )
Returns the numeric constant pi: 3.14159.

POWER(number, power)
Raises the number to the specified power.
Examples
POWER(5,2) = 52 = 25
POWER(Temperature, 2)

You can also use the ^ symbol:

5^2 = POWER(5,2) = 25

Radians (number)
Converts the given number from degrees to radians.
Example
RADIANS(180) = 3.14159

ROUND(number, [decimals])
Rounds numbers to a specified number of digits. The decimals argument specifies how many
decimal points of precision to include in the final result, and it is not required. If decimals is
omitted, number is rounded to the nearest integer.
Example

Tjos example rounds every Sales value to an integer:


ROUND(7.3) = 7ROUND(-6.9) = -7ROUND(123.47,1) = 123.5ROUND(Sales)

Note that some databases such as MS SQL Server, allow specification of a negative length,
where -1 rounds number to 10's, -2 rounds to 100's, and so on. This is not true of all databases to
which you can connect. For example, it is not true of Excel or Access.

SIGN(number)
Returns the sign of a number: The possible return values are -1 if the number is negative, 0 if the
number is zero, or 1 if the number is positive.
Example

If the average of the profit field is negative, then


SIGN(AVG(Profit)) = -1

SIN(number)
Returns the sine of an angle. Specify the angle in radians.
Example
SIN(0) = 1.0SIN(PI( )/4) = 0.707106781186548

SQRT(number)
Returns the square root of a number.
Example
SQRT(25) = 5

SQUARE(number)
Returns the square of a number.
Example
SQUARE(5) = 25

TAN(number)
Returns the tangent of an angle. Specify the angle in radians..
Example
TAN(PI ( )/4) = 1.0

ZN(expression)
Returns the expression if it is not null, otherwise returns zero. Use this function to use zero
values instead of null values.
Example
ZN([Profit]) = [Profit]

String Functions
ASCII(string)
Return the ASCII code for the first character of string.
Example
ASCII('A') = 65

CHAR(number)
Returns the character encoded by the ASCII code number.
Example
CHAR(65) = 'A'

Contains(string, substring)
Returns true if the given string contains the specified substring.
Example
CONTAINS(Calculation, alcu) = true

ENDSWITH(string, substring)
Returns true if the given string ends with the specified substring. Trailing white spaces are
ignored.
Example
ENDSWITH(Tableau, leau) = true

FIND(string, substring, [start])


Returns the index position of substring in string, or 0 if the substring isn't found. If the
optional argument start is added, the function ignores any instances of substring that appear
before the index position start. The first character in the string is position 1.
Examples
FIND("Calculation", "alcu") = 2
FIND("Calculation", "Computer") = 0
FIND("Calculation", "a", 3) = 7
FIND("Calculation", "a", 2) = 2
FIND("Calculation", "a", 8) = 0

LEFT(string, number)
Returns the left-most number of characters in the string.

Example
LEFT("Matador", 4) = "Mata"

LEN(string)
Returns the length of the string.
Example
LEN("Matador") = 7

LOWER(string)
Returns string, with all characters lowercase.
Example
LOWER("ProductVersion") = "productversion"

LTRIM(string)
Returns the string with any leading spaces removed.
Example
LTRIM(" Matador ") = "Matador "

MAX(a, b)
Returns the maximum of a and b (which must be of the same type). This function is usually used
to compare numbers, but also works on strings. With strings, MAX finds the value that is highest
in the sort sequence defined by the database for that column. It returns Null if either argument is
Null.
Example
MAX ("Apple","Banana") = "Banana"

MID(string, start, [length])


Returns the string starting at index position start. The first character in the string is position 1.
If the optional argument length is added, the returned string includes only that number of
characters.

Examples
MID("Calculation", 2) = "alculation"
MID("Calculation", 2, 5) ="alcul"

MIN(a, b)
Returns the minimum of a and b (which must be of the same type). This function is usually used
to compare numbers, but also works on strings. With strings, MIN finds the value that is lowest in
the sort sequence. It returns Null if either argument is Null.
Example
MIN ("Apple","Banana") = "Apple"

REPLACE(string, substring, replacement)


Searches string for substring and replaces it with replacement. If substring is not found,
the string is not changed.
Example
REPLACE("Version8.5", "8.5", "9.0") = "Version9.0"

RIGHT(string, number)
Returns the right-most number of characters in string.
Example
RIGHT("Calculation", 4) = "tion"

RTRIM(string)
Returns string with any trailing spaces removed.
Example
RTRIM(" Calculation ") = " Calculation"

SPACE(number)
Returns a string that is composed of the specified number of repeated spaces.

Example
SPACE(1) = " "

STARTSWITH(string, substring)
Returns true if string stars with substring. Leading white spaces are ignored.
Example
STARTSWITH(Joker, Jo) = true

TRIM(string)
Returns the string with leading and trailing spaces removed. For example, TRIM(" Calculation
") = "Calculation"

UPPER(string)
Returns string, with all characters uppercase.
Example
UPPER("Calculation") = "CALCULATION"

Date Functions
Tableau provides a variety of date functions. Many of the examples use the # symbol with date
expressions. See Formatting Literals for an explanation of this symbol. Additionally, many date
functions use date_part, which is a constant string argument. The valid date_part values that
you can use are:
date_part

Values

'year'

Four-digit year

'quarter'

1-4

'month'

1-12 or "January", "February", and so on

'dayofyear' Day of the year; Jan 1 is 1, Feb 1 is 32, and so on

date_part

Values

'day'

1-31

'weekday'

1-7 or "Sunday", "Monday", and so on

'week'

1-52

'hour'

0-23

'minute'

0-59

'second'

0-60

DATEADD(date_part, increment, date, start_of_week)


Returns an increment added to date. The type of increment is specified in date_part.
The start_of_week parameter is optional. If it is omitted, the start of week is determined by the
data source. See Date Properties for a Data Source.
Example
DATEADD('month', 3, #April 15, 2004#) = #July 15, 2004#

This expression adds three months to the date #April 15, 2004#, and results in #July 15,
2004#.

DATEDIFF(date_part, date1, date2, start_of_week)


Returns the difference between date1 and date2 expressed in units of date_part.
The start_of_week parameter is optional. If it is omitted, the start of week is determined by the
data source. See Date Properties for a Data Source.
Example
DATEDIFF('week', #September 22, 2013#, #September 24, 2013#, 'monday')= 1
DATEDIFF('week', #September 22, 2013#, #September 24, 2013#, 'sunday')= 0

The first expression returns 1 because when start_of_week is 'monday', then September 22 (a
Sunday) and September 24 (a Tuesday) are in different weeks. The second expression returns 2
because when start_of_week is 'sunday' then September 22 (a Sunday) and September 24 (a
Tuesday) are in the same week.

DATENAME(date_part, date, start_of_week)


Returns date_part of date as a string. The start_of_week parameter is optional.
If it is omitted, the start of week is determined by the data source. See Date Properties for a Data
Source.
Examples
DATENAME('year', #April 15, 2004#) = "2004"
DATENAME('month', #April 15, 2004#) = "April"

DATEPARSE(format, string)
Converts a string to a datetime in the specified format. Support for some locale specific formats
is determined by the computer's system settings. Letters that appear in the data and do not need
to be parsed should be surrounded by single quotes (' '). For formats that do not have delimiters
between values (e.g., MMddyy), verify that they are parsed as expected. The format must be a
constant string, not a field value. Returns Null if the data does not match the format.
This function is available for MySQL, Oracle, PostgreSQL, and Tableau Data Extract
connections only. Some formats may not be available for all connections.
Examples
DATEPARSE ("dd.MMMM.yyyy", "15.April.2004") = #April 15, 2004#
DATEPARSE ("h'h' m'm' s's'", "10h 5m 3s") = #10:05:03#

Refer to the Understanding the DATEPARSE Function knowledge base article for more
examples.

DATEPART(date_part, date, start_of_week)


Returns date_part of date as an integer.
The start_of_week parameter is optional. If it is omitted, the start of week is determined by the
data source. See Date Properties for a Data Source.
When the date_part is weekday, the start_of_week parameter is ignored. This is because
Tableau relies on a fixed weekday ordering to apply offsets.
Examples
DATEPART('year', #April 15, 2004#) = 2004

DATEPART('month', #April 15, 2004#) = 4

DATETRUNC(date_part, date, start_of_week)


Truncates the specified date to the accuracy specified by the date_part. This function returns a
new date. For example, when you truncate a date that is in the middle of the month at the month
level, this function returns the first day of the month. The start_of_week parameter is optional.
If it is omitted, the start of week is determined by the data source. See Date Properties for a Data
Source.
Examples
DATETRUNC('quarter', #August 15, 2005#) = July 1, 2005
DATETRUNC('month', #April 15, 2007#) = April 1, 2007

DAY(date)
Returns the day of the given date as an integer.
Example
DAY(#April 12, 2005#) = 12

ISDATE(string)
Returns true if a given string is a valid date.
Example
ISDATE("April 15, 2004") = = true

MAKEDATETIME(date, time)
Returns a datetime that combines a date and a time. The date can be a date, datetime, or a string
type. The time must be a datetime. This function is available only for MySQL connections.
Examples
MAKEDATETIME("1899-12-30", #07:59:00#) = #12/30/1899 7:59:00 AM#
MAKEDATETIME([Date], [Time]) = #1/1/2001 6:00:00 AM#

MAX(expression) or MAX(expr1, expr2)


Usually applied to numbers but also works on dates. Returns the maximum of a and b (a and b
must be of the same type). Returns Null if either argument is Null.
Examples
MAX(#January 1, 2004# ,#March 1, 2004#) = #March 1, 2004#
MAX([ShipDate1], [ShipDate2])

MIN(expression) or MIN(expr1, expr2)


Usually applied to numbers but also works on dates. Returns the minimum of a and b (a and b
must be of the same type). Returns Null if either argument is Null.
Examples
MIN(#January 1, 2004# ,#March 1, 2004#) = #January 1, 2004#
MIN([ShipDate1], [ShipDate2])

MONTH(date)
Returns the month of the given date as an integer.
Example
MONTH(#April 12, 2005#) = 4

NOW( )
Returns the current date and time.
Example
NOW( ) = #5/10/2006 1:08:21 PM#

TODAY( )
Returns the current date.
Example
TODAY( ) = #5/10/2006#

YEAR (date)
Returns the year of the given date as an integer.
Example
YEAR(#April 12, 2005#) = 2005

Type Conversion
The result of any expression in a calculation can be converted to a specific data type. The
conversion functions are STR(), DATE(), DATETIME(), INT(), and FLOAT(). For example, if you
want to cast a floating point number like 3.14 as an integer, you could write INT(3.14). The
result would be 3, which is an integer. The casting functions are described below.
A boolean can be cast to an integer, float, or string, It cannot be cast to a date. True is 1, 1.0, or
1, while False is 0, 0.0 or 0. Unknown maps to Null.

DATE(expression)
Returns a date given a number, string, or date expression.
Examples
DATE([Employee Start Date])
DATE("April 15, 2004") = #April 15, 2004#
DATE("4/15/2004")
DATE(#2006-06-15 14:52#) = #2006-06-15#

Quotation marks are required in the second and third examples.

DATETIME(expression)
Returns a datetime given a number, string, or date expression.
Example
DATETIME(April 15, 2005 07:59:00) = April 15, 2005 07:59:00

FLOAT(expression)
Casts its argument as a floating point number.
Examples
FLOAT(3)

= 3.000

FLOAT([Age])

converts every value in the Age field to a floating point number.

INT(expression)
Casts its argument as an integer. For expressions, this function truncates results to the closest
integer toward zero.
Examples
INT(8.0/3.0)

=2

INT(4.0/1.5)

=2

INT(0.50/1.0)
INT(-9.7)

=0

= -9

When a string is converted to an integer it is first converted to a float and then rounded.

STR(expression)
Casts its argument as a string.
Example
STR([Age])

takes all of the values in the measure called Age and converts them to strings.

Logical Functions

CASE expression WHEN value1 THEN return1 WHEN value2 THEN


return2...ELSE default return END
Use the CASE function to perform logical tests and return appropriate values. CASE is often
easier to use than IIF or IF THEN ELSE. The CASE function evaluates expression, compares it
to a sequence of values, value1, value2, etc., and returns a result. When a value that matches
expression is encountered, CASE returns the corresponding return value. If no match is found,
the default return expression is used. If there is no default return and no values match, then Null
is returned.
Typically, you use an IF function to perform a sequence of arbitrary tests, and you use a CASE
function to search for a match to an expression. But a CASE function can always be rewritten as
an IF function , although the CASE function will generally be more concise.
Many times you can use a group to get the same results as a complicated case function.
Examples
CASE [Region] WHEN "West" THEN 1 WHEN "East" THEN 2 ELSE 3 END
CASE LEFT(DATENAME('weekday',[Order Date]),3) WHEN "Sun" THEN 0 WHEN "Mon"
THEN 1 WHEN "Tue" THEN 2 WHEN "Wed" THEN 3 WHEN "Thu" THEN 4 WHEN "Fri" THEN
5 WHEN "Sat" THEN 6 END

If you need to include numeric comparisons in your conditions, use a nested IF clause. The
CASE function compares strings only. For example, suppose you want to break the values of the
Sales field into three custom categories: one for sales less than 200, one for sales between 200
and 300, and one for sales between 300 and 400. The formula would be:
IF [Sales] < 200 THEN "Low" ELSEIF [Sales] < 300 THEN "Medium" ELSEIF [Sales]
< 400 THEN "High" ELSE "NULL" END

IIF(test, then, else, [unknown])


Use the IIF function to perform logical tests and return appropriate values. The first argument,
test, must be a boolean: either a boolean field in the data source, or the result of a logical
expression using operators (or a logical comparison of AND, OR, or NOT). If test evaluates to
TRUE, then IIF returns the then value. If test evaluates to FALSE, then IIF returns the else
value.
A boolean comparison may also yield the value UNKNOWN (neither TRUE nor FALSE),
usually due to the presence of Null values in test. The final argument to IIF is returned in the
event of an UNKNOWN result for the comparison. If this argument is left out, Null is returned.

Examples
IIF(7>5, "Seven is greater than five", "Seven is less than five")
IIF([Cost]>[Budget Cost], "Over Budget", "Under Budget")
IIF([Budget Sales]!=0,[Sales]/[Budget Sales],0)
IIF(Sales>=[Budget Sales], "Over Cost Budget and Over Sales Budget", "Over
Cost Budget and Under Sales Budget","Under Cost Budget")

IF test THEN value END / IF test THEN value ELSE else END
Use the IF THEN ELSE function to perform logical tests and return appropriate values. The IF
THEN ELSE function evaluates a sequence of test conditions and returns the value for the first
condition that is true. If no condition is true, the ELSE value is returned. Each test must be a
boolean: either be a boolean field in the data source or the result of a logical expression. The
final ELSE is optional, but if it is not provided and there is no true test expression, then the
function returns Null. All of the value expressions must be of the same type.
Examples
IF [Cost]>[Budget Cost] THEN "Over Budget" ELSE "Under Budget" END
IF [Budget Sales]!=0 THEN [Sales]/[Budget Sales] END

IF test1 THEN value1 ELSEIF test2 THEN value2 ELSE else END
Use this version of the IF function to perform logical tests recursively. There is no built-in limit
to the number of ELSEIFvalues you can use with an IF function, though individual databases
may impose a limit on IF function complexity. While an IF function can be rewritten as a series
of nested IIF statements, there are differences in how the expressions will be evaluated. In
particular, an IIF statement distinguishes TRUE, FALSE and UNKNOWN, whereas an IF
statement only worries about TRUE and not true (which includes both FALSE and
UNKNOWN).
Example
IF [Region]="West" THEN 1 ELSEIF [Region]="East" THEN 2 ELSE 3 END

IFNULL(expression1, expression2)
The IFNULL function returns the first expression if the result is not null, and returns the second
expression if it is null.

Example
IFNULL([Proft], 0) = [Profit]

ISDATE(string)
The ISDATE function returns TRUE if the string argument can be converted to a date and FALSE
if it cannot.
Examples
ISDATE("January 1, 2003") = TRUE
ISDATE("Jan 1 2003") = TRUE
ISDATE("1/1/03") = TRUE
ISDATE("Janxx 1 2003") = FALSE

ISNULL(expression)
The ISNULL function returns TRUE if the expression is Null and FALSE if it is not.

MIN(expression) or MIN(expression1,expression2)
The MIN function returns the minimum of an expression across all records or the minimum of
two expressions for each record.

Aggregate Functions
Aggregations and floating-point arithmetic: The results of some aggregations may not always
be exactly as expected. For example, you may find that the Sum function returns a value such as
-1.42e-14 for a column of numbers that you know should sum to exactly 0. This happens because
the Institute of Electrical and Electronics Engineers (IEEE) 754 floating-point standard requires
that numbers be stored in binary format, which means that numbers are sometimes rounded at
extremely fine levels of precision. You can eliminate this potential distraction by using the
ROUND function (see Number Functions) or by formatting the number to show fewer decimal
places.

ATTR(expression)
Returns the value of the expression if it has a single value for all rows. Otherwise returns an
asterisk. Null values are ignored.

AVG(expression)
Returns the average of all the values in the expression. AVG can be used with numeric fields
only. Null values are ignored.

COUNT(expression)
Returns the number of items in a group. Null values are not counted.

COUNTD(expression)
Returns the number of distinct items in a group. Null values are not counted. This function is not
available if you are connected to MS Excel, MS Access, or a text file. You can extract your data
into an extract file to gain this functionality. See Extracting Data.

MAX(expression)
Returns the maximum of an expression across all records. If the expression is a string value, this
function returns the last value where last is defined by alphabetical order.

MEDIAN(expression)
Returns the median of an expression across all records. Median can only be used with numeric
fields. Null values are ignored. This function is not available if you are connected to MS Excel,
MS Access, or a text file. You can extract your data into an extract file to gain this functionality.
See Extracting Data.

MIN(expression)
Returns the minimum of an expression across all records. If the expression is a string value, this
function returns the first value where first is defined by alphabetical order.

PERCENTILE(expression, number)
Returns the percentile value from the given expression corresponding to the specified
number.The number must be between 0 and 1 (inclusive)for example, 0.66, and must be a
numeric constant. This function is available for extracts, Sybase IQ 15.1 (and higher) data
sources, and Oracle 10 (and higher) data sources. You can extract your data into an extract file to
gain this functionality. See Extracting Data.

STDEV(expression)
Returns the statistical standard deviation of all values in the given expression based on a sample
of the population.

STDEVP(expression)
Returns the statistical standard deviation of all values in the given expression based on a biased
population.

SUM(expression)
Returns the sum of all values in the expression. SUM can be used with numeric fields only. Null
values are ignored.

VAR(expression)
Returns the statistical variance of all values in the given expression based on a sample of the
population.

VARP(expression)
Returns the statistical variance of all values in the given expression on the entire population.

Pass-Through Functions (RAWSQL)


These RAWSQL pass-through functions can be used to send SQL expressions directly to the
database, without first being interpreted by Tableau. If you have custom database functions that
Tableau doesnt know about, you can use these pass-through functions to call these custom
functions.
Your database usually will not understand the field names that are shown in Tableau. Because
Tableau does not interpret the SQL expressions you include in the pass-through functions, using
the Tableau field names in your expression may cause errors. You can use a substitution syntax
to insert the correct field name or expression for a Tableau calculation into pass-through SQL.
For example, if you had a function that computed the median of a set of values, you could call
that function on the Tableau column [Sales] like this:
RAWSQLAGG_REAL(MEDIAN(%1), [Sales])
Because Tableau does not interpret the expression, you must define the aggregation. You can use
the RAWSQLAGG functions described below when you are using aggregated expressions.
RAWSQL pass-through functions will not work with published data sources.

RAWSQL Functions
The following RAWSQL functions are available in Tableau.
RAWSQL_BOOL(sql_expr, [arg1], [argN])

Returns a Boolean result from a given SQL expression. The SQL expression is passed directly to
the underlying database. Use %n in the SQL expression as a substitution syntax for database
values.
In the example, %1 is equal to [Sales] and %2 is equal to [Profit].
RAWSQL_BOOL(IIF( %1 > %2, True, False), [Sales], [Profit])
RAWSQL_DATE(sql_expr, [arg1], [argN])

Returns a Date result from a given SQL expression. The SQL expression is passed directly to the
underlying database. Use %n in the SQL expression as a substitution syntax for database values.
In this example, %1 is equal to [Order Date].
Example
RAWSQL_DATE(%1, [Order Date])

RAWSQL_DATETIME(sql_expr, [arg1], [argN])

Returns a Date and Time result from a given SQL expression. The SQL expression is passed
directly to the underlying database. Use %n in the SQL expression as a substitution syntax for
database values. In this example, %1 is equal to [Delivery Date].
Example: RAWSQL_DATETIME(MIN(%1), [Delivery Date])
RAWSQL_INT(sql_expr, [arg1], [argN])

Returns an integer result from a given SQL expression. The SQL expression is passed directly to
the underlying database. Use %n in the SQL expression as a substitution syntax for database
values. In this example, %1 is equal to [Sales].
Example
RAWSQL_INT(500 + %1, [Sales])

RAWSQL_REAL(sql_expr, [arg1], [argN])

Returns a numeric result from a given SQL expression that is passed directly to the underlying
database. Use %n in the SQL expression as a substitution syntax for database values. In this
example, %1 is equal to [Sales]
Example
RAWSQL_REAL(-123.98 * %1, [Sales])

RAWSQL_STR(sql_expr, [arg1], [argN])

Returns a string from a given SQL expression that is passed directly to the underlying database.
Use %n in the SQL expression as a substitution syntax for database values. In this example, %1
is equal to [Customer Name].
Example
RAWSQL_STR(%1, [Customer Name])

RAWSQLAGG_BOOL(sql_expr, [arg1], [argN])

Returns a Boolean result from a given aggregate SQL expression. The SQL expression is passed
directly to the underlying database. Use %n in the SQL expression as a substitution syntax for
database values.
In the example, %1 is equal to [Sales] and %2 is equal to [Profit].
Example: RAWSQLAGG_BOOL(SUM( %1) >SUM( %2), [Sales], [Profit])
RAWSQLAGG_DATE(sql_expr, [arg1], [argN])

Returns a Date result from a given aggregate SQL expression. The SQL expression is passed
directly to the underlying database. Use %n in the SQL expression as a substitution syntax for
database values. In this example, %1 is equal to [Order Date].
Example
RAWSQLAGG_DATE(MAX(%1), [Order Date])

RAWSQLAGG_DATETIME(sql_expr, [arg1], [argN])

Returns a Date and Time result from a given aggregate SQL expression. The SQL expression is
passed directly to the underlying database. Use %n in the SQL expression as a substitution
syntax for database values. In this example, %1 is equal to [Delivery Date].

Example
RAWSQLAGG_DATETIME(MIN(%1), [Delivery Date])

RAWSQLAGG_INT(sql_expr, arg1, argN)

Returns an integer result from a given aggregate SQL expression. The SQL expression is passed
directly to the underlying database. Use %n in the SQL expression as a substitution syntax for
database values. In this example, %1 is equal to [Sales].
Example
RAWSQLAGG_INT(500 + SUM(%1), [Sales])

RAWSQLAGG_REAL(sql_expr, arg1, argN)

Returns a numeric result from a given aggregate SQL expression that is passed directly to the
underlying database. Use %n in the SQL expression as a substitution syntax for database values.
In this example, %1 is equal to [Sales]
Example
RAWSQLAGG_REAL(SUM( %1), [Sales])

RAWSQLAGG_STR(sql_expr, arg1, argN)

Returns a string from a given aggregate SQL expression that is passed directly to the underlying
database. Use %n in the SQL expression as a substitution syntax for database values. In this
example, %1 is equal to [Customer Name].
Example
RAWSQLAGG_STR(AVG(%1), [Discount])

User Functions
Use these user functions to create user filters based on user lists in your data source. For
example, assume you have a view that shows the sales performance for each employee. When
you publish that view, you may want to only allow employees to see their own sales numbers.
You can use the function CURRENTUSER to create a field that returns True if the username of
the person signed in to the server is the same as the employee name in the view. Then when you
filter the view using this calculated field, only the data for the user who is currently signed in is
shown.

FULLNAME( )
Returns the name of the person currently using Tableau. This is the Tableau Server username if
user is signed in otherwise this function returns the Windows username. Use this function to
create calculations that are dependent on the current user.
Example
[Manager]=FULLNAME( )

If the manager Dave Hallsten was signed in, this example would return True only if the Manager
field in the view contained Dave Hallsten. When used as a filter, this calculated field can be used
to create a user filter that only shows data that is relevant to the person signed in to the server.

ISFULLNAME(string)
Returns True if the full name of the person currently using Tableau matches the given string. The
full name for the person currently using Tableau is the Tableau Server or Tableau Online
username if the user is signed in, otherwise its the user's Windows username.
Example
ISFULLNAME(Dave Hallsten)

This example returns true if Dave Hallsten is the current user, otherwise it returns false.

ISMEMBEROF(string)
Returns true if the person currently using Tableau is a member of a group that matches the given
string. If the person currently using Tableau is signed in, the group membership is determined by
groups on Tableau Server. If the person is not signed in, this function returns false.
Example
IF ISMEMBEROF(Sales) THEN Sales ELSE Other END

ISUSERNAME(string)
Returns True if the username of the person currently using Tableau matches the given string. The
username for the person currently using Tableau is the Tableau Server or Tableau Online
username if the user is signed in, otherwise its the Windows username.
Example
ISUSERNAME(dhallsten)

This example returns true if dhallsten is the current user; otherwise it returns false.

USERDOMAIN()
Returns the domain for the person currently using Tableau. This is the Tableau Server domain if
the user is signed in; otherwise it is the Windows domain. Use this function in combination with
other user functions to create calculations that are dependent on the current user and domain.
Example
[Manager]=USERNAME() AND [Domain]=USERDOMAIN()

USERNAME( )
Returns the username of the person currently using Tableau. This is the Tableau Server or
Tableau Online username if the user is signed in; otherwise this function returns the Windows
username. Use this function to create calculations that are dependent on the current user.
Example
[Manager]=USERNAME( )

If the manager dhallsten was signed in, this function would only return True when the Manager
field in the view is dhallsten. When used as a filter this calculated field can be used to create a
user filter that only shows data that is relevant to the person signed in to the server.

able Calculation Functions


Use table calculation functions to customize table calculations. Table Calculations are
computations that are applied to the values in the entire table and are often dependent on the
table structure itself. See Customizing Table Calculations for information about creating and
customizing table calculations.

FIRST( )
Returns the number of rows from the current row to the first row in the partition. For example,
the view below shows quarterly sales. When FIRST() is computed within the Date partition, the
offset of the first row from the second row is -1.

Example

When the current row index is 3, FIRST() = -2.

INDEX( )
Returns the index of the current row in the partition, without any sorting with regard to value.
The first row index starts at 1. For example, the table below shows quarterly sales. When
INDEX() is computed within the Date partition, the index of each row is 1, 2, 3, 4...etc.

Example

For the third row in the partition, INDEX() = 3.

LAST( )
Returns the number of rows from the current row to the last row in the partition. For example,
the table below shows quarterly sales. When LAST() is computed within the Date partition, the
offset of the last row from the second row is 5.

Example

When the current row index is 3 of 7, LAST() = 4.

LOOKUP(expression, [offset])
Returns the value of the expression in a target row, specified as a relative offset from the current
row. Use FIRST() + n and LAST() - n as part of your offset definition for a target relative to the
first/last rows in the partition. If offset is omitted, the row to compare to can be set on the field
menu. This function returns NULL if the target row cannot be determined.
The view below shows quarterly sales. When LOOKUP (SUM(Sales), 2) is computed within the
Date partition, each row shows the sales value from 2 quarters into the future.

Example
LOOKUP(SUM([Profit]), FIRST()+2)

computes the SUM(Profit) in the third row of the

partition.

PREVIOUS_VALUE(expression)
Returns the value of this calculation in the previous row. Returns the given expression if the
current row is the first row of the partition.
Example
SUM([Profit]) * PREVIOUS_VALUE(1)

computes the running product of SUM(Profit).

RANK(expression, ['asc' | 'desc'])


Returns the standard competition rank for the current row in the partition. Identical values are
assigned an identical rank. Use the optional 'asc' | 'desc' argument to specify ascending or
descending order. The default is descending.
With this function, the set of values (6, 9, 9, 14) would be ranked (1, 2, 2, 4).

Nulls are ignored in ranking functions. They are not numbered and they do not count against the
total number of records in percentile rank calculations.
For information on different ranking options, see .
Example

The following image shows the effect of the various ranking functions (RANK, RANK_DENSE,
RANK_MODIFIED, RANK_PERCENTILE, and RANK_UNIQUE) on a set of values. The data
set contains information on 14 students (StudentA through StudentN); the Age column shows the
current age of each student (all students are between 17 and 20 years of age). The remaining
columns show the effect of each rank function on the set of age values.

RANK_DENSE(expression, ['asc' | 'desc'])


Returns the dense rank for the current row in the partition. Identical values are assigned an
identical rank, but no gaps are inserted into the number sequence. Use the optional 'asc' |
'desc' argument to specify ascending or descending order. The default is descending.
With this function, the set of values (6, 9, 9, 14) would be ranked (1, 2, 2, 3).
Nulls are ignored in ranking functions. They are not numbered and they do not count against the
total number of records in percentile rank calculations.
For information on different ranking options, see Rank Calculation.

RANK_MODIFIED(expression, ['asc' | 'desc'])


Returns the modified competition rank for the current row in the partition. Identical values are
assigned an identical rank. Use the optional 'asc' | 'desc' argument to specify ascending or
descending order. The default is descending.
With this function, the set of values (6, 9, 9, 14) would be ranked (1, 3, 3, 4).
Nulls are ignored in ranking functions. They are not numbered and they do not count against the
total number of records in percentile rank calculations.
For information on different ranking options, see Rank Calculation.

RANK_PERCENTILE(expression, ['asc' | 'desc'])


Returns the percentile rank for the current row in the partition. Use the optional 'asc' |
'desc' argument to specify ascending or descending order. The default is ascending.
With this function, the set of values (6, 9, 9, 14) would be ranked (25, 75, 75, 100).
Nulls are ignored in ranking functions. They are not numbered and they do not count against the
total number of records in percentile rank calculations.
For information on different ranking options, see Rank Calculation.

RANK_UNIQUE(expression, ['asc' | 'desc'])


Returns the unique rank for the current row in the partition. Identical values are assigned
different ranks. Use the optional 'asc' | 'desc' argument to specify ascending or descending
order. The default is descending.
With this function, the set of values (6, 9, 9, 14) would be ranked (1, 2, 3, 4).
Nulls are ignored in ranking functions. They are not numbered and they do not count against the
total number of records in percentile rank calculations.
For information on different ranking options, see Rank Calculation.

RUNNING_AVG(expression)
Returns the running average of the given expression, from the first row in the partition to the
current row.
The view below shows quarterly sales. When RUNNING_AVG(SUM([Sales]) is computed within
the Date partition, the result is a running average of the sales values for each quarter.

Example
RUNNING_AVG(SUM([Profit]))

computes the running average of SUM(Profit).

RUNNING_COUNT(expression)
Returns the running count of the given expression, from the first row in the partition to the
current row.
Example
RUNNING_COUNT(SUM([Profit]))

computes the running count of SUM(Profit).

RUNNING_MAX(expression)
Returns the running maximum of the given expression, from the first row in the partition to the
current row.

Example
RUNNING_MAX(SUM([Profit]))

computes the running maximum of SUM(Profit).

RUNNING_MIN(expression)
Returns the running minimum of the given expression, from the first row in the partition to the
current row.

Example
RUNNING_MIN(SUM([Profit]))

computes the running minimum of SUM(Profit).

RUNNING_SUM(expression)
Returns the running sum of the given expression, from the first row in the partition to the current
row.

Example
RUNNING_SUM(SUM([Profit]))

computes the running sum of SUM(Profit)

SIZE()
Returns the number of rows in the partition. For example, the view below shows quarterly sales.
Within the Date partition, there are seven rows so the Size() of the Date partition is 7.

Example
SIZE() = 5

when the current partition contains five rows.

SCRIPT_BOOL
Returns a Boolean result from the specified R expression. The R expression is passed directly to
a running Rserve instance. Use .argn in the R expression to reference parameters (.arg1, .arg2,
etc.).
Examples

In the following example, .arg1 is equal to SUM([Profit]):


SCRIPT_BOOL("is.finite(.arg1)", SUM([Profit]))

The next example returns True for store IDs in Washington state, and False otherwise. This
example could be the definition for a calculated field titled IsStoreInWA.
SCRIPT_BOOL('grepl(".*_WA", .arg1, perl=TRUE)',ATTR([Store ID]))

SCRIPT_INT
Returns an integer result from the specified R expression. The R expression is passed directly to
a running Rserve instance. Use .argn in the R expression to reference parameters (.arg1, .arg2,
etc.).
Examples

In the following example, .arg1 is equal to SUM([Profit]):


SCRIPT_INT("is.finite(.arg1)", SUM([Profit]))

In the next example, k-means clustering is used to create three clusters:


SCRIPT_INT('result <- kmeans(data.frame(.arg1,.arg2,.arg3,.arg4),
3);result$cluster;', SUM([Petal length]), SUM([Petal width]),SUM([Sepal
length]),SUM([Sepal width]))

SCRIPT_REAL
Returns a real result from the specified R expression. The R expression is passed directly to a
running Rserve instance. Use .argn in the R expression to reference parameters (.arg1, .arg2,
etc.).

Examples

In the following example, .arg1 is equal to SUM([Profit]):


SCRIPT_REAL("is.finite(.arg1)", SUM([Profit]))

The next example converts temperature values from Celsius to Fahrenheit.


SCRIPT_REAL('library(udunits2);ud.convert(.arg1, "celsius",
"degree_fahrenheit")',AVG([Temperature]))

SCRIPT_STR
Returns a string result from the specified R expression. The R expression is passed directly to a
running Rserve instance. Use .argn in the R expression to reference parameters (.arg1, .arg2,
etc.).
Examples

In the following example, .arg1 is equal to SUM([Profit]):


SCRIPT_STR("is.finite(.arg1)", SUM([Profit]))

The next example extracts a state abbreviation from a more complicated string (in the original
form 13XSL_CA, A13_WA):
SCRIPT_STR('gsub(".*_", "", .arg1)',ATTR([Store ID]))

TOTAL(expression)
Returns the total for the given expression. For example, the view below shows quarterly sales.
The total within the Date partition is the SUM([Sales]) across all dates.

Example
TOTAL(SUM([Profit]))

computes SUM(Profit) across all database rows in the partition.

WINDOW_AVG(expression, [start, end])


Returns the average of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.
For example, the view below shows quarterly sales. A window average within the Date partition
returns the average sales across all dates.

Example
WINDOW_AVG(SUM[Profit]), FIRST()+1, 0)

computes the average of SUM(Profit) from the

second row to the current row.

WINDOW_COUNT(expression, [start, end])


Returns the count of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.
Example
WINDOW_COUNT(SUM[Profit]), FIRST()+1, 0)

computes the count of SUM(Profit) from the

second row to the current row

WINDOW_MEDIAN(expression, [start, end])


Returns the median of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.

For example, the view below shows quarterly profit. A window median within the Date partition
returns the median profit across all dates.

Example
WINDOW_MEDIAN(SUM[Profit]), FIRST()+1, 0)

computes the median of SUM(Profit) from

the second row to the current row.

WINDOW_MAX(expression, [start, end])


Returns the maximum of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.
For example, the view below shows quarterly sales. A window maximum within the Date
partition returns the maximum sales across all dates.

Example
WINDOW_MAX(SUM[Profit]), FIRST()+1, 0)

computes the maximum of SUM(Profit) from the

second row to the current row.

WINDOW_MIN(expression, [start, end])


Returns the minimum of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.
For example, the view below shows quarterly sales. A window minimum within the Date
partition returns the minimum sales across all dates.

Example
WINDOW_MIN(SUM[Profit]), FIRST()+1, 0)

computes the minimum of SUM(Profit) from the

second row to the current row.

WINDOW_PERCENTILE(expression, number, [start, end])


Returns the value corresponding to the specified percentile within the window. The window is
defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from
the first or last row in the partition. If the start and end are omitted, the entire partition is used.
Example
WINDOW_PERCENTILE(SUM([Profit]), 0.75, -2, 0))

returns the 75th percentile for


SUM(Profit) from the two previous rows to the current row.

WINDOW_STDEV(expression, [start, end])


Returns the sample standard deviation of the expression within the window. The window is
defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from
the first or last row in the partition. If the start and end are omitted, the entire partition is used.

Example
WINDOW_STDEV(SUM[Profit]), FIRST()+1, 0)

computes the standard deviation of


SUM(Profit) from the second row to the current row.

WINDOW_STDEVP(expression, [start, end])


Returns the biased standard deviation of the expression within the window. The window is
defined by means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from
the first or last row in the partition. If the start and end are omitted, the entire partition is used.
Example
WINDOW_STDEVP(SUM[Profit]), FIRST()+1, 0)

computes the standard deviation of


SUM(Profit) from the second row to the current row.

WINDOW_SUM(expression, [start, end])


Returns the sum of the expression within the window. The window is defined by means of
offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or last row
in the partition. If the start and end are omitted, the entire partition is used.
For example, the view below shows quarterly sales. A window sum computed within the Date
partition returns the summation of sales across all quarters.

Example
WINDOW_SUM(SUM[Profit]), FIRST()+1, 0)

computes the sum of SUM(Profit) from the

second row to the current row.

WINDOW_VAR(expression, [start, end])


Returns the sample variance of the expression within the window. The window is defined by
means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or
last row in the partition. If the start and end are omitted, the entire partition is used.
Example
WINDOW_VAR(SUM[Profit]), FIRST()+1, 0)

computes the variance of SUM(Profit) from the

second row to the current row.

WINDOW_VARP(expression, [start, end])


Returns the biased variance of the expression within the window. The window is defined by
means of offsets from the current row. Use FIRST()+n and LAST()-n for offsets from the first or
last row in the partition. If the start and end are omitted, the entire partition is used.

Example
WINDOW_VARP(SUM[Profit]), FIRST()+1, 0)

computes the variance of SUM(Profit) from the

second row to the current row.

Operators
To create calculated fields and formulas, you need to understand the operators supported by
Tableau. This section discusses the basic operators that are available and the order (precedence)
of operations.

+ (addition)
This means addition when applied to numbers and concatenation when applied to strings. When
applied to dates, it can be used to add a number of days to a date. For example,
7 + 3
Profit + Sales
'abc' + 'def' = 'abcdef'
#April 15, 2004# + 15 = #April 30, 2004#

(subtraction)
This means subtraction when applied to numbers and negation if applied to an expression. When
applied to dates, it can be used to subtract a number of days from a date. Hence it can also be
used to calculate the difference in days between two dates. For example,
7 - 3
Profit - Sales
-(7+3) = -10
#April 16, 2004# - 15 = #April 1, 2004#
#April 15, 2004# - #April 8, 2004# = 7

* (multiplication)
This means numeric multiplication. For example, 5 * 4 = 20.

/ (division)
This means numeric division. For example, 20 / 4 = 5.

% (modulo)
This calculates a numeric remainder. For example, 5% 4 = 1.

= =, =, >, <, >=, <=, !=, <>(comparisons)


These are the basic comparison operators that can be used in expressions. Their meanings are as
follows: = = or =(equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less
than or equal to), != and <> (not equal to).
Each operator compares two numbers, dates, or strings and returns a boolean (TRUE or FALSE).
Booleans themselves, however, cannot be compared using these operators. For example,
TRUE=TRUE is not a valid expression. To compare booleans in this way, use the logical operators
AND and OR. For example, TRUE AND TRUE is a valid expression.

^ (power)
This symbol is equivalent to the POWER function. It raises a number to the specified power.
For example:
6^3 = 216

AND
This is a logical operator. An expression or a boolean must appear on either side of it. For
example,
IIF(Profit =100 AND Sales =1000, "High", "Low")

If both expressions are TRUE (i.e., not FALSE and not UNKNOWN), then the result is TRUE. If either
expression is UNKNOWN, then the result is UNKNOWN. In all other cases, the result is FALSE.
If you create a calculation in which the result of an AND comparison is displayed on a
worksheet, Tableau displays TRUE and FALSE. If you would like to change this, use the Format
area in the format dialog.

OR
This is a logical operator. An expression or a boolean must appear on either side of it. For
example,

IIF(Profit =100 OR Sales =1000, "High", "Low")

If either expression is TRUE, then the result is TRUE. If both expressions are FALSE, then the result
is FALSE. If both expressions are UNKNOWN, then the result is UNKNOWN.
If you create a calculation in which the result of an OR comparison is displayed on a worksheet,
Tableau displays TRUE and FALSE. If you would like to change this, use the Format area in the
format dialog. The OR operator employs "short circuit evaluation." This means that if the first
expression is evaluated to be TRUE, then the second expression is not evaluated at all. This can be
helpful if the second expression results in an error when the first expression is TRUE, because the
second expression in this case is never evaluated.

NOT
This is a logical operator. It can be used to negate another boolean or an expression. For
example,
IIF(NOT(Sales = Profit),"Not Equal","Equal")

Precedence
All operators are evaluated in a specific order. For example, 2*1+2 is equal to 4 and not equal to
6. The reason is that the * operator is always evaluated before the + operator.
The following table shows the order in which operators are evaluated. The first line has the
highest precedence. Operators on the same line have the same precedence. If two operators have
the same precedence they are evaluated from left to right in the formula.
Precedence

Operator

(negate)

^ (power)

*, /, %

+,

==, >, <, >=, <=, !=

NOT

AND

OR

Parentheses can be used as needed. Operators that appear within parentheses are evaluated before
those outside of parentheses, starting from the innermost parentheses and moving outward. For
example, (1+ (2*2+1)*(3*6/3)) = 31.

You might also like