Sub topic 9
Making queries reusable with parameters
A query that hard-codes a filter value has to be edited every time the value changes. Parameters turn those values into inputs. You write the query once, and the SQL editor shows a field for each parameter. This chapter covers named parameter markers, widget types, how values are bound, and the errors you are most likely to meet.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL with
SELECT,WHERE, andORDER BY. - Open the SQL editor and run a query on a running SQL warehouse.
- Address a table with a three-level name such as
samples.nyctaxi.trips.
What a parameter is
A parameter is a named placeholder in a query. At run time, the editor replaces the placeholder with a value you supply. The value is passed to the engine as a typed value. It is not pasted into the query text as a string, so a parameter cannot change the structure of the statement.
The marker syntax is a colon followed by a name:
SELECT
pickup_zip,
trip_distance,
fare_amount
FROM samples.nyctaxi.trips
WHERE trip_distance > :min_distance
ORDER BY fare_amount DESC
LIMIT 50;When the editor sees :min_distance, it adds an input field named min_distance above the results. Type a number, such as 10, and run the query. Change the number and run it again. The query text stays the same.
How the editor handles parameters
Three points follow from this flow:
- The editor finds markers by scanning the query text. If you delete a marker, its field disappears.
- You choose the field type. The type decides how the value is interpreted.
- The warehouse receives the statement and the bound value separately.
Parameter types
The type you pick for a field controls how your input is read. A wrong type is the most common reason a parameterized query fails or returns nothing.
| Type | Use it for | Example input |
|---|---|---|
| Text | Strings such as names or codes | `10001` |
| Number | Integers and decimals | `10.5` |
| Date | A calendar date | `2026-01-31` |
| Date and time | A timestamp | `2026-01-31 08:00:00` |
| Dropdown list | A fixed set of allowed values | `Credit`, `Cash` |
Exact type names in the interface can vary between releases. Check the type selector in your workspace if a label differs from this table.
A zip code is a good example of the type problem. The column pickup_zip in the sample data is an integer, but zip codes are identifiers, not quantities. If a column stores them as text, a Number parameter will not match. Match the parameter type to the column type.
Using more than one parameter
You can use as many markers as you need. Each distinct name gets its own field. Using the same name twice in one query gives you one field that feeds both places.
SELECT
pickup_zip,
COUNT(*) AS trips,
ROUND(AVG(fare_amount), 2) AS avg_fare
FROM samples.nyctaxi.trips
WHERE trip_distance BETWEEN :min_distance AND :max_distance
GROUP BY pickup_zip
HAVING COUNT(*) >= :min_trips
ORDER BY trips DESC
LIMIT 20;This query shows three fields: min_distance, max_distance, and min_trips. Set them to 1, 5, and 100 to see busy zones for short trips.
Choosing a type for each field
Open the parameter settings for a field to set its type and, for a dropdown, its allowed values. A dropdown limits input to values you approve. That helps when the query will be shared with people who do not write SQL, because it prevents typos.
For a dropdown whose values should come from data, base the list on another query. The list then stays current as the data changes.
Parameters are values, not identifiers
A named marker stands in for a value. It does not stand in for a table name, a column name, or a keyword. This query is invalid:
SELECT * FROM :table_name LIMIT 10;If you need to switch tables or columns, Databricks provides the IDENTIFIER clause, which treats a string value as an object name:
SELECT *
FROM IDENTIFIER(:table_name)
LIMIT 10;Enter the full three-level name, for example samples.nyctaxi.trips, in the table_name field. Because the value becomes an object name, restrict it with a dropdown. Free text lets a user point the query at any table they can read.
Running the query without a value
If a parameter field is empty, the query does not run, or it runs with a null value, depending on the field type. A comparison with null never matches, so this filter returns no rows:
SELECT COUNT(*) AS trips
FROM samples.nyctaxi.trips
WHERE trip_distance > :min_distance;If you want an optional filter, write the logic yourself. Give the field a default value, or use a pattern such as this one:
SELECT COUNT(*) AS trips
FROM samples.nyctaxi.trips
WHERE :min_distance IS NULL OR trip_distance > :min_distance;This pattern is easy to misread. Test it with a value and with an empty field before you share the query.
Parameters and the other pieces
- Saved queries. A saved query keeps its markers and the last values you used. Anyone who opens it sees the same fields. See the chapter on saving and sharing queries.
- Query history. Each run is recorded with the statement text. Compare runs of the same query in query history to see how different values change duration.
- Dashboards and alerts. A dashboard can pass its own filter values into a parameterized query. Alerts can run a query with fixed values. See the later chapter on dashboards and alerts.
- Programmatic access. The Statement Execution API accepts named parameters in its request body, so the same marker syntax works from code. The following request is a sketch that passes
min_distanceas a typed value:
curl -X POST "$DATABRICKS_HOST/api/2.0/sql/statements" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"warehouse_id": "'"$WAREHOUSE_ID"'",
"statement": "SELECT COUNT(*) FROM samples.nyctaxi.trips WHERE trip_distance > :min_distance",
"parameters": [
{"name": "min_distance", "value": "10", "type": "DOUBLE"}
],
"wait_timeout": "30s"
}'The type field is the API counterpart of the type selector in the editor. The value is sent as a string and cast to that type.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No field appears | The marker is misspelled, or the cursor is in a comment | Check that the text is `:name`, outside a comment or string literal |
| Query returns zero rows | The field is empty, or the type does not match the column | Enter a value, or change the field type |
| Type conversion error | A text value was entered in a Number field | Enter a valid number, or change the type |
| Marker is treated as plain text | The marker is inside quotes, as in `':name'` | Remove the quotes. Let the field type handle them |
| `IDENTIFIER` fails | The name is not fully qualified or does not exist | Enter `catalog.schema.table` and confirm you can read it |
| Date filter returns the wrong days | Date type used against a timestamp column | Cast or compare with a range, such as `>= :start AND < :end` |
The date case deserves an example. A Date value means midnight at the start of that day. Using = :day against a timestamp column returns only rows at exactly midnight. Use a half-open range instead:
SELECT COUNT(*) AS trips
FROM samples.nyctaxi.trips
WHERE tpep_pickup_datetime >= :start_date
AND tpep_pickup_datetime < DATE_ADD(:start_date, 1);Design habits
- Name parameters for what they mean:
min_distance, notp1. - Pick the narrowest type that fits, and use dropdowns for closed sets.
- Always set sensible defaults so that a new reader can run the query immediately.
- Keep the parameterized query simple. If you need heavy branching, move that logic into a view or a separate query.
Exercise
A teammate saves this query. It has a Text parameter named zip_code, and it returns no rows even though the data contains the zip they typed. What two checks would you make first?
SELECT COUNT(*) FROM samples.nyctaxi.trips WHERE pickupzip = ':zipcode'
Show answer
First, check the quotes. The marker is inside a string literal, so the engine compares against the literal text ':zipcode' instead of the entered value. Remove the quotes: WHERE pickupzip = :zipcode. Second, check the type match. The pickupzip column is an integer, so the field should be a Number, not Text. A mismatch between the parameter type and the column type can cause no matches or a conversion error.
Exercise
Rewrite this query so that users choose the table from a dropdown instead of editing the SQL, and explain why a dropdown is a better choice than a free-text field here: SELECT * FROM samples.nyctaxi.trips LIMIT 10
Show answer
Use IDENTIFIER with a named marker: SELECT * FROM IDENTIFIER(:tablename) LIMIT 10. Set the tablename field to a dropdown with approved full names, such as samples.nyctaxi.trips. A dropdown is better because the value becomes an object name, so free text would let a user point the query at any table they can read. A dropdown limits that to tables you approved and prevents typos.