How to Add Custom SQL in Tableau

Cody Schneider9 min read

Using Custom SQL in Tableau gives you direct control over your data connection, allowing you to run a specific SQL query on a database and use the results of that query as your data source. This article walks you through exactly when to use it, how to set it up step-by-step, and best practices for making it work for you.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

What is Custom SQL in Tableau and Why Use It?

Normally, when you connect to a database in Tableau, you see a list of tables. You can drag these tables onto the canvas and create joins visually by dragging noodles between them. Behind the scenes, Tableau's VizQL engine generates optimized SQL queries based on the fields you drag into your worksheets.

The "Custom SQL" option lets you bypass that visual interface. Instead of dragging and dropping tables, you write or paste your own full SQL query. Tableau then treats the result of your single query as if it were a single table. You're essentially defining your data source with code before you even start building visualizations.

So, why would you choose this path over Tableau's user-friendly visual method? There are several powerful reasons:

  • Performance Optimization: If you're working with a massive table that has millions or even billions of rows, pulling the entire thing into Tableau for filtering can be slow. With Custom SQL, you can use a WHERE clause to pre-filter the data at the database level, meaning Tableau only has to handle a much smaller subset of relevant data.
  • Complex Joins or Unions: While Tableau's visual join editor is great for straightforward inner, left, or right joins on a common key, it sometimes struggles with more advanced scenarios. Custom SQL allows you to perform joins based on complex logic (e.g., using date ranges or multiple conditions) or union data from tables with slightly different structures.
  • Data Shaping and Cleaning: You can use SQL to reshape your data before it ever hits Tableau. This could involve pivoting data, casting data types (e.g., changing text to a date), concatenating fields, or applying case statements to create a new, clean category on the fly.
  • Leveraging Database-Specific Functions: Your database (like PostgreSQL, SQL Server, or Oracle) often has unique functions that Tableau's standard connectors might not natively generate. Custom SQL allows you to use powerful window functions, date functions, or other proprietary features directly in your query.
  • Connecting to Views or Stored Procedures: While Tableau can connect to database views, sometimes you may need to query a parameterized stored procedure using Custom SQL (support varies by database).

A Few Words of Caution

Custom SQL is a powerful tool, but it's not always the best choice. It comes with a few trade-offs you should be aware of before you commit.

  • Potential for Worse Performance: Tableau is exceptionally good at creating optimized queries for its visualizations. A poorly written Custom SQL query can perform much slower than what Tableau would generate on its own. It effectively puts the responsibility for optimization squarely on your shoulders.
  • Reduced Flexibility: When you connect to full tables, you can explore the entire dataset freely. A Custom SQL query, by its nature, is fixed. If you realize later that you need a column you didn't include in your initial SELECT statement, you have to go back and edit the query itself.
  • Maintenance Headaches: A complex SQL query can be difficult for other people (or a future version of you) to understand and maintain. Unlike the visual interface, there's no easy-to-read diagram of the data relationships, there's only the code. Proper commenting is essential.
  • Query Rewriting Issues: Tableau sometimes wraps your Custom SQL inside another SELECT statement to perform additional operations like filtering or aggregation. This can cause issues with certain types of queries or database features, leading to unexpected errors.

As a rule of thumb, always try to accomplish your goal with Tableau's native visual connectors first. If you hit a roadblock - whether it's performance or complexity - then turn to Custom SQL as your next powerful option.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

How to Add Custom SQL in Tableau: A Step-by-Step Guide

Ready to write your own query? The process is straightforward. For this example, let's assume we're connecting to a PostgreSQL database that has tables for orders, customers, and order details.

Step 1: Connect to Your Database

Open Tableau Desktop and, under the "To a Server" list, select your database type. For this example, we'll choose PostgreSQL. Enter your server credentials and sign in.

Step 2: Find the "New Custom SQL" Option

Once you connect, you’ll land on the Data Source screen. Instead of dragging tables from the left pane onto the canvas, find the item labeled "New Custom SQL" and drag that onto the canvas instead.

Step 3: Write Your SQL Query

A dialog box will pop up where you can write or paste your query. A common use case is joining several tables and filtering for a specific subset of data. Let's create a query that pulls order information specifically for corporate customers in 2023.

Type or paste your query into the box. Here is an example:

SELECT
  o.OrderID,
  o.OrderDate,
  c.CustomerName,
  c.Segment,
  p.ProductName,
  p.Category,
  oi.Sales,
  oi.Quantity
FROM
  Orders AS o
JOIN
  Customers AS c ON o.CustomerID = c.CustomerID
JOIN
  OrderItems AS oi ON o.OrderID = oi.OrderID
JOIN
  Products AS p ON oi.ProductID = p.ProductID
WHERE
  c.Segment = 'Corporate' AND EXTRACT(YEAR FROM o.OrderDate) = 2023
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step 4: Preview and Confirm Your Query

Before committing, it's always a good idea to click the "Preview Results" button. This will run the query against your database and show you the first few rows of output. It's a great way to quickly check for syntax errors or confirm that the data looks the way you expect.

If there's an error in your SQL, Tableau will display an error message from the database. This helps you debug before you move on.

Once you're satisfied, click "OK."

Step 5: Use Your Query in Tableau

Back on the Data Source canvas, you'll now see a single object labeled "Custom SQL Query". Tableau will treat this as a single entity, just like a table. From here, you can click on "Sheet" and start building visuals. All the fields you defined in your SELECT statement will be available in the data pane on the left, ready to be dragged onto your worksheet.

Best Practices for Writing Custom SQL

To avoid the pitfalls mentioned earlier, keep these tips in mind when crafting your queries inside Tableau:

  • Only Select the Columns You Need: Never use SELECT *. Explicitly list the columns you need for your analysis. This minimizes the amount of data being transferred from the database and makes your query easier to understand.
  • Filter Early with WHERE: The single biggest performance gain comes from filtering as much data out as possible within your query itself. Use strong WHERE clauses so Tableau processes fewer records.
  • Use Aliases for Readability: Use table aliases (e.g., Customers AS c) and column aliases (e.g., CustomerName AS "Customer Name") to keep your query concise and easy-to-read, especially when dealing with complex joins.
  • Test Outside Tableau First: For anything beyond a simple query, it's often faster and easier to develop and test your SQL in a dedicated client like DBeaver, SQL Server Management Studio, or pgAdmin. You have access to better debugging and performance analysis tools. Once it's working perfectly, copy it into Tableau.
  • Comment Your Code: If your query has complex business logic or joins, add SQL comments (-- a single-line comment or /* a multi-line comment */) explaining what each section does. Your colleagues (and your future self) will thank you for it.

Using Parameters for Dynamic Custom SQL

One of the most powerful features is combining Custom SQL with Tableau Parameters. This lets you give end-users an interactive way to dynamically modify your query without ever having to see the SQL editor.

Let's take our previous example. What if you wanted the user to choose the "Segment" to analyze? Instead of hard-coding 'Corporate', we can insert a parameter.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

How it Works

  1. First, create a Tableau Parameter. In the data pane on the left, right-click and select "Create Parameter." For our example, let's call it "Segment Parameter," set its 'Data Type' to 'String,' and in the 'List' area add 'Corporate,' 'Consumer,' and 'Home Office.'
  2. Now, edit your Custom SQL Query (go back to the Data Source tab, right-click on your query object, and select "Edit Custom SQL Query").
  3. Find the filter in the WHERE clause where you had 'Corporate' hardcoded.
  4. Delete 'Corporate'. In its place, click the Insert Parameter button on the right of the screen and select "Segment Parameter".

Your WHERE clause will now look something like this:

WHERE c.Segment = <Parameters.Segment Parameter> AND EXTRACT(YEAR FROM o.OrderDate) = 2023

Now, show the parameter control on your dashboard. Whenever a user selects a different segment from the drop-down, Tableau re-runs the query with the user's selection, delivering a fully interactive reporting experience powered by your query.

Final Thoughts

Adding Custom SQL in Tableau is a fantastic way to handle complex data situations that the standard visual interface can't quite manage. It gives you the granular control to join, filter, and shape your data with precision, often leading to huge performance gains when used correctly with large datasets.

For us at Graphed, the desire to escape complex configuration is at the core of what we do. Instead of spending time debugging SQL queries to prepare data, you can connect your sources (like Google Analytics, Salesforce, and Shopify) and just describe what you want to see - even the complex bits. Just ask, "Create a dashboard comparing Facebook Ads spend this month to Shopify sales from customers in the 'Corporate' segment," and it gets built in seconds, backed by a live data feed. We handle writing the optimal, complex queries so you can skip straight to getting answers with Graphed.

Related Articles