How to Add a Formula in Tableau
Trying to create a custom calculation in Tableau, like a profit ratio or grouping sales into "Large" and "Small" buckets? You're in the right place. These custom formulas, known as Calculated Fields, are what transform a good dashboard into a great one by letting you create new data from your existing data sources. This guide will walk you through exactly how to add and use formulas in Tableau, starting with the basics and moving to practical examples you can use today.
What Exactly is a Tableau Formula?
In Tableau, a "formula" is the core of a Calculated Field. Think of a calculated field as a new column or field you create in your data set that doesn't exist in your original data source. Its values are derived from a formula you write, which can range from simple arithmetic to complex logical statements.
Why would you need one? Here are a few common scenarios:
- Segmenting Data: You might want to group customers into tiers based on their total purchase value.
- Creating Ratios: You may need to calculate a profit margin, which involves dividing your profit field by your sales field.
- Transforming Data: Maybe you need to combine a
First Namefield and aLast Namefield into a singleFull Namefield. - Calculating Timelines: You could figure out how many days it took for an order to ship by subtracting the
Order Datefrom theShip Date.
In all these cases, the answer isn't a pre-existing field in your data. You have to create it with a formula.
Creating Your First Calculated Field: A Step-by-Step Guide
Getting started is straightforward. Once you know where the calculation editor is and what it does, you'll be on your way.
1. Open the Calculation Editor
There are two primary ways to open the editor:
- From the Data Pane: In the left-hand sidebar (the Data pane), right-click on an empty space and select "Create Calculated Field." This is the most common method.
- From the Top Menu: Navigate to the "Analysis" menu at the top of the Tableau window and select "Create Calculated Field."
2. Understand the Editor Window
Once you open it, you’ll see the calculation editor. It looks advanced, but it's really just three main parts.
- Field Name: At the very top, you name your calculated field. Be descriptive!
Profit Ratiois much better thanCalculation1. - Formula Box: The large, central text area is where you write your formula. You can either type directly into this box or drag and drop fields and functions into it.
- Functions & Fields Reference: On the right, you have a searchable list of all available functions. You can filter by category (like String, Date, or Logical) and clicking on a function shows you its syntax and a brief description.
Beneath the formula box, you’ll see a small message: “The calculation is valid.” This is a live syntax checker - if you see an error message, it means there’s a mistake in your formula that you need to fix.
Essential Tableau Formula Types (with Practical Examples)
Now for the fun part. Let's build some common and useful calculated fields. You can follow along with these examples using Tableau's sample data sets or apply them to your own data.
Simple Mathematical Operations
The simplest formulas are just like the ones you’d write on paper or in a spreadsheet. Tableau uses standard mathematical operators like + (add), - (subtract), * (multiply), and / (divide).
Example: Calculate Profit Per Item
Imagine you have Sales, Quantity, and Profit fields. If you want to see the profit made on each unit sold, you need a calculated field.
Formula:
[Profit] / [Quantity]
Just create a calculated field, name it "Profit Per Item," and type the formula above. Note: The square brackets [] are used to refer to existing data fields. When you drag this new field into your view, you’ll see the unit profit instead of a simple sum. In Tableau, this might appear as a column in a table or as a measure on a chart.
Logical Functions (IF Statements)
Often, you need to segment your data based on certain conditions. This is where logical functions, especially IF-THEN statements, become invaluable. The syntax is: IF [condition] THEN [value if true] ELSE [value if false] END.
Example: Create Sales Categories
Let's say you want to categorize orders as "Large" or "Small" based on their sales value. Anything over $1,000 is a large order.
Formula:
IF SUM([Sales]) > 1000 THEN "Large Order" ELSE "Small Order" END
You can also create more complex logic with ELSEIF.
Example: Regional Grouping
What if you want to group your US regions into broader "Coastal" and "Central" buckets?
Formula:
IF [Region] = "East" OR [Region] = "West" THEN "Coastal" ELSEIF [Region] = "Central" THEN "Central" ELSE "Other" END
String (Text) Functions
String functions help you manipulate text data, whether it’s cleaning, splitting, or combining fields.
Example: Create a Full Name
If you have separate First Name and Last Name fields, combining them is easy. The + operator works for joining strings together.
Formula:
[First Name] + " " + [Last Name]
This formula concatenates the first name, a space, and the last name into one clean field.
Example: Extract Part of a String
Suppose you have an Order ID field formatted like USA-2023-10025, and you only want to extract the year.
Formula:
SPLIT([Order ID], "-", 2)
The SPLIT function breaks the string by the delimiter (in this case, a hyphen "-") and returns the specified part. Here, we're asking for the second part.
Date Functions
Analyzing performance over time is a core part of business intelligence. Tableau’s date functions are perfect for this.
Example: Calculate Shipping Duration
To find out how long orders take to ship, you can calculate the difference between the Ship Date and the Order Date.
Formula:
DATEDIFF('day', [Order Date], [Ship Date])
The DATEDIFF function finds the difference between two dates. The first argument 'day' tells Tableau to return the result in days. You could also use 'week', 'month', or 'year'.
Example: Isolate the Year from a Date
Sometimes you need to analyze data yearly, but your date field is more granular (e.g., MM/DD/YYYY). You can easily pull just the year.
Formula:
YEAR([Order Date])
Level of Detail (LOD) Expressions
LODs are a more advanced feature, but they are incredibly powerful. They allow you to compute aggregations at a different level of detail than what is currently in your visualization. The most common LOD is FIXED.
Example: Calculate Average Sales per Customer
Imagine you want to create a histogram showing how many customers fall into different annual sales buckets. You first need to find the total sales for each customer, regardless of what other details (like Product Category or Region) are in your view.
Formula:
{ FIXED [Customer ID] : SUM([Sales]) }
This formula tells Tableau: "For each unique Customer ID, calculate the total sum of Sales." The result is a new field where every row for a given customer will have the same value - that customer's total sales. You can then use this new field to create bins for your histogram or segment customers. It's powerful because it stays constant even if you add or remove other dimensions from your chart.
Tips for Cleaner, More Efficient Formulas
- Add Comments: For complex formulas, you can add comments to explain what you're doing. Use two forward slashes
//to start a comment line. This is a lifesaver when you revisit your work months later. - Use Line Breaks: Don't be afraid to break up long formulas into multiple lines, especially
IFstatements. Tableau ignores whitespace, so it makes your logic much easier to read. - Drag and Drop: Instead of typing field names, drag them from the Data pane into the formula box. This prevents typos, which are a common source of errors.
- Check for Validity: Always keep an eye on the little message below the formula box. If it says there’s an error, Tableau often gives a hint about what’s wrong.
Final Thoughts
Writing formulas unlocks the true analytical power of Tableau. By creating calculated fields, you can move beyond simply visualizing your existing data and start building entirely new metrics, segments, and insights. Whether you're doing simple math, writing complex logical statements, or digging into Level of Detail expressions, formulas allow you to ask deeper, more specific questions of your business.
While getting proficient with Tableau's syntax is a powerful skill, it requires a significant time investment to master the calculation editor, chart settings, and dozens of menus. At Graphed, we felt there should be a faster path to getting answers. Instead of learning functions like DATEDIFF or FIXED LODs, we help you connect your data and ask questions in plain English - like, "What was our average shipping time last month?" or "Show me a chart of total sales per customer." We instantly translate your question into a live dashboard, letting you skip the learning curve and go straight to the insight.
Related Articles
How to Enable Data Analysis in Excel
Enable Excel's hidden data analysis tools with our step-by-step guide. Uncover trends, make forecasts, and turn raw numbers into actionable insights today!
What SEO Tools Work with Google Analytics?
Discover which SEO tools integrate seamlessly with Google Analytics to provide a comprehensive view of your site's performance. Optimize your SEO strategy now!
Looker Studio vs Metabase: Which BI Tool Actually Fits Your Team?
Looker Studio and Metabase both help you turn raw data into dashboards, but they take completely different approaches. This guide breaks down where each tool fits, what they are good at, and which one matches your actual workflow.