Can You Write SQL Queries in Power BI?

Cody Schneider8 min read

The short answer is yes, you can absolutely write SQL queries in Power BI, and it's a powerful way to handle your data. But just because you can doesn't always mean you should. Knowing when and how to use SQL is the key to creating fast, efficient, and accurate reports. This article will walk you through the primary ways to use SQL queries in Power BI, show you best practices for getting it right, and explain when it’s better to stick with Power BI's other powerful tools like Power Query and DAX.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

So, Can You Actually Write SQL in Power BI?

Yes, but it's important to understand that you're not writing SQL to create visualizations directly. Instead, you're using SQL to define the data table that Power BI loads. Think of it as shaping your data at the source before it even enters the Power BI environment. This gives you precise control over what information you work with, and it can often dramatically improve your report’s performance.

Why Would You Want to Write SQL in Power BI?

Working directly with Power BI’s graphical interface is great, but there are several scenarios where dropping into SQL is a better approach:

  • Performance Boosts: Databases are designed to process massive quantities of data very efficiently. By writing a SQL query, you can perform complex filtering, joining multiple tables, and aggregating data on the database server itself. This is often much faster than loading several enormous tables into Power BI and then trying to do the same work with Power Query or DAX.
  • Handling Complex Logic: Sometimes the data transformation you need is too complex or convoluted for Power Query. Executing a stored procedure, using window functions, or creating complex common table expressions (CTEs) can all be done in a single SQL query before Power BI even sees the data.
  • Greater Control: A SQL query gives you command-line control over your data. You can select specific columns, rename them on the fly with aliases, and filter rows with a WHERE clause to bring in only the exact data required for your report.
  • Connecting to Existing Views: Your company might already have predefined SQL views that encapsulate important business logic. Instead of trying to recreate this logic in Power BI, you can simply write a SELECT * FROM YourCoolView query to use that validated data source directly.

Two Main Ways to Use SQL Queries in Power BI

There are two fundamental approaches to leveraging SQL in Power BI. The one you choose depends on whether you need live data or are simply looking to shape the initial dataset you import.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Method 1: Writing a Custom SQL Statement for Data Import

This is the most common method. You write a specific SQL query that Power BI runs once to fetch your dataset. After that, the data is loaded into Power BI's data model, and any further analysis is done there. This gives you complete control over the starting table you want to analyze.

Step-by-Step Guide:

  1. From the Power BI Desktop home ribbon, click on Get data and select your SQL data source (e.g., SQL Server database, PostgreSQL, MySQL, etc.).
  2. In the connection dialog box, enter your server and database information.
  3. Before clicking "OK," expand the Advanced options section. You'll see an input box labeled SQL statement.
  4. Write or paste your SQL query directly into this box. This is where you can define exactly what data you want.

For example, imagine you want to pull a pre-filtered list of your top international sales from the last year, joining your customers, orders, and products tables. Your query might look like this:

SELECT
  c.CustomerName,
  c.Country,
  o.OrderID,
  o.OrderDate,
  p.ProductName,
  oi.Quantity * oi.Price AS SaleAmount
FROM Customers c
JOIN Orders o ON c.CustomerID = o.CustomerID
JOIN OrderItems oi ON o.OrderID = oi.OrderID
JOIN Products p ON oi.ProductID = p.ProductID
WHERE
  c.Country NOT IN ('USA', 'Canada')
  AND o.OrderDate >= DATEADD(year, -1, GETDATE())

When you click "OK," Power BI will send this exact query to your database. The result - a perfectly formed table of international sales data - is what gets loaded into the Power Query Editor for any further cleaning or transformations.

Method 2: Using DirectQuery Mode

Using DirectQuery is a different beast entirely. Instead of importing a static snapshot of your data, DirectQuery creates a live connection to your database. In this mode, you don't write one SQL query up front. Instead, Power BI writes SQL queries automatically in the background every time you interact with your report - clicking a slicer, filtering a chart, or opening a new page.

This mode is ideal for working with extremely large datasets (think billions of rows) that are too big to import or for scenarios where you need absolutely real-time data.

How to Enable DirectQuery:

  1. Follow the same initial steps: click Get data and select your SQL source.
  2. In the connection dialog box, under Data Connectivity mode, select DirectQuery instead of the default "Import."
  3. Instead of writing a custom query, you'll select the tables you want to connect to from the Navigator, just as you would in Import mode.

From here, when you build a visual - say, a bar chart of sales by country - Power BI formulates a SQL query (like SELECT Country, SUM(Sales) FROM YourTable GROUP BY Country), sends it to your database, and visualizes the results. Every filter and interaction sends a new query, keeping the visuals live.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Best Practices and Common Pitfalls

Using SQL in Power BI isn't without its quirks. Keeping a few key concepts in mind will save you a lot of headaches.

Watch Out for Query Folding!

Query folding is a magical, behind-the-scenes Power BI process. When you're connected to a SQL source, Power BI attempts to convert the transformation steps you perform in the Power Query Editor back into a single, efficient SQL statement.

For example, if you filter rows and remove columns in Power Query, Power BI will "fold" those steps into the WHERE clause and SELECT statement of its SQL query. This is great for performance because the work happens on the database server. However, some transformations can "break" query folding. Adding an index column, for example, is something your SQL server doesn't know how to do, so Power BI has to perform that step locally after getting the data.

Pro Tip: To see if query folding is active, right-click on your last transformation step in the "Applied Steps" pane in the Power Query Editor. If the View Native Query option is enabled (not grayed out), folding is working!

Import Mode vs. DirectQuery: Choose Wisely

This is one of the most important decisions you'll make.

  • Choose Import Mode (with or without a custom SQL statement) when:
  • Choose DirectQuery Mode when:
GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

When DAX and Power Query Are Your Best Bet

Just because you can push logic to SQL doesn't mean you always should. Power BI's own languages, Power Query (M) and DAX, are purposefully built for business intelligence.

Use Power Query for: User-friendly data shaping. Things like splitting columns, unpivoting data, replacing values, and merging data from different sources (like a SQL database and a CSV file) are often faster and easier to manage in the Power Query interface, especially for users who aren't SQL experts.

Use DAX for: Dynamic, on-the-fly calculations within your report. DAX (Data Analysis Expressions) operates on the data model inside Power BI. It's used to create dynamic measures that respond to user interactions. You can't use SQL to create a measure like Total Sales YTD that automatically updates when a user selects "2023" on a slicer. That's a job for DAX.

A good workflow is often a hybrid: use an initial SQL query to import a clean, pre-filtered, and pre-aggregated dataset. Then, use Power Query for any final cleaning, and finally, use DAX to build the powerful, interactive measures your reports need.

Final Thoughts

So, can you write SQL in Power BI? Absolutely. It’s an invaluable skill for optimizing performance and gaining precise control over your data. By writing SQL at the connection stage or leveraging DirectQuery for live reports, you can let your database handle the heavy lifting, leading to a much more efficient analytics workflow.

Wrestling with BI tools, configuring data models, and writing custom SQL can soak up hours that could be spent on strategy. To help with this, we built Graphed to skip the technical setup entirely. By connecting your data sources and asking questions in simple English, you can get insights and build real-time reports in seconds. We made it for teams who need answers now, without needing a data engineering degree to get them.

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!