Dynamic SQL Generation
A powerful pattern in hibase is generating SQL dynamically from metadata tables. Instead of hardcoding table names, column lists, or conditions, you build the SQL programmatically using a parameter query — then execute it in the main step.
How It Works
The pattern has two parts:
- Parameter query: Generates SQL by iterating over rows in a metadata table using
STRING_AGG+FORMAT - Step SQL: Executes the generated query using
{{ raw_value($generated_sql) }}
Example: Dynamic Table Union
Imagine you have the same table structure across multiple schemas, and you want to create a single unified view:
Metadata table (meta.source_tables):
| schema_name | table_name | tenant_id |
|---|---|---|
| client_a | orders | a001 |
| client_b | orders | b002 |
| client_c | orders | c003 |
Parameter Query (generates the UNION ALL):
SELECT
STRING_AGG(
FORMAT(
"""
SELECT *, '%s' AS tenant_id
FROM `%s.%s`
""",
tenant_id,
schema_name,
table_name
),
'\n UNION ALL \n'
) AS union_sql
FROM meta.source_tables
Step SQL (executes the generated query):
CREATE OR REPLACE TABLE datamarts.all_orders AS
{{ raw_value($union_sql) }}
The parameter query produces a $union_sql parameter containing the full UNION ALL query. The step SQL injects it with raw_value() (no quoting) and wraps it in a CREATE TABLE.
Example: Dynamic Column Aggregation
Generate pivot-like aggregations dynamically from a column list:
Parameter Query:
SELECT
STRING_AGG(
FORMAT(
"SUM(CASE WHEN metric_name = '%s' THEN metric_value END) AS %s",
metric_name,
REPLACE(LOWER(metric_name), ' ', '_')
),
',\n'
) AS agg_columns
FROM (SELECT DISTINCT metric_name FROM source.metrics)
Step SQL:
SELECT
date,
dimension,
{{ raw_value($agg_columns) }}
FROM source.metrics
GROUP BY date, dimension
Why Use raw_value()
The raw_value() function is essential for this pattern because it injects the parameter without SQL quoting. Without it, the generated SQL would be wrapped in quotes and treated as a string literal instead of being executed as SQL.
See the Using Parameters docs for more on raw_value() vs regular interpolation.
Tips
- Always test your parameter query first — run it standalone to see the generated SQL before using it in a step
- Use
FORMATwith triple-quoted strings ("""...""") for multi-line SQL generation STRING_AGGwith a separator like'\n UNION ALL \n'or',\n'is the standard pattern for joining multiple generated fragments- Combine with cross-environment workflows to generate environment-aware queries
- Consider adding
ORDER BYin theSTRING_AGGto ensure deterministic output