Home / Databricks on Azure

Databricks on AzureHow-toIntermediate

Parallel JDBC reads from Azure SQL in Databricks: partitionColumn, bounds, fetchsize and pushdown

A Databricks job that reads a big Azure SQL or SQL Server table runs as one slow task. Split it into parallel queries with partitionColumn or predicates, tune fetchsize and push filters down without overloading the database.

Deepak Bhardwaj7 min read

Applies toAzure Databricks Runtime 13.3 LTS and later, Apache Spark JDBC data source, Azure SQL Database, Azure SQL Managed Instance, SQL Server 2016+

Symptom

A notebook or job reads a table from Azure SQL with spark.read.format("jdbc"). It takes an hour or more. The Spark UI shows a single task in that stage while the other executors sit idle. The database shows one long-running SELECT.

That is the default behaviour. Without partitioning options, Spark opens one connection and pulls the whole result through it. This post covers splitting the read safely. Writes are a separate problem with different settings.

1. Confirm it's a single-partition read

df = (spark.read.format("jdbc")
      .option("url", jdbc_url)
      .option("dbtable", "dbo.SalesOrderLine")
      .option("user", user).option("password", pwd)
      .load())

print(df.rdd.getNumPartitions())   # 1 = one query, one connection

On the database side, give the connection a name so you can find its sessions:

jdbc_url = (
    "jdbc:sqlserver://sql-prod.database.windows.net:1433;"
    "database=sales;encrypt=true;trustServerCertificate=false;"
    "loginTimeout=30;applicationName=dbx-sales-ingest"
)
user = dbutils.secrets.get("kv-sql", "sql-reader-user")
pwd  = dbutils.secrets.get("kv-sql", "sql-reader-password")
-- On Azure SQL: what is this job doing right now?
SELECT s.session_id, r.status, r.wait_type, r.cpu_time, r.logical_reads, t.text
FROM sys.dm_exec_sessions s
LEFT JOIN sys.dm_exec_requests r ON r.session_id = s.session_id
OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE s.program_name = 'dbx-sales-ingest';

2. The options that matter

Option What it does Notes
partitionColumn Column used to split the read Numeric, date or timestamp. Should be indexed
lowerBound / upperBound Range used to compute the split points They don't filter rows. Values outside the range land in the first and last partitions
numPartitions Number of parallel queries, and the max number of connections Start at executor cores, rarely above a few dozen
fetchsize Rows per network round trip Test values in the low thousands
dbtable Table or a subquery with an alias Use this, not query, when partitioning
query Free-form query Can't be combined with partitionColumn
pushDownPredicate Push filter() into the SQL WHERE Default true
pushDownAggregate Push simple aggregates down Default false. Check your runtime's Spark docs
sessionInitStatement SQL run when each connection opens Useful for SET options

3. Partition on an indexed key

Get the real bounds first. This is a cheap query when the column is indexed:

bounds = (spark.read.format("jdbc")
          .option("url", jdbc_url).option("user", user).option("password", pwd)
          .option("query", "SELECT MIN(SalesOrderLineID) AS lo, MAX(SalesOrderLineID) AS hi FROM dbo.SalesOrderLine")
          .load().first())

df = (spark.read.format("jdbc")
      .option("url", jdbc_url).option("user", user).option("password", pwd)
      .option("dbtable", "dbo.SalesOrderLine")
      .option("partitionColumn", "SalesOrderLineID")
      .option("lowerBound", bounds.lo)
      .option("upperBound", bounds.hi + 1)
      .option("numPartitions", 16)
      .option("fetchsize", 5000)
      .load())

print(df.rdd.getNumPartitions())   # 16

Spark sends 16 queries of the form WHERE SalesOrderLineID >= x AND SalesOrderLineID < y. Each one should be an index range seek. If the column isn't indexed, every partition scans the whole table and the database does 16 times the work.

Warning

numPartitions is also the number of concurrent sessions opened against the database. On a small Azure SQL tier, 32 parallel scans can max out CPU, log or worker limits and slow down the application that shares the database. Check the current limits for your service tier, start low and raise the value while you watch the database's CPU and IO.

Filter and select inside the subquery

lowerBound and upperBound don't filter. To read only recent rows or fewer columns, put the filter and column list in dbtable as an aliased subquery:

src = """(SELECT SalesOrderLineID, OrderDate, ProductID, Quantity, LineTotal
          FROM dbo.SalesOrderLine
          WHERE ModifiedDate >= '2026-11-01') AS src"""

df = (spark.read.format("jdbc")
      .option("url", jdbc_url).option("user", user).option("password", pwd)
      .option("dbtable", src)
      .option("partitionColumn", "SalesOrderLineID")
      .option("lowerBound", lo).option("upperBound", hi + 1)
      .option("numPartitions", 8)
      .load())

A .filter() on the DataFrame is usually pushed down too, when pushDownPredicate is on. Check with df.explain() and look for PushedFilters. Functions Spark can't translate stay in Spark, and the full table comes over the wire.

4. Skewed or sparse keys: use predicates

Identity keys with big gaps, or a date column where the last month holds half the rows, give uneven partitions. One task runs for an hour and the rest finish in a minute. Write the split yourself with predicates. Each string becomes one partition's WHERE clause:

predicates = [
    "OrderDate >= '2026-01-01' AND OrderDate < '2026-04-01'",
    "OrderDate >= '2026-04-01' AND OrderDate < '2026-07-01'",
    "OrderDate >= '2026-07-01' AND OrderDate < '2026-10-01'",
    "OrderDate >= '2026-10-01' AND OrderDate < '2026-11-01'",
    "OrderDate >= '2026-11-01' AND OrderDate < '2026-11-16'",
    "OrderDate >= '2026-11-16'",
]

df = spark.read.jdbc(
    url=jdbc_url,
    table="dbo.SalesOrderLine",
    predicates=predicates,
    properties={"user": user, "password": pwd, "fetchsize": "5000"},
)

Make sure the predicates cover every row exactly once. Gaps lose data and overlaps duplicate it. Add OR OrderDate IS NULL to one predicate if the column is nullable.

To get balanced ranges, check the distribution on the source first:

SELECT DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) AS month_start, COUNT_BIG(*) AS row_count
FROM dbo.SalesOrderLine
GROUP BY DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1)
ORDER BY month_start;

5. Keep the database healthy

  • Read from a replica. On Business Critical, Premium and Hyperscale tiers, and on geo-replicas or failover groups, add applicationIntent=ReadOnly to the URL. Read scale-out sends the session to a readable secondary, so the primary isn't loaded.
  • Know that the result isn't one snapshot. Each partition is a separate query in its own transaction. If rows change during the read, partitions see different points in time. For consistent extracts, read up to a fixed watermark (ModifiedDate < @run_start) or use the source's snapshot features.
  • Run heavy extracts off-peak and give them their own SQL login, so you can find them and limit them.
  • Avoid fetchsize extremes. Very small values add round trips. Very large ones cost executor memory per open cursor.

Tip

Stage the result in Delta straight away (df.write.mode("overwrite").saveAsTable(...)) and run your transformations from there. Every action on a JDBC DataFrame that isn't cached sends the queries to the database again.

6. Incremental instead of full reads

Most "slow JDBC read" jobs are full reloads that don't need to be. Read only the rows changed since the last run, then MERGE them:

last = spark.sql("SELECT COALESCE(MAX(ModifiedDate), '1900-01-01') AS wm FROM main.bronze.sales_order_line").first().wm

src = f"(SELECT * FROM dbo.SalesOrderLine WHERE ModifiedDate > '{last}') AS src"
changes = (spark.read.format("jdbc")
           .option("url", jdbc_url).option("user", user).option("password", pwd)
           .option("dbtable", src).option("fetchsize", 5000).load())
changes.createOrReplaceTempView("changes")
MERGE INTO main.bronze.sales_order_line t
USING changes s ON t.SalesOrderLineID = s.SalesOrderLineID
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

ModifiedDate needs an index on the source, and the column has to be maintained reliably by the application. Deletes aren't captured this way. If you need them, use change tracking or CDC, or Lakeflow Connect for SQL Server. For ad hoc queries rather than bulk extracts, Lakehouse Federation is usually the better tool.

Prevent it next time

  • Treat a JDBC read without partitionColumn or predicates as a code review flag for any table over a few million rows.
  • Set applicationName on every connection string so DBAs can see which job is running which query.
  • Put numPartitions and fetchsize in job parameters, not hard-coded, so you can tune them without a redeploy.
  • Alert on the job's duration and on the source database's CPU during the extract window.
  • Move full reloads to watermark-based incremental loads once the table is stable.