Power Query Value.NativeQuery Function Guide
In this article
The Value.NativeQuery function in Power Query allows you to execute a specific SQL statement directly against a database source instead of relying on the visual Query Editor to generate the SQL for you. This is primarily used to improve performance through query folding, to utilize database-specific functions that Power Query does not support natively, and to write complex joins or CTEs (Common Table Expressions) that are difficult to replicate using the Power Query interface. To use it, you need a valid connection to a database (such as SQL Server, Oracle, or PostgreSQL) and the appropriate permissions to execute queries on that server.
What You'll Need
- Microsoft Excel or Power BI Desktop installed on your machine.
- Access to a relational database (e.g., SQL Server, MySQL, PostgreSQL, Oracle).
- The server name and database name for the connection.
- A valid SQL query written and tested in a database management tool (like SQL Server Management Studio) to ensure the syntax is correct before implementing it in Power Query.
- Appropriate database user permissions to run
SELECTstatements.
Step-by-Step
- Open the Power Query Editor: In Power BI, go to the Home tab and select Get Data. In Excel, go to the Data tab, select Get Data, and choose your specific database source.
- Establish the Initial Connection: Select your database provider (e.g., SQL Server database). Enter the Server and Database names. When prompted for the Data Connectivity mode, select Import. Click OK.
- Select a Table as a Placeholder: The Navigator window will appear showing a list of tables. Select any small table from the database and click Transform Data. This creates the initial connection string (the
Sql.Databasestep) required forValue.NativeQueryto function. - Open the Advanced Editor: Once the Power Query Editor opens, go to the Home tab and click on the Advanced Editor button. This allows you to modify the M code directly.
- Identify the Source Step: Look for the line that defines the source, which usually looks like
Source = Sql.Database("ServerName", "DatabaseName"). This line establishes the connection to the server. - Insert the Value.NativeQuery Function: Create a new step immediately following the Source step. The syntax for the function is
Value.NativeQuery(source, query, parameters, options). Replace the placeholder table step with the following structure:let Source = Sql.Database("YourServer", "YourDatabase"), RunQuery = Value.NativeQuery(Source, "SELECT * FROM Sales.Orders WHERE OrderDate > '2023-01-01'", null, [EnableFolding=true]) in RunQueryIn this example,Sourceis the connection object, and the second argument is your raw SQL string. - Configure Parameters (Optional): If you want to make your query dynamic, you can pass a record as the third argument. For example, if your SQL query uses a parameter like WHERE City = @City , you would define the third argument as .
- Set the EnableFolding Option: In the fourth argument (the options record), set
[EnableFolding=true]. This tells Power Query to attempt to merge any subsequent filter or sort steps into the native SQL query, ensuring the database does the heavy lifting rather than your local machine. - Apply and Close: Click Done in the Advanced Editor. Power Query may prompt you with a security warning regarding "Native Database Queries." Click Run to execute the SQL. Finally, click Close & Apply to load the data into your model.
Common Mistakes
One of the most frequent errors is forgetting that Value.NativeQuery requires a database connection object as its first argument. Users often try to pass a text string or a table name instead of the Sql.Database result. The function cannot create a connection; it can only execute a query over an existing one.
Another common mistake is ignoring the "Native Query" security warning. By default, Power Query warns users when a manual SQL statement is executed to prevent SQL injection attacks. Many users believe this is an error, but it is a security feature. You must explicitly grant permission to run the query for that specific data source.
Syntax errors within the SQL string are also common. Because Power Query treats the SQL query as a text string, you cannot use the database's native IDE to check for typos. If you use double quotes inside your SQL query (e.g., SELECT * FROM Table WHERE Name = "John"), you must escape them by using double-double quotes (""John"") so that the M engine does not think the string has ended.
Lastly, users often fail to set EnableFolding=true. Without this, any steps added after the native query in the Power Query interface (like filtering a column or removing duplicates) will be performed in the local memory of the computer (Mashup Engine) rather than on the SQL server, which can lead to massive performance degradation when dealing with millions of rows.
Tips
To keep your queries clean, write your SQL in a dedicated editor like SQL Server Management Studio (SSMS) or Azure Data Studio first. Once the query is optimized and verified, copy and paste it into the Value.NativeQuery function. This prevents the tedious cycle of editing M code, clicking Apply, and waiting for a timeout error to find a missing comma.
Use parameters to make your reports flexible. Instead of hard-coding a date or a region into the SQL string, use a Power Query Parameter. You can then reference that parameter within the Value.NativeQuery record, allowing end-users to change the data being pulled without editing the M code.
When dealing with very large datasets, avoid SELECT *. Explicitly name your columns in the native query. This reduces the amount of data traveling over the network and prevents the query from breaking if a database administrator adds a new, unnecessary column to the source table.
If you are using a complex query with multiple Common Table Expressions (CTEs), wrap the entire SQL block in a single string. Ensure that the SQL dialect you are using matches the database provider. For example, using TOP 10 works for SQL Server but will fail on PostgreSQL, where you must use LIMIT 10.
Troubleshooting
If you encounter a "Permission denied" or "Security warning" error, go to File > Options and settings > Data source settings. Select the data source and ensure that the privacy levels are set consistently (e.g., both set to Organizational or both set to Public). If the warning persists, you can disable the "Require user approval for native database queries" option in the Global settings, though this is only recommended for secure, internal environments.
If the query returns a "Syntax error" but the SQL works in your database tool, check your quotation marks. Ensure that any single quotes used for dates or strings in SQL are preserved and that any double quotes are escaped as "". Also, verify that there are no hidden line-break characters causing the M engine to misinterpret the string.
When the query runs extremely slowly, check the Query Diagnostics. If you see that the "Folding" is not occurring, it means the EnableFolding=true option is either missing or the subsequent steps in your Power Query sequence are not foldable. Try moving all filters and joins into the native SQL statement itself to ensure maximum efficiency.
If you receive a "Timeout expired" error, it usually means the SQL server is struggling to process the request within the default time limit. You can resolve this by adding a timeout option to the Sql.Database function. For example: Sql.Database("Server", "DB", [CommandTimeout=#duration(0, 0, 30, 0)]), which extends the timeout to 30 minutes.
Frequently Asked Questions
Does Value.NativeQuery support all SQL dialects?
It supports any dialect that the underlying database connector (like Sql.Database or Oracle.Database) supports. The function simply passes the string to the server, so as long as the server understands the SQL, it will work.
Can I use Value.NativeQuery with Excel files?
No. Value.NativeQuery is designed for relational databases that accept SQL queries. Excel files are flat files and do not have a SQL engine to process native queries.
Is Value.NativeQuery better than the visual Query Editor?
For simple tasks, the visual editor is faster. For complex logic, such as window functions (RANK, LEAD, LAG) or complex joins, Value.NativeQuery is significantly more powerful and often more performant.
Will using native queries break my report if the table schema changes?
Yes, if you explicitly name columns in your SELECT statement and those columns are renamed or deleted in the database, the query will fail. You will need to update the SQL string in the Advanced Editor.
Can I combine Value.NativeQuery with other M functions?
Yes. You can use the result of a Value.NativeQuery as the input for other M functions like Table.Group or Table.Pivot, though doing so may stop query folding for those specific steps.