For most of Fabric’s life (and it’s been more than 3 years now), the answer to “can my Fabric notebook read our on-premises SQL Server?” was… Eehhmm, no… The on-premises data gateway worked for pipelines, Dataflow Gen2, and mirroring, but not for notebooks. The standard workaround was to ingest the data with a pipeline first, and only then pick it up in Spark. In February 2026, the Execute Query REST API opened a side door: a notebook could call it to run Power Query M inside a Dataflow Gen2 item (gateway included), as long as the query finished within 90 seconds.

The November Fabric feature summary turned that into a native notebook feature. A new module, notebookutils.powerquery, runs Power Query M from a notebook through an existing Fabric connection, including a gateway-backed one! The result comes back as a PySpark DataFrame.

Strictly speaking, the gateway still doesn’t reach Spark. Power Query reaches the gateway, and the notebook receives the result. That difference explains most of what this feature is good for and where it might be challenging, including a 180-second limit that decides most use cases on its own.

In this article, I cover how it works, a walkthrough against an on-prem SQL Server, the limitations, and the other ways to reach the same SQL Server from a notebook, including pyodbc and JDBC.

How it works

In a nutshell, one call does all the work:

notebookutils.powerquery.executeQuery(query_name, script, connections=None)

Behind it, a request travels through five stops:

  1. The notebook sends an M script and the name of the query to run.
  2. The Power Query engine evaluates the script, in Fabric for cloud sources and through the gateway for on-prem ones. Spark isn’t involved yet.
  3. The Fabric connection you pass in connections supplies the credentials and, for on-prem sources, the gateway routing.
  4. The on-premises data gateway connects to the source inside your network. It only opens outbound connections, so nothing on-prem has to accept traffic from the internet.
  5. The result comes back to the notebook as a PySpark DataFrame. Pass a list of query names instead, and you get a QueryResults container with one DataFrame per query.

Two details are important for everything that follows.

First, the M script defines the source, and the connection only authenticates it. The docs are explicit that the script’s server and database must match the Fabric connection. You’re not picking a connection and browsing it, as you would do in Dataflow Gen2. You write Sql.Database("server", "db") and pass the connection that matches it.

Second, everything the notebook gets has already gone through Power Query and the gateway. Spark only sees the result. The source isn’t read in parallel by Spark executors, and the time limits are Power Query’s, not Spark’s.

Walkthrough: an on-prem SQL Server table in a notebook

Before writing any code, you need three things in place:

  1. An on-premises data gateway, installed on a machine that can reach the SQL Server, and that gateway must be online
  2. A Fabric connection to that server and database, bound to the gateway. You create it in Manage connections and gateways, the same way you would for a pipeline
  3. Permission to use that connection, for the identity that runs the notebook

Then the notebook code is short:

script = """
let
    Source = Sql.Database("sql01.corp.contoso.local", "SalesDB"),
    Orders = Source{[Schema = "dbo", Item = "Orders"]}[Data],
    Recent = Table.SelectRows(Orders, each [OrderDate] >= #date(2026, 11, 1))
in
    Recent
"""

df = notebookutils.powerquery.executeQuery(
    "RecentOrders",
    script,
    connections=["onprem-sql01-salesdb"]
)

df.write.mode("append").format("delta").saveAsTable("bronze_orders")

The server and database in Sql.Database must match the connection. You can pass the connection’s name or its ID. If two connections share the same name, use the ID.

The filter belongs in M, not in Spark. Table.SelectRows on a SQL source folds into a WHERE clause, so only November’s orders leave the server. Filtering the DataFrame afterward would pull the whole table through the gateway first, and with the time limits below, that’s the difference between a query that finishes and one that might run into a timeout.

I checked that with an Extended Events session on my SQL Server while the notebook read one month of FactOnlineSales. The query that arrived had the filter in its WHERE clause, translated to convert(datetime2, '2009-12-01 00:00:00'). Power Query also added an ORDER BY on the table’s key, so SQL Server sorts the result before sending it.

The notebook got 478,320 rows in 58 seconds. That’s roughly 8,000 rows per second in my setup, so a 180-second budget covers about 1.5 million rows of this table, and the full 12.6 million would need around 25 minutes. Your numbers will depend on row width, the gateway machine, and the network, but the order of magnitude explains why the full read failed.

