How to Write Code in Tableau
Thinking about “writing code” in Tableau can be a little confusing, because it’s not what you might expect if you’re picturing lines of Python or JavaScript. Tableau is primarily a visual, drag-and-drop platform, but to unlock its true power, you’ll need to work with its own flexible formula language. This guide will walk you through what “coding” really means in Tableau and give you practical, step-by-step examples for creating powerful calculations that turn raw data into meaningful insights.
Demystifying "Code" in Tableau
First, let's clear up a common misconception. When data analysts talk about writing code in Tableau, they aren't typically referring to a traditional programming language. Instead, they’re talking about creating custom formulas and logical expressions using functions and operators built directly into the Tableau platform. The experience is much closer to writing formulas in an Excel or Google Sheets cell than building an application.
These formulas allow you to go far beyond the basic fields in your data source. You can create new metrics, segment your customers, perform complex comparisons, and manipulate data to answer very specific business questions. This “code” lives inside what Tableau calls Calculated Fields.
There are three main types of calculations you'll frequently use, each with a different purpose:
- Basic Calculations: Simple formulas that operate at the row level or as a basic aggregation, similar to work you'd do in a spreadsheet.
- Level of Detail (LOD) Expressions: More advanced calculations that let you compute aggregations at a different level of granularity than what's currently displayed in your visualization.
- Table Calculations: Special calculations that operate only on the data in your current view, making them perfect for computing things like running totals or percent of total.
Let's walk through how to create and use each of these, starting with the most fundamental.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Calculated Fields: Your Everyday Workhorse
Calculated fields are the foundation of writing formulas in Tableau. Think of them as creating a new column in your dataset that's derived from your existing data. You can perform math, manipulate text, work with dates, and use logical statements like IF/THEN to create new dimensions or measures.
Example: Calculating Profit Margin
Imagine you have a dataset from your e-commerce store with Sales and Profit for a list of transactions. You want to see the Profit Margin for each of your product categories, which isn't a field in your original data. You can easily create it.
Here’s how to build that calculated field step-by-step:
- In the Data pane on the left, right-click anywhere in the blank space and select Create Calculated Field.
- A calculation editor window will open. First, give your new field a name. Let's call it
Profit Margin. - In the large text box, you'll write your formula. To calculate profit margin, the formula is profit divided by sales. In Tableau, this looks like:
- Let’s break that down.
[Profit]and[Sales]refer to the fields from your data source. We wrap them inSUM()because in analytics, you almost always want to aggregate your measures before performing mathematical operations. This ensures you’re calculating the total profit margin, not an average of row-level margins. - Click OK once the "The calculation is valid" message appears at the bottom.
You’ve just "written code" in Tableau! Your new Profit Margin field now appears in the Data pane. You can drag it into your view just like any other field. To make it a percentage, right-click the new field, go to Default Properties > Number Format..., and select Percentage.
Tips for Working with Text and Dates
Calculations aren't just for numbers. They're incredibly useful for cleaning and manipulating text and date fields, too.
- Combining text fields: You can join fields together with the
+operator. For example, to create aFull Namefield fromFirst NameandLast Name: - Calculating duration between dates: The
DATEDIFFfunction is fantastic for finding the time between two dates. For instance, to calculate shipping time: - Using logical statements: You can use
IF/THEN/ELSElogic to create custom groupings. For instance, you could create a field calledDeal Sizebased on the sales amount:
Unlocking Deeper Insights with LOD Expressions
Level of Detail (LOD) expressions are where Tableau’s calculation capabilities start to feel truly powerful. They allow you to compute values at a level of detail that is independent of the dimensions in your view. This sounds complicated, but a simple example makes it clear.
Imagine your chart shows the total Sales for each Sub-Category. But what if you wanted to also show the total sales for the entire Category that each sub-category belongs to on the same chart? An LOD expression can calculate the total category sales and "fix" that value to every row within that category, letting you make direct comparisons.
There are three types of LOD expressions: FIXED, INCLUDE, and EXCLUDE. We’ll focus on FIXED, as it’s the most common and straightforward.
FIXED: Calculating at a Specific Level
A FIXED LOD expression calculates a value for a specific dimension you define, regardless of what else is happening in your view.
Example: Finding a Customer's First Purchase Date
Let’s say you want to analyze customer cohorts based on when they made their first purchase. You have a list of all transactions, but you need a new field that stores, for every customer, the date of their very first order.
- Create a new calculated field and name it
Customer First Order Date. - Enter the following
FIXEDLOD expression: - Let’s deconstruct this formula:
- Click OK.
Now you have a new dimension, Customer First Order Date. Even if a customer has 50 orders in your dataset, every single one of those rows will now have a new field containing the single date of that customer's very first purchase. You can now use this to analyze how behavior differs between customers acquired in 2021 versus those acquired in 2023.
Using Table Calculations for Relative Analysis
The final type of “code” you’ll use in Tableau are Table Calculations. Unlike other calculations that operate on the entire dataset, table calculations work only on the numbers currently in your visualization (the “table”). This makes them perfect for analyzing data relative to other marks in the view, such as calculating a running total, percent of total, or a moving average.
Tableau makes common table calculations very easy with its "Quick Table Calculation" feature.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Example: Calculating a Running Total of Sales
Imagine a line chart showing your monthly Sales over time. To see your cumulative growth, you can add a running total with just a few clicks.
- Create a line chart with
SUM(Sales)on the Rows shelf and a monthlyOrder Dateon the Columns shelf. - Right-click the
SUM(Sales)pill in the Rows shelf. - In the context menu, hover over Quick Table Calculation and select Running Total.
Your line chart instantly transforms to show the cumulative sum of sales month after month. No formula writing required! But what if you wanted something more custom?
Writing a Custom Table Calculation
You can also write your own table calculations for more advanced use cases, like finding the percent difference from the previous month.
Example: Month-Over-Month Sales Growth
Using the same monthly sales chart, let's create a field that shows the percentage growth from the prior month.
- Create a new calculated field and name it
MoM Growth. - Enter the following formula:
- The star of this formula is the
LOOKUP()function. It's a special table calculation function that "looks up" a value in another row in the table. LOOKUP(SUM([Sales]), -1)tells Tableau to get theSUM(Sales)from the previous partition in the view (the-1part means "go back one step").- The whole formula subtracts the previous month's sales from the current month's sales (giving us the change) and then divides by the previous month's sales to get the growth rate.
- Drag this new field onto your view and format it as a percentage. Now you have a powerful month-over-month growth metric.
Best Practices for Writing Tableau "Code"
As your analyses become more complex, keeping your calculations organized and understandable is crucial. Here are a few tips:
- Use Comments: You can add comments to your formulas by starting a line with
//. Use this to explain complex logic to teammates or your future self. For example:// This LOD finds the first purchase date for cohort analysis. - Keep It Simple: Avoid nesting calculations too deeply if possible. It’s often clearer to break complex logic into two or three separate calculated fields that build on each other.
- Get Organized: The Data pane can get cluttered fast. Right-click on a field and select Group by > Folder to create folders and organize your new calculated fields (e.g., "LOD Expressions," "Key Metrics").
- Use the Editor's Help: The Tableau calculation editor will auto-complete field-names and functions. It also has a function reference on the right. If you’re ever unsure, that’s a great place to look.
Final Thoughts
While Tableau is known for its user-friendly interface, learning to “code” with calculated fields, LOD expressions, and table calculations is what separates a beginner from an expert user. These tools empower you to customize your data, build sophisticated metrics, and ultimately answer nuanced business questions that simply aren't possible with drag-and-drop alone.
Of course, mastering Tableau’s formula language takes time, and sometimes you just need to get a specific business answer fast without wrestling with the right calculation syntax. For those moments, we created Graphed. Our platform allows you to connect all your data sources and simply ask questions in plain English, like "What was our month-over-month sales growth this year?" Graphed instantly handles the complex logic and builds the dashboard for you, turning hours spent reporting into a 30-second conversation.
Related Articles
Facebook Ads for Real Estate Agents: The Complete 2026 Strategy Guide
Master Facebook ads for real estate agents in 2026. Learn targeting, ad formats, budgets, and creative best practices to generate more leads.
Facebook Ads for Movers: The Complete 2026 Strategy Guide
Learn how to run Facebook ads for movers that actually generate booked jobs—not just clicks. Budget, targeting, funnel strategy, and creative that converts.
Facebook Ads for Web Designers: The Complete 2026 Strategy Guide
Learn how to use Facebook ads to attract high-value web design clients in 2026. A complete 7-step system for agencies and freelancers.