Sitemap
DBSQL SME Engineering

Publication for content from the DBSQL SME group and the surrounding community on DBSQL best practices, new design patterns, creative solutions, and real world user stories all in one place.

Databricks SQL Orchestration Patterns with For Each and Dynamic Value References

8 min readApr 16, 2025

--

Press enter or click to view image in full size
Dynamic SQL Orchestration on DBSQL with Workflows

Author

Justin Kolpak, Sr. Solutions Architect @ Databricks

Introduction

To reduce the burden of writing and maintaining repetitive, boilerplate code, it’s often a best practice to build parameterized pipelines for the more common, repetitive tasks (for example, ingesting data from the source), and pass in the relevant inputs to those pipelines. The result is a solution that requires less development time, a smaller, more maintainable code base, and ultimately allows for more time to focus on the more interesting and value-add responsibilities.

With recent enhancements to the Databricks Workflows product, you can build out this entire pattern using Databricks native functionality! This blog presents 3 orchestration patterns to build robust configuration-driven, parameterized, SQL-based ETL pipelines with Databricks SQL and Workflows using the For Each task type and the new dynamic value references for SQL outputs.

Feature Overview

Logically, this configuration-driven pattern relies on three key pieces of functionality:

  1. Write code with parameters: Of course, we’ll need the ability to write parameterized code, and luckily, this has long been supported in Databricks. In the examples to follow, we’ll show how this can be used with Databricks SQL Query Parameters using the :parameter syntax.
  2. Retrieve and pass in parameters to each iteration of the loop: Once we have our parameterized code, we need to figure out which inputs to pass into the query. There are many ways to store these configurations and retrieve the values, but in this blog, we’ll focus on doing this in a SQL-first approach by retrieving the inputs with a Databricks SQL query and passing in the parameters via dynamic value references for SQL outputs.
  3. Loop/iterate over a set of inputs: Finally, you need a looping construct to iterate through the parameters. For this, we’ll use the Databricks Workflows For Each Task Type.

Examples

Let’s dig into the details to show exactly how this pattern works. All of the code to follow is available in this GitHub Repository. The Workflows are represented as Databricks Asset Bundles, making it easy to recreate in your own workspace and follow along.

For context, we have a dataset stored as text-delimited files in cloud object storage that we’d like to ingest and process into bronze and silver layers. We’ll start with a simple base case and add on complexity from there.

Example 1: Simple For Each

Let’s start with the basics. In this example, we have a basic SQL query that creates a Delta Lake table using the COPY INTO function, which reads data from a file path and uses a few other options to properly parse a delimited file. I know this is a pattern that I’ll want to use more than once, so I write the query with Query Parameters.

-- Declare Variables
DECLARE OR REPLACE VARIABLE _create_table_sql STRING;
DECLARE OR REPLACE VARIABLE _copy_into_sql STRING;


-- Create Table
SET VAR _create_table_sql = 'CREATE TABLE IF NOT EXISTS ' || :tgt_catalog || '.' || :tgt_schema || '.' || :tgt_table || ' (' || :src_column_list || ' , _last_modified_ts timestamp' || ')
TBLPROPERTIES (delta.enableChangeDataFeed = true)';


SELECT _create_table_sql;
EXECUTE IMMEDIATE _create_table_sql;


-- COPY INTO Table
SET VAR _copy_into_sql = "COPY INTO " || :tgt_catalog || '.' || :tgt_schema || '.' || :tgt_table || "
BY POSITION
FROM (
SELECT
*
, now() AS _last_modified_ts
FROM '" || :src_path || "'
)
FILEFORMAT = "|| :src_format || "
FORMAT_OPTIONS ('mergeSchema' = 'true', 'sep' = '"|| :src_sep || "')
COPY_OPTIONS('mergeSchema' = 'true')";


SELECT _copy_into_sql;
EXECUTE IMMEDIATE _copy_into_sql;

How can we go about applying this code on every file location and bronze table I’d like to produce? Historically, I might have reached for a Python for loop + the Databricks %run command or used an external orchestrator, each which introduces their own drawbacks.

Enter: The For Each task in Databricks Workflows. Here’s how it works:

Start out by creating a new task, and setting the Type to “For Each” and providing an array of inputs in the “Inputs” field. In this case, the Inputs align to the parameters in the query above:

[{"bronze_catalog":"justin_kolpak","
bronze_schema":"tpch_blog","bronze_table":
"bronze_customer",
"primary_key":"c_custkey",
"silver_catalog":"justin_kolpak",
"silver_schema":"tpch",
"silver_table":"silver_customer",
"src_column_list":"c_custkey int, c_name string, c_address string, c_nationkey int, c_phone string, c_acctbal decimal(15,2), c_mktsegment string, c_comment string, c_dummy string",
"src_format":"csv",
"src_header":"false",
"src_path":"/Volumes/justin_kolpak/tpch/raw/customer",
"src_sep":"|"},

{"bronze_catalog":"justin_kolpak","bronze_schema":"tpch_blog","bronze_table":"bronze_orders","primary_key":"o_orderkey","silver_catalog":"justin_kolpak","silver_schema":"tpch","silver_table":"silver_orders","src_column_list":"o_orderkey int, o_custkey int, o_orderstatus string, o_totalprice double, o_order_date date, o_orderpriority string, o_clerk string, o_shippriority int, o_comment string, o_dummy string","src_format":"csv","src_header":"false","src_path":"/Volumes/justin_kolpak/tpch/raw/orders","src_sep":"|"},{"bronze_catalog":"justin_kolpak","bronze_schema":"tpch_blog","bronze_table":"bronze_lineitem","primary_key":"l_orderkey","silver_catalog":"justin_kolpak","silver_schema":"tpch","silver_table":"silver_lineitem","src_column_list":"l_orderkey int, l_partkey int, l_suppkey int, l_linenumber int, l_quantity decimal(15,2), l_extendedprice decimal(15,2), l_discount decimal(15,2), l_tax decimal(15,2), l_returnflag string, l_linestatus string, l_shipdate date, l_commitdate date, l_receiptdate date, l_shipinstruct string, l_shipmode string, l_comment string, l_dummy string","src_format":"csv","src_header":"false","src_path":"/Volumes/justin_kolpak/tpch/raw/lineitem","src_sep":"|"}]
Press enter or click to view image in full size
For Each task type can take a hard-coded list of values as an “Input”

Then from there, add in the “inner” task that the For Each operator will iterate through.

Press enter or click to view image in full size
Inner task is a SQL file that takes the values from the “Inputs” field as Parameter values

And that’s it!

Get Databricks SQL SME’s stories in your inbox

Join Medium for free to get updates from this writer.

When this job runs, the tasks all run concurrently and the UI shows execution details at the iteration-level, making it simple to monitor, observe, and debug issues with this pipeline. In the absence of a capability like this, we would likely only see 1 Success (if everything succeeded) or 1 Failure (if at least one of the components failed) at the job- or task-level, and any troubleshooting efforts would begin with digging through the code/logs trying to find out what specifically caused the failure. By having iteration-level details, we can immediately see what succeeded, what failed, how long it took, what parameters it used, what the code looked like, etc.

Press enter or click to view image in full size
Example Job Run Details show the iteration-level metrics, including duration, status, and input parameters used
Press enter or click to view image in full size
Succesfull run example

Example 2: For Each + Dynamic Value Reference for SQL Outputs

What if the list of inputs is constantly changing over time? In the real world, things are always in flux, being added, removed, or modified, and it’s not practical to go into the Workflow and update the “Inputs” field every time there’s a change. Instead, let’s store these inputs in a configuration file (using a JSON file here, but a table or a YAML file would work great too!) and see how we can fit them into this Workflow.

In this Workflow, we’ve added an initial task that queries the configuration table/file and returns a result set with all of the parameters to pass into the subsequent task. Then using task values, we can pass in these parameters to downstream tasks.

Press enter or click to view image in full size
Task values from get_ingest_metadata task can be used in the load_bronze for each task

Task values have been around for a long time with Python, which would require explicitly setting the task values at the end of the get_ingest_metadata task. Now, with dynamic value references for SQL outputs, we 1) can use SQL to do this and 2) don’t need to explicitly set task values — we just need to write a SQL query that returns a meaningful result set and use it through the rest of the workflow.

Here’s the get_ingest_metadata task — it’s a SQL query that returns a result set with all of the parameters needed downstream.

Press enter or click to view image in full size
Example dynamic SQL query that creates multiple inputs from a SQL query

Instead of hardcoding the values in the “Inputs” field, as in Example 1 above, this Workflow can be more dynamic by setting the “Inputs” field to {{tasks.get_ingest_metadata.output.rows}}. With this configuration, the Workflow will use the result set of the previous SQL task (get_ingest_metadata) and pass them in as an input to the For Each operator (load_bronze, in this case).

Press enter or click to view image in full size
Using the dynamic SQL output values in a downstream dynamic SQL forEach task

Example 3: For Each + Dynamic Value References + Run Job

In the examples above, the For Each task is iterating over just a single task. What if the task we want to iterate over is more complex than just 1 task? Enter: the Run Job task type, which supports the ability to run another job from the current job. This provides the ability to build highly modular, DRY (Don’t Repeat Yourself) workflows, and when combined with For Each and dynamic value references, creates a very robust, maintainable, and observable pipeline — all with SQL!

Instead of the inner task using a SQL File or Query, we can set it to “Run Job”. If there are needs for more advanced logic than can reasonably be expressed with a single task (as in Examples 1 and 2), being able to build a separate job with orchestration logic provides more flexibility in your workflow definitions.

In this example, it’s a relatively straightforward job consisting of two tasks to be run in sequence, but this pattern can be extended to much more complex tasks. For example, you may want to build conditional control flow logic into your workflow, or you may find yourself with code written in different languages (e.g. a SQL query and a Python script) that you’d like to orchestrate as part of the same process.

By using this pattern, you can handle highly complex orchestration patterns, while still taking advantage of a configuration-driven approach facilitated by the dynamic value references and For Each operator.

Press enter or click to view image in full size
Inner Task is set to Run Job type
Press enter or click to view image in full size
load_bronze_silver is defined as separate job with a more complex structure than the single task

How To Get Started

All of the resources in this blog are available on this GitHub Repository as a Databricks Asset Bundle. Follow the instructions in the Getting Started section.

Conclusion

These examples are just scratching the surface on what can be accomplished with these tools. Workflows supports a variety of advanced orchestration operators that we didn’t have a chance to discuss (like conditional execution, run dbt projects or DLT pipelines, and much more). By putting all of these tools together, inspired by the patterns outlined in this blog, you can build highly sophisticated data pipelines using just Databricks Workflows + DBSQL.

If you have any questions, feedback, or ideas on how this can be extended to other use cases, feel free to reach out to me at justin.kolpak@databricks.com.

Note: All code is provided as-is and is not subject to support SLAs. The examples in this code base are specifically designed to work with the TPC-H dataset, and any production application of this will require some level of customization to work with your datasets and requirements. The intention of publishing these examples is to highlight the high-level design patterns that you can build using Databricks SQL and Workflows.

Databricks SQL SME
Databricks SQL SME

Written by Databricks SQL SME

One stop shop for all technical how-tos, demos, and best practices for building on Databricks SQL

DBSQL SME Engineering
DBSQL SME Engineering

Published in DBSQL SME Engineering

Publication for content from the DBSQL SME group and the surrounding community on DBSQL best practices, new design patterns, creative solutions, and real world user stories all in one place.