To read several tables in one call, write a complete M document that starts with section and marks each query as shared:

script = """
section Section1;
shared Customers = Sql.Database("sql01.corp.contoso.local", "SalesDB"){[Schema = "dbo", Item = "Customers"]}[Data];
shared Products = Sql.Database("sql01.corp.contoso.local", "SalesDB"){[Schema = "dbo", Item = "Products"]}[Data];
"""

results = notebookutils.powerquery.executeQuery(
    ["Customers", "Products"],
    script,
    connections=["onprem-sql01-salesdb"]
)

for name, frame in results.successes.items():
    frame.write.mode("overwrite").format("delta").saveAsTable(f"bronze_{name.lower()}")

for name, error in results.failures.items():
    print(f"{name} failed: {error}")

A multi-query call doesn’t fail as a whole when one query fails. Failures end up in results.failures, so you can keep the tables that worked and log the rest. Call results.raise_if_failed() if you’d rather stop the run instead.

What happened when I ran it

I ran the loop against the Contoso database on my own on-prem SQL Server, through a freshly registered gateway, reading three tables in one cell:

TableResultTime
dbo.DimChannel4 rows3.7 s
dbo.DimCustomerFailed: [UNSUPPORTED_ARROWTYPE] Unsupported arrow type Int(8, false)6.1 s
dbo.FactOnlineSalesFailed: Standalone Power Query request failed with status code 408483.2 s

Three things are worth mentioning:

Every call carries overhead. Four rows took 3.7 seconds. A dozen small lookups in a loop add up to about a minute, even when every result is tiny.

A tinyint column breaks the read. DimCustomer failed in six seconds, not because of its size but because of a data type. More on that in the limitations below.

The timeout came late. The fact table failed with HTTP 408, but only after 483 seconds, not the documented 180. My notebook sat waiting for eight minutes.

Then I asked SQL Server only for the row count of the same table:

script = """
let
    Source = Sql.Database("nikola-master", "Contoso"),
    T = Source{[Schema = "dbo", Item = "FactOnlineSales"]}[Data],
    Grouped = Table.Group(T, {}, {{"RowCount", each Table.RowCount(_), Int64.Type}})
in
    Grouped
"""

df = notebookutils.powerquery.executeQuery(
    "CountRows", script, connections=["onprem-nikola-master-contoso"]
)

The answer, 12,627,608 rows, came back in about 6 seconds for the whole cell. That’s the same table that failed after eight minutes as a full read. The difference is where the work happens: the count runs in SQL Server, and only one row crosses the gateway.

One more thing showed up in the output: an extra column called PQ Arrow Metadata, filled with NULLs. It isn’t in the source table, and the docs don’t mention it. Drop it before you write to a Delta table, or it ends up in your lakehouse:

df = df.drop("PQ Arrow Metadata")

Limitations and gotchas

The 180-second timeout is the one that decides whether this feature fits your case. If the gateway can’t return the result in three minutes, the query fails, regardless of its size.

In my test, the failure didn’t arrive at 180 seconds. A full read of a fact table blocked the notebook for 483 seconds before failing with HTTP 408. Plan for the wait, not just the limit.

The documented limits for the preview:

LimitValue
OperationsRead only, no write-back to the source
Evaluation timeout, gateway-backed180 seconds
Evaluation timeout, other sources230 seconds
M document size512 KiB (UTF-8), including the wrapper added around a single expression
Query name length80 characters
Connections per M document100
Multi-query scriptsMust start with section, each query must be shared

In practice, 180 seconds means reference data, lookups, small dimension tables, and incremental slices. It doesn’t mean a full extract of a large fact table, and it doesn’t mean an initial load. Push filters and column selection into M, so the source does the work before anything crosses the gateway.

What the documentation doesn’t say yet:

  • Cost. The official documentation page doesn’t say how the Power Query evaluation is billed, on top of the Spark session that called it. For the older Execute Query REST API, Microsoft documents an operation called “Dataflows Gen2 Run Query API”, billed on the Dataflow Gen2 meter by query duration. Something similar is likely here, but unconfirmed, so check the Capacity Metrics app after your first runs.
  • Python notebooks. Insert test results here!
  • Supported sources. There’s no connector list. The page only says gateway access needs “a Fabric connection configured for a supported on-premises data source”.
  • VNet data gateways. Not mentioned either way.
  • Row or size limits. Only the time limits are documented.

A few more things to plan for:

  • The gateway is now in your Spark job’s critical path. The same gateway often serves Power BI refreshes and pipelines. A notebook that hits it hard competes with them, and a gateway that’s offline fails your notebook run.
  • Private Link tenants need a closer look. Microsoft’s Private Link documentation says on-premises data gateways aren’t supported and fail to register when Private Link is enabled for the tenant. Community experts in Reddit threads report that a gateway registered before Private Link was switched on keeps working, but adding or reconfiguring one requires turning Private Link off. VNet data gateways do support Private Link, but whether this feature accepts a VNet gateway connection isn’t documented. The managed private endpoint option in the next section works either way.
  • tinyint columns break the conversion. SQL Server’s tinyint is unsigned, Power Query hands it over as an unsigned 8-bit Arrow type, and Spark has no unsigned integer types. The read fails with [UNSUPPORTED_ARROWTYPE] Unsupported arrow type Int(8, false), whatever the table’s size. The documentation doesn’t mention it. The workaround is to cast those columns in M, before the result reaches Spark:
script = """
let
    Source = Sql.Database("nikola-master", "Contoso"),
    T = Source{[Schema = "dbo", Item = "DimCustomer"]}[Data],
    ByteCols = Table.ColumnsOfType(T, {Byte.Type, type nullable Byte.Type}),
    Fixed = Table.TransformColumnTypes(T, List.Transform(ByteCols, each {_, Int32.Type}))
in
    Fixed
"""

Note: Python notebooks aren’t affected! The same DimCustomer read works there without the workaround.

Does it work in a Python notebook?

The docs only show PySpark, and say a single query returns a PySpark DataFrame. A Python notebook has no Spark session, so I ran the same reads in one: same on-prem SQL Server (nikola-master, the Contoso sample database), same gateway, same connection.

The module is there, and it returns pandas:

notebookutils.powerquery.help()

The help text answers the return-type question before any query runs: a pandas DataFrame for a single query, and QueryResults for a list of query names. The session was on Python 3.12 and ready in about 3 seconds.

One month of FactOnlineSales

The same filtered read I traced with Extended Events in the walkthrough, timed:

import time

script = """
let
    Source = Sql.Database("nikola-master", "Contoso"),
    T = Source{[Schema = "dbo", Item = "FactOnlineSales"]}[Data],
    Month = Table.SelectRows(T, each [DateKey] >= #datetime(2009, 12, 1, 0, 0, 0)
                                  and [DateKey] < #datetime(2010, 1, 1, 0, 0, 0))
in
    Month
"""

start = time.perf_counter()
pdf = notebookutils.powerquery.executeQuery(
    "FactOnlineSalesMonth", script, connections=["onprem-nikola-master-contoso"]
)
print(f"{len(pdf):,} rows in {time.perf_counter() - start:.1f} s")

478,320 rows in 69.8 seconds. The same cell in PySpark took 58 seconds. Both are single runs, but they’re close enough to say the Python notebook isn’t faster. The time goes into Power Query and the gateway moving rows, not into building a Spark DataFrame.

The result also contains a column I didn’t ask for, PQ Arrow Metadata. It shows up in PySpark too. Drop it before you write anything:

pdf = pdf.drop(columns=["PQ Arrow Metadata"], errors="ignore")

DimCustomer, the table that fails in PySpark

In PySpark, DimCustomer fails on its tinyint columns with an Arrow Int(8, false) error. In the Python notebook it reads without any workaround!

script = """
let
    Source = Sql.Database("nikola-master", "Contoso"),
    T = Source{[Schema = "dbo", Item = "DimCustomer"]}[Data]
in
    T
"""
customers = notebookutils.powerquery.executeQuery(
    "DimCustomer", script, connections=["onprem-nikola-master-contoso"]
).drop(columns=["PQ Arrow Metadata"], errors="ignore")

cols = ["TotalChildren", "NumberChildrenAtHome", "NumberCarsOwned"]
print(dict(customers[cols].dtypes))

The catch is in the printout: all three former tinyint columns arrive as float64, so a children count of 2 becomes 2.0. Write that to Delta as-is and the integer columns end up in the lakehouse as doubles. Cast them back first:

customers[cols] = customers[cols].astype("Int64")

Writing it to the lakehouse

The Python runtime comes with delta-rs (the deltalake package) preinstalled. Microsoft notes that versions 1.0 and above aren’t supported yet, so don’t upgrade it with %pip.

My first attempt wrote to the local /lakehouse/default/Tables/... path and failed with Unable to rename file, Operation not permitted. The mounted lakehouse folder doesn’t allow the file rename that delta-rs performs on commit. Writing through the OneLake URL works:

from deltalake import write_deltalake, DeltaTable

workspace_id = notebookutils.runtime.context["currentWorkspaceId"]
lakehouse_id = "<your-lakehouse-id>"
path = (f"abfss://{workspace_id}@onelake.dfs.fabric.microsoft.com/"
        f"{lakehouse_id}/Tables/dim_customer_py")
storage_options = {
    "bearer_token": notebookutils.credentials.getToken("storage"),
    "use_fabric_endpoint": "true",
}

write_deltalake(path, customers, mode="overwrite", storage_options=storage_options)

dt = DeltaTable(path, storage_options=storage_options)
print(f"{len(dt.to_pandas()):,} rows written")
for field in dt.schema().fields:
    if field.name in cols:
        print(field.name, field.type)

I hardcoded the lakehouse ID because defaultLakehouseId in the runtime context came back as None in my session, since I didn’t attach the default lakehouse. The workspace ID resolved fine.

The write produced 18,870 rows, and TotalChildren, NumberChildrenAtHome and NumberCarsOwned came out as long in the Delta schema.

Python notebook vs PySpark, side by side

CheckPython notebookPySpark notebook
Return type, single querypandas DataFramePySpark DataFrame
One month of FactOnlineSales (478,320 rows)69.8 s58 s
DimCustomer with tinyint columnsReads; columns arrive as float64Arrow error without the M cast
PQ Arrow Metadata column in the resultYesYes
Session startAbout 3 sDepends on Spark settings

So it works, with one change in what you get: a usually lighter session that starts in seconds, not a faster read. The query timeout and the gateway throughput are the same in both runtimes, and so is the size of the read that fits inside them.

Can’t I just use pyodbc or JDBC?

You can, but the driver was never the problem. The network is.

pyodbc, JDBC, and pymssql all need the same thing: a TCP connection from the Spark cluster to port 1433 on your SQL Server. Fabric Spark runs in a Microsoft-managed network, and your SQL Server sits behind your firewall. Without a network path between the two, every driver fails the same way, with “make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections”. The gateway doesn’t help here, because it isn’t a network tunnel. It runs queries on Fabric’s behalf, which is exactly why notebooks couldn’t use it until now.

So the real question is how to give Spark a network path, or how to avoid needing one. There are three legit options.

Option 1: Managed private endpoint to a Private Link Service

This is the direct path, and it’s the only one where pyodbc or JDBC from the notebook actually works. A Fabric managed private endpoint connects the workspace’s managed network to an Azure Private Link Service, which forwards traffic over ExpressRoute or VPN to the on-prem SQL Server.

What you need on the Azure side:

  • An Azure VNet connected to on-prem through ExpressRoute or a VPN gateway.
  • A Standard internal load balancer in front of the target, plus forwarder VMs that NAT the traffic to the SQL Server. Microsoft’s example uses iptables DNAT rules on Linux VMs. Private Link Service Direct Connect, in preview, removes the forwarder VMs but only supports static destination IPs in listed regions.
  • A Private Link Service on that load balancer.
  • A managed private endpoint in the Fabric workspace that references the Private Link Service and the SQL Server’s FQDN. This one can only be created through the REST API, not the UI. The data source owner then approves the request in Azure.

After that, the notebook code is plain JDBC:

jdbc_url = "jdbc:sqlserver://sqlserver.corp.contoso.com:1433;database=SalesDB"
props = {
    "user": "<username>",
    "password": notebookutils.credentials.getSecret("<key-vault-uri>", "<secret-name>"),
    "driver": "com.microsoft.sqlserver.jdbc.SQLServerDriver",
}

df = spark.read.jdbc(url=jdbc_url, table="dbo.Orders", properties=props)
df.write.mode("overwrite").format("delta").saveAsTable("bronze_orders")

Here, there is no 180-second limit, Spark-parallel reads with partitionColumn, and you can write back to the source. Microsoft lists notebooks (Spark and Python), Spark job definitions, materialized lake views, and Livy endpoints as able to use the endpoint.

The price is setup effort (which is significant) and slower sessions. Once a workspace has a managed virtual network, starter pools are disabled, and Microsoft says Spark sessions can take around 3 to 5 minutes to start. Every interactive session in that workspace pays that, not just the ones that touch on-prem data.

Option 2: Ingest first with a pipeline or Copy job

The established pattern still works, and for bulk loads it’s still the right one. A pipeline Copy activity or a Copy job reads through the gateway and writes to a lakehouse, and the notebook processes the Delta tables from there. Copy job also supports on-premises SQL Server as a CDC source, and can merge the captured changes into a lakehouse table. There’s no notebook-side timeout, and the data volume is the gateway’s problem, not Power Query’s.

Option 3: Mirror the database

If the goal is “the SQL Server tables, in OneLake, current”, mirroring is the least code. Mirroring for SQL Server 2016 to 2022 uses Change Data Capture, and needs an on-premises data gateway or a VNet data gateway. SQL Server 2025 uses change feed instead, and for on-prem instances requires Azure Arc. The notebook then reads mirrored Delta tables like any other.

Dataflow Gen2 through the gateway is the fourth way to land data, if the transformation logic should live in Power Query anyway.

What about “the predecessor”? The Execute Query REST API

The API still exists, and it’s what a notebook used before notebookutils.powerquery. It runs M inside a Dataflow Gen2 (CI/CD) item, which supplies the connections and gateway routing, and returns an Apache Arrow stream. It’s read-only, evaluations must finish within 90 seconds, and usage shows up as “Dataflows Gen2 Run Query API” in the Capacity Metrics app. The new powerquery module is the simpler choice: no dataflow item to maintain, no token handling, and twice the time available.

When to choose what?

OptionNetwork set-upData volumeCode in the notebookWrite backBest for
notebookutils.powerqueryExisting gateway and connectionWhatever finishes in 180 secondsPower Query MNoLookups, reference data, small incremental slices, ad hoc reads
Managed private endpoint + JDBC or pyodbcAzure VNet, ExpressRoute or VPN, load balancer, Private Link ServiceNo notebook-side limit, parallel readsPython, SparkYesLarge or frequent reads where Spark should own the whole load
Pipeline or Copy job, then notebookExisting gatewayBulk, incremental, CDC with Copy jobNone for extractionCopy activity can writeScheduled ingestion, initial loads
Mirroring, then notebookExisting gateway (or VNet gateway)Selected tables or the whole database, continuouslyNone for extractionNoKeeping SQL Server tables current in OneLake

The question that sorts most cases is whether the notebook needs to own the extraction. If it only needs the data, landing it with a Copy job or mirroring is simpler and already battle-tested. If the notebook has to decide at runtime what to read, notebookutils.powerquery covers it for small reads, and a managed private endpoint covers it for everything else.

Where does notebookutils.powerquery fit?

notebookutils.powerquery closes a gap that people have asked about on the Fabric forums for well over a year (if not more): a notebook that needs a few on-prem rows no longer needs a pipeline in front of it. It does that with infrastructure most Fabric tenants already have, a gateway and a connection, and without touching complex Azure networking.

However, just to be clear, it isn’t an ingestion engine. The 180-second limit, the read-only scope, and the (still) preview status put it next to the notebook’s logic, not in front of it. A good test is the sentence “the notebook needs to look something up on-prem”. If that describes your case, this feature fits. If the sentence is “the notebook needs to load the on-prem table”, use a Copy job or mirroring, or build the managed private endpoint if Spark really has to read it directly.

So, to conclude, regardless of how cool this new feature looks at first glance, I probably won’t change how I design ingestion workloads because of this. Copy job/Copy data/Mirroring stay the default for moving on-prem data into Fabric. Where notebookutils.powerquery might be a valid option is the small stuff around ingestion: control tables, lookups, and checks that used to need a pipeline just to read a few rows.

Thanks for reading!

Sources

Last Updated on December 3, 2026 by Nikola

Spread the music: