How to Write Queries in Tableau

Cody Schneider••8 min read

Writing your own SQL queries directly in Tableau can feel like unlocking a secret level of data analysis. It lets you go beyond the standard drag-and-drop interface to shape, clean, and organize your data before it even loads into a worksheet. This article will guide you through how to use Custom SQL in Tableau, from writing your first query to leveraging dynamic parameters for interactive dashboards.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

When Should You Use Custom SQL in Tableau?

Tableau's visual data connection editor is incredibly powerful and handles most standard joins and unions perfectly. So why would you opt to write code instead? Custom SQL is the right tool for specific situations where you need more control, performance optimization, or access to advanced database features.

Here are a few common scenarios where Custom SQL shines:

  • Data Pre-Processing: You might need to perform calculations, concatenate fields, or cast data types before Tableau ingests the data. For instance, combining a FirstName and LastName field into a single FullName column is a perfect use case.
  • Complex Joins or Unions: While Tableau handles simple joins, you might have a situation requiring a complex series of joins, subqueries, or a specialized union that’s easier to write in SQL than to build visually.
  • Performance Optimization: Sometimes, you can improve dashboard performance by pushing heavy lifting, like data filtering (using a WHERE clause) or aggregations (using GROUP BY), to the database server. Databases are designed for this kind of work and can often return a smaller, more focused dataset to Tableau faster.
  • Accessing Specific Database Features: Your database might have unique functions (like specific window functions, JSON parsing, or spatial functions) that Tableau's standard interface doesn't expose. Custom SQL allows you to use these native database features directly.
  • Working with Stored Procedures: If your company's data logic is encapsulated in stored procedures, you can connect to them through Tableau, though this often requires specific permissions and database configurations.

Getting Started: Your First Custom SQL Query in Tableau

Ready to try it out? Let's walk through the process of connecting to a data source and running your first query. For this example, we'll assume we're connecting to a SQL database with a table called tbl_Sales.

Step 1: Connect to Your Data Source

First, open Tableau and connect to your data. In the "Connect" pane, select the appropriate connector for your database (e.g., Microsoft SQL Server, PostgreSQL, MySQL).

Enter your server credentials to establish the connection and select the database you want to work with. Once connected, you’ll see a list of tables in the left sidebar of the Data Source page.

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.

Step 2: Find the 'New Custom SQL' Option

Instead of dragging a table onto the canvas like you normally would, look for an option in the left pane called "New Custom SQL."

Drag this item onto the main canvas area. This will open the "Edit Custom SQL" dialog box where you can write or paste your query.

Step 3: Write Your SQL Query

Now it’s time to write the query. This code gets sent directly to your database, so you need to use the SQL dialect specific to that database (e.g., T-SQL for Microsoft SQL Server, PL/pgSQL for PostgreSQL).

Let's write a simple query to pull sales data only for orders from the United States and Canada that are over $50. We'll also combine the customer's first and last name into a single "Customer Name" field.

SELECT
  order_id,
  customer_first_name || ' ' || customer_last_name AS "Customer Name",
  order_date,
  product_category,
  sales_amount
FROM
  tbl_Sales
WHERE
  country IN ('USA', 'Canada') AND sales_amount > 50

Notice we used an alias (AS "Customer Name") to give our new, calculated field a clean name. This is the name that will appear in Tableau.

Step 4: Preview Your Results and Go to Worksheet

After you’ve written your query, click the "Preview Results" button. Tableau will run the query and show you the first few rows of the output. This is an essential step for catching typos or errors in your SQL without having to load the full dataset.

If everything looks correct, click "OK". Tableau now treats the result of your query as its data source. You can rename it, then click "Go to Worksheet" (or "Sheet 1") to start building visualizations with your precisely curated data.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

Making Your Queries Dynamic with Parameters

Writing a static query is useful, but the real power comes from making it interactive. Imagine letting your dashboard users choose which product category to analyze or what sales threshold to set. You can do this with Tableau Parameters.

A parameter is a dynamic placeholder that users can control. You can insert this placeholder into your Custom SQL, allowing users to effectively change the query's behavior on the fly without ever seeing the code.

How to Create and Use a Parameter in Custom SQL

Let's adapt our previous query. Instead of hard-coding the sales amount threshold (> 50), we'll let the user decide with a parameter.

Step 1: Create the Parameter

In the Custom SQL dialog box, look for the "Insert Parameter" dropdown. If you haven't created one yet, select "Create a new parameter...".

Set up your parameter with the following properties:

  • Name: Sales Threshold
  • Data type: Integer
  • Allowable values: Range
  • Set a range of values: Minimum of 1, Maximum of 1000, and a Step size of 10.

Click "OK". You've just created a new parameter.

Step 2: Insert the Parameter into Your SQL

Now, modify your SQL query to use this new parameter. Tableau has a specific syntax for this: <,Parameters.YourParameterName>. Replace the hard-coded 50 with your new parameter.

SELECT
  order_id,
  customer_first_name || ' ' || customer_last_name AS "Customer Name",
  order_date,
  product_category,
  sales_amount
FROM
  tbl_Sales
WHERE
  country IN ('USA', 'Canada') AND sales_amount > <,Parameters.Sales Threshold>,

Now, the value used in the WHERE clause will be whatever the user sets in the "Sales Threshold" parameter.

Step 3: Show the Parameter Control

After you click "OK" and go to your worksheet, the parameter you created will be available in the bottom-left corner of the Data pane. Right-click on it and select "Show Parameter". A slider or a text box will appear in your worksheet view, allowing you or your users to control the query's results interactively.

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.

Tips and Best Practices for Writing Custom SQL in Tableau

While Custom SQL offers great flexibility, it's also a path where you can run into performance issues if you're not careful. Here are some best practices to follow:

  • Don't Use SELECT *: It’s tempting to grab every column, but you should only select the columns you actually need for your analysis. Pulling unnecessary data increases load times and clutters your data pane.
  • Test in a Standalone SQL Client First: The debugging capabilities in Tableau's Custom SQL editor are limited. It's much easier to write, test, and debug your query in a dedicated SQL editor like DBeaver, SQL Server Management Studio, or pgAdmin first. Once it's working perfectly, copy and paste it into Tableau.
  • Let the Database Do the Heavy Lifting: Use your query to perform as much filtering and aggregation as possible. Sending a query like WHERE region = 'West' is much more efficient than pulling the entire table and then applying a filter in Tableau.
  • Understand the Performance Impact: Custom SQL can sometimes prevent Tableau from performing its own optimizations (like "query fusion"). If a dashboard is slow, compare the performance of your Custom SQL connection against a standard connection with tables joined visually. The result might surprise you.
  • Use Comments in Your Code: If your query is complex, use SQL comments (-- for single line, /* block comment */) to explain the logic. This will be invaluable for your future self or any colleagues who need to understand your data source.
  • Think About Live vs. Extract: A complex Custom SQL query against a massive database on a live connection can be very slow. In these cases, it's often best to run the query once and then create a Tableau Extract. The dashboard will then query the hyper-fast extract file, resulting in near-instant load times for your users.

Final Thoughts

Learning to write Custom SQL queries directly in Tableau provides a fantastic layer of control, helping you tackle complex data challenges, optimize for performance, and build more dynamic dashboards. By understanding when to use it and combining it with the power of parameters, you can deliver precise and interactive insights.

As powerful as this is, an undeniable learning curve is associated with SQL and BI tool configuration. For those who want the powerful insights without the coding, we built Graphed to remove this friction. We made it possible to connect all your data sources and create real-time dashboards and reports just by asking questions. Instead of writing queries and dragging fields, you can simply ask, "show me a dashboard comparing sales vs. marketing spend for last quarter," and get your answer in seconds.

Related Articles