When you need this
You have a notebook or job that builds SQL with f-strings, such as spark.sql(f"DELETE FROM {tbl} WHERE dt = '{d}'"), and it breaks on a quote in a value, or it is open to injection from a widget. Or you have a maintenance task that has to loop over tables, and you would rather keep it in SQL than wrap it in Python.
Databricks SQL can do all of this natively. The table below shows which feature to use for each job and the minimum runtime. Each feature is covered in a section further down.
| You want to | Use | Minimum |
|---|---|---|
| Pass a value safely | Named parameter marker :name | DBR 12.1+ / SQL warehouse |
| Pass a table, schema or column name | IDENTIFIER(:name) | DBR 13.3 LTS+ |
| Hold a value across statements | DECLARE VARIABLE / SET VAR | DBR 14.1+ |
| Run a SQL string built at runtime | EXECUTE IMMEDIATE ... USING | DBR 14.3 LTS+ |
| Use loops, IF and error handlers | BEGIN ... END SQL scripting | DBR 16.3+ (Public Preview) |
Tip
Version floors change and some features start in preview. Check the SQL language reference for your runtime before you rely on a feature in a production job, and look at the "Applies to" line on each page.
Named parameter markers
In the SQL editor, notebooks and dashboards, write :name wherever a literal value goes. The UI shows an input box for each one.
SELECT order_id, amount
FROM sales.silver.orders
WHERE order_date = :run_date
AND region = :region;
Markers only replace values. You cannot use them for keywords, operators or object names. For those, use IDENTIFIER() (next section).
From Python, pass args to spark.sql. The value is bound as a literal, so a quote or a semicolon inside it cannot change the statement.
df = spark.sql(
"SELECT * FROM sales.silver.orders WHERE order_date = :d AND region = :r",
args={"d": "2026-11-15", "r": "EMEA"},
)
Positional ? markers also work, with a list instead of a dict (PySpark 3.5+):
spark.sql("SELECT * FROM sales.silver.orders WHERE region = ?", args=["EMEA"])
Warning
Older notebooks use
${var}or$varsubstitution from widgets. That is plain text replacement, so values are not escaped, and the syntax is deprecated in favour of parameter markers. Move those notebooks to:namemarkers when you touch them.
Common errors
| Error | Cause | Fix |
|---|---|---|
UNBOUND_SQL_PARAMETER | A :name in the text has no value | Add the key to args, or fill in the widget or parameter box |
Parse error near :tbl | Marker used as a table name | Wrap it: IDENTIFIER(:tbl) |
| Date comparison returns no rows | Value bound as a string, column is DATE | Cast it: order_date = CAST(:d AS DATE), or pass a datetime.date |
IDENTIFIER() for object names
IDENTIFIER() takes a constant string expression (a marker, a variable or a literal) and treats it as a name.
-- Table name from a parameter
SELECT COUNT(*) FROM IDENTIFIER(:catalog || '.bronze.' || :table_name);
-- Column name from a parameter
SELECT IDENTIFIER(:col), COUNT(*)
FROM IDENTIFIER(:tbl)
GROUP BY ALL;
-- DDL works too
ALTER TABLE IDENTIFIER(:tbl) SET TBLPROPERTIES ('owner_team' = 'finance');
From Python:
spark.sql(
"OPTIMIZE IDENTIFIER(:t)",
args={"t": "prod.silver.orders"},
)
The string is parsed as a name. Something like orders; DROP TABLE x fails as an invalid identifier instead of running as a second statement. You still need to check which table a caller may name. Unity Catalog grants decide what the run-as identity can touch, so keep job identities scoped.
Session variables
Variables live for the whole session: a notebook attachment, an SQL editor session or a job task.
DECLARE OR REPLACE VARIABLE run_date DATE DEFAULT current_date() - INTERVAL 1 DAY;
DECLARE OR REPLACE VARIABLE row_cnt BIGINT;
SET VAR row_cnt = (SELECT COUNT(*) FROM sales.silver.orders WHERE order_date = run_date);
SELECT run_date, row_cnt;
Use a variable anywhere a constant expression is allowed, including in IDENTIFIER():
DECLARE OR REPLACE VARIABLE tgt STRING DEFAULT 'prod.gold.daily_sales';
SELECT * FROM IDENTIFIER(tgt) LIMIT 10;
SET VAR with a subquery fails if the subquery returns more than one row. Aggregate it, or add LIMIT 1 when any row will do.
EXECUTE IMMEDIATE
Use this when the statement itself has to be built at runtime. Bind values with USING instead of putting them into the string.
DECLARE OR REPLACE VARIABLE stmt STRING;
DECLARE OR REPLACE VARIABLE cnt BIGINT;
SET VAR stmt = 'SELECT COUNT(*) FROM ' || 'prod.silver.orders' || ' WHERE order_date >= :d';
EXECUTE IMMEDIATE stmt INTO cnt USING DATE'2026-11-01' AS d;
SELECT cnt;
Rules worth remembering:
INTOneeds a statement that returns at most one row. Leave outINTOto get a result set.- The string holds exactly one statement. You cannot run a batch separated by semicolons this way.
- Build the string only from trusted values (catalog metadata, fixed lists). Bind anything a user typed with
USING, or pass it throughIDENTIFIER().
SQL scripting: BEGIN ... END
From Databricks Runtime 16.3 and on SQL warehouses, a compound statement gives you local variables, IF, loops and condition handlers in plain SQL. It is in Public Preview, so test it on your runtime before you move production jobs onto it.
Loop over tables and optimize the ones with many small files
BEGIN
DECLARE n INT DEFAULT 0;
FOR t AS
SELECT table_catalog || '.' || table_schema || '.' || table_name AS fqn
FROM prod.information_schema.tables
WHERE table_schema = 'silver'
AND table_type = 'MANAGED'
DO
EXECUTE IMMEDIATE 'OPTIMIZE ' || t.fqn;
SET n = n + 1;
END FOR;
SELECT n AS tables_optimized;
END;
Fail the job on a bad load
BEGIN
DECLARE bad BIGINT;
SET bad = (SELECT COUNT(*) FROM prod.silver.orders
WHERE order_date = current_date() - INTERVAL 1 DAY
AND amount IS NULL);
IF bad > 0 THEN
SELECT raise_error(concat('Null amounts in yesterday''s load: ', bad));
END IF;
END;
raise_error makes the statement fail, so the job task is marked failed and your failure alerts fire.
Log a failure with an EXIT handler
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
INSERT INTO ops.audit.maintenance_log
VALUES (current_timestamp(), 'vacuum_failed', 'prod.silver.orders');
END;
VACUUM prod.silver.orders;
INSERT INTO ops.audit.maintenance_log
VALUES (current_timestamp(), 'vacuum_ok', 'prod.silver.orders');
END;
An EXIT handler runs its body and then leaves the block that declared it. CONTINUE handlers, which resume after the failing statement, need a newer runtime (18.1+ at the time of writing).
Caution
A handler that swallows every
SQLEXCEPTIONturns a failed job into a green run. Log the failure and then re-raise it withraise_error, unless you really mean to ignore it.
Using these in jobs
- SQL file or notebook tasks: job and task parameters reach SQL as named markers (
:run_date). Check that the parameter names in the job match the markers exactly, because names are case-sensitive. - Python tasks: read the parameter with
dbutils.widgets.get("run_date")and pass it throughargs=. Don't put it into an f-string. - Run on a SQL warehouse or a recent runtime. If an older cluster reports a syntax error on
IDENTIFIER,DECLAREorBEGIN, check its runtime version first.
Prevent it next time
- Search your repos for
spark.sql(f"and${and move them to markers. Do the jobs that take widget input or external input first. - Add a review rule: no string-built SQL unless the pieces come from catalog metadata, and even then wrap names in
IDENTIFIER(). - Run maintenance and data-quality SQL under a service principal that only has the grants it needs, so a bad parameter can't reach other catalogs.
- Write down the runtime floor for each scripting feature you use in the job's README, so a runtime pin or downgrade doesn't break it without anyone noticing.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get