Databricks SQL (DBSQL) - Advanced Features
Prerequisites
- Databricks CLI v0.205+ installed and authenticated (see
databricks-cli-install skill; for CLI operations see databricks-cli skill)
- A Databricks SQL warehouse (Serverless recommended for AI functions, MVs, and http_request)
Detecting Unity Catalog vs Hive Metastore
Before assuming Unity Catalog is available, always check:
databricks metastores current --output json 2>&1
- If a metastore is returned: Unity Catalog is active. Use three-level naming (
catalog.schema.table) throughout.
- If it errors or returns nothing: The workspace uses the legacy Hive Metastore. In this case:
- Use two-level naming (
schema.table or database.table) instead of three-level
- The
default database is always available
- UC-only features are unavailable: materialized views, AI functions, grants CLI, Liquid Clustering, pipe syntax
- SQL execution via
databricks api post /api/2.0/sql/statements still works with two-level references
- Skip any instructions that reference
catalog.schema.table and adapt to schema.table
When to Use
- User wants to write or debug Databricks SQL (procedural SQL, stored procedures, MVs, AI functions)
- User asks about DBSQL-specific features (pipe syntax, geospatial, collations, http_request)
- User needs data modeling guidance for the Databricks Lakehouse
- User wants to use AI functions (ai_query, ai_classify, ai_extract, etc.) in SQL
Workflow
Convention: All placeholders in <angle-brackets> must be replaced with actual values from the user. All SQL examples use three-level Unity Catalog naming: catalog.schema.object.
Step 1: Detect Intent
Goal: Determine which DBSQL feature area the user needs.
Route by topic:
| User mentions |
Load reference |
| SQL scripting, BEGIN...END, DECLARE, IF/WHILE/FOR, stored procedure, CREATE PROCEDURE, CALL, recursive CTE, WITH RECURSIVE, transaction |
Load references/sql-scripting.md |
| ai_query, ai_classify, ai_extract, ai_gen, ai_summarize, ai_analyze_sentiment, ai_similarity, ai_mask, ai_fix_grammar, ai_forecast, ai_parse_document, vector_search, AI function, http_request, remote_query, read_files, Lakehouse Federation |
Load references/ai-functions.md |
Materialized view, CREATE MATERIALIZED VIEW, refresh, temp table, temporary view, pipe syntax, |> operator |
Load references/materialized-views-pipes.md |
| Geospatial, H3, h3_longlatash3, ST_Point, ST_Contains, spatial, collation, COLLATE, UTF8_LCASE, case-insensitive |
Load references/geospatial-collations.md |
| Data modeling, star schema, dimension table, fact table, Liquid Clustering, partitioning, Z-ORDER, SCD, best practices, performance |
Load references/best-practices.md |
If the intent spans multiple areas, load the primary reference first and additional references as needed.
Step 2: Understand the User's Goal
⚠️ MANDATORY STOPPING POINT: Before writing any SQL, ask the user:
- What are you trying to accomplish?
- Which catalog/schema/tables are involved?
- What SQL warehouse type are you using? (Serverless required for AI functions, MVs, http_request)
Do NOT proceed until the user responds.
Step 3: Write or Debug SQL
Goal: Help the user write, optimize, or debug their SQL.
Actions:
- Use the loaded reference for correct syntax, parameters, and patterns
- Write SQL using three-level Unity Catalog naming (
catalog.schema.table)
- Include comments explaining non-obvious logic
- For procedural SQL: use proper BEGIN...END blocks, DECLARE variables, and error handling
- For AI functions: always include
LIMIT during development to control costs
⚠️ MANDATORY STOPPING POINT: Before executing any DDL or DML (CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, MERGE), present the SQL to the user for approval.
Step 4: Verify Results
Goal: Confirm the SQL works as expected.
Actions:
- If the user approved execution, run the SQL
- Check for errors and suggest fixes if needed
- For materialized views: verify refresh status
- For stored procedures: test with sample parameters
Quick Reference
| Feature |
Key Syntax |
Requires |
Reference |
| SQL Scripting |
BEGIN...END, DECLARE, IF/WHILE/FOR |
DBR 16.3+ |
references/sql-scripting.md |
| Stored Procedures |
CREATE PROCEDURE, CALL |
DBR 17.0+ |
references/sql-scripting.md |
| Recursive CTEs |
WITH RECURSIVE |
DBR 17.0+ |
references/sql-scripting.md |
| Transactions |
BEGIN ATOMIC...END |
Preview |
references/sql-scripting.md |
| Materialized Views |
CREATE MATERIALIZED VIEW |
Serverless |
references/materialized-views-pipes.md |
| Temp Tables |
CREATE TEMPORARY TABLE |
All |
references/materialized-views-pipes.md |
| Pipe Syntax |
|> operator |
DBR 16.1+ |
references/materialized-views-pipes.md |
| Geospatial (H3) |
h3_longlatash3() |
DBR 11.2+ |
references/geospatial-collations.md |
| Geospatial (ST) |
ST_Point(), ST_Contains() |
DBR 16.0+ |
references/geospatial-collations.md |
| Collations |
COLLATE, UTF8_LCASE |
DBR 16.1+ |
references/geospatial-collations.md |
| AI Functions |
ai_query(), ai_classify(), 11+ funcs |
Serverless, DBR 15.1+ |
references/ai-functions.md |
| http_request |
http_request(conn, ...) |
Serverless |
references/ai-functions.md |
| remote_query |
SELECT * FROM remote_query(...) |
Serverless |
references/ai-functions.md |
| read_files |
SELECT * FROM read_files(...) |
All |
references/ai-functions.md |
| Data Modeling |
Star schema, Liquid Clustering |
All |
references/best-practices.md |
Common Patterns
Procedural ETL with SQL Scripting
BEGIN
DECLARE v_count INT;
SET v_count = (SELECT COUNT(*) FROM catalog.schema.raw_orders WHERE status = 'new');
IF v_count > 0 THEN
INSERT INTO catalog.schema.processed_orders
SELECT *, current_timestamp() AS processed_at
FROM catalog.schema.raw_orders
WHERE status = 'new';
END IF;
SELECT v_count AS rows_processed;
END
AI-Powered Data Enrichment
SELECT
ticket_id,
ai_classify(description, ARRAY('billing', 'technical', 'account')) AS category,
ai_analyze_sentiment(description) AS sentiment
FROM catalog.schema.support_tickets
LIMIT 100;
Materialized View with Scheduled Refresh
CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.daily_revenue
CLUSTER BY (order_date)
SCHEDULE EVERY 1 HOUR
AS SELECT
order_date, region,
SUM(amount) AS total_revenue,
COUNT(DISTINCT customer_id) AS unique_customers
FROM catalog.schema.fact_orders
JOIN catalog.schema.dim_store USING (store_id)
GROUP BY order_date, region;
Pipe Syntax
FROM catalog.schema.fact_orders
|> WHERE order_date >= current_date() - INTERVAL 30 DAYS
|> AGGREGATE SUM(amount) AS total, COUNT(*) AS cnt GROUP BY region
|> WHERE total > 10000
|> ORDER BY total DESC
|> LIMIT 20;
Stopping Points
- Before Step 2: clarify user intent and target objects
- Before executing any DDL/DML in Step 3
- After Step 4 if results are unexpected (diagnose before retrying)
Troubleshooting
| Problem |
Solution |
AI function not available |
Requires Serverless SQL warehouse. Classic SQL warehouses do not support AI functions. |
MATERIALIZED VIEW requires serverless |
Create/refresh MVs only on Serverless SQL warehouses. |
SQLSTATE error in BEGIN...END |
Check variable scoping and handler declarations. See references/sql-scripting.md Exception Handling. |
H3 function not found |
Requires DBR 11.2+. Check cluster/warehouse runtime version. |
ST_ function not found |
Requires DBR 16.0+. ST functions are in Public Preview. |
Pipe syntax parse error |
Requires DBR 16.1+. Each pipe stage must start with |> on a new line. |
http_request connection error |
Verify CONNECTION object exists and has correct host/credentials. |
Collation mismatch |
Use explicit COLLATE in comparisons or align column collations. |
Output
- Working Databricks SQL for the user's use case
- Correct syntax following DBSQL-specific features and requirements
- Performance-optimized queries following Lakehouse best practices
1---2name: databricks-dbsql3description: >-4 Databricks SQL (DBSQL) advanced features and SQL warehouse capabilities.5 Use when the user mentions: DBSQL, Databricks SQL, SQL warehouse,6 SQL scripting, stored procedure, CALL procedure, materialized view,7 CREATE MATERIALIZED VIEW, pipe syntax, pipe operator, geospatial, H3,8 ST_, spatial SQL, collation, COLLATE, ai_query, ai_classify, ai_extract,9 ai_gen, ai_analyze_sentiment, ai_similarity, ai_forecast, ai_mask,10 ai_fix_grammar, ai_parse_document, vector_search, AI function,11 http_request, remote_query, read_files, Lakehouse Federation,12 recursive CTE, WITH RECURSIVE, multi-statement transaction,13 temp table, temporary view, data modeling best practices on Databricks,14 Liquid Clustering, star schema Databricks, SCD Type 2 Databricks.15metadata:16 source: https://skillmd.com/skills/s-14-h/databricks-dbsql17---1819# Databricks SQL (DBSQL) - Advanced Features2021## Prerequisites2223- Databricks CLI v0.205+ installed and authenticated (see `databricks-cli-install` skill; for CLI operations see `databricks-cli` skill)24- A Databricks SQL warehouse (Serverless recommended for AI functions, MVs, and http_request)2526## Detecting Unity Catalog vs Hive Metastore2728**Before assuming Unity Catalog is available, always check:**2930```bash31databricks metastores current --output json 2>&132```3334- **If a metastore is returned:** Unity Catalog is active. Use three-level naming (`catalog.schema.table`) throughout.35- **If it errors or returns nothing:** The workspace uses the legacy Hive Metastore. In this case:36 - Use two-level naming (`schema.table` or `database.table`) instead of three-level37 - The `default` database is always available38 - UC-only features are **unavailable**: materialized views, AI functions, grants CLI, Liquid Clustering, pipe syntax39 - SQL execution via `databricks api post /api/2.0/sql/statements` still works with two-level references40 - Skip any instructions that reference `catalog.schema.table` and adapt to `schema.table`4142## When to Use4344- User wants to write or debug Databricks SQL (procedural SQL, stored procedures, MVs, AI functions)45- User asks about DBSQL-specific features (pipe syntax, geospatial, collations, http_request)46- User needs data modeling guidance for the Databricks Lakehouse47- User wants to use AI functions (ai_query, ai_classify, ai_extract, etc.) in SQL4849## Workflow5051> **Convention:** All placeholders in `<angle-brackets>` must be replaced with actual values from the user. All SQL examples use three-level Unity Catalog naming: `catalog.schema.object`.5253### Step 1: Detect Intent5455**Goal:** Determine which DBSQL feature area the user needs.5657**Route by topic:**5859| User mentions | Load reference |60|---------------|----------------|61| SQL scripting, BEGIN...END, DECLARE, IF/WHILE/FOR, stored procedure, CREATE PROCEDURE, CALL, recursive CTE, WITH RECURSIVE, transaction | **Load** `references/sql-scripting.md` |62| ai_query, ai_classify, ai_extract, ai_gen, ai_summarize, ai_analyze_sentiment, ai_similarity, ai_mask, ai_fix_grammar, ai_forecast, ai_parse_document, vector_search, AI function, http_request, remote_query, read_files, Lakehouse Federation | **Load** `references/ai-functions.md` |63| Materialized view, CREATE MATERIALIZED VIEW, refresh, temp table, temporary view, pipe syntax, `\|>` operator | **Load** `references/materialized-views-pipes.md` |64| Geospatial, H3, h3_longlatash3, ST_Point, ST_Contains, spatial, collation, COLLATE, UTF8_LCASE, case-insensitive | **Load** `references/geospatial-collations.md` |65| Data modeling, star schema, dimension table, fact table, Liquid Clustering, partitioning, Z-ORDER, SCD, best practices, performance | **Load** `references/best-practices.md` |6667If the intent spans multiple areas, load the primary reference first and additional references as needed.6869### Step 2: Understand the User's Goal7071**⚠️ MANDATORY STOPPING POINT**: Before writing any SQL, ask the user:72731. What are you trying to accomplish?742. Which catalog/schema/tables are involved?753. What SQL warehouse type are you using? (Serverless required for AI functions, MVs, http_request)7677Do NOT proceed until the user responds.7879### Step 3: Write or Debug SQL8081**Goal:** Help the user write, optimize, or debug their SQL.8283**Actions:**84851. Use the loaded reference for correct syntax, parameters, and patterns862. Write SQL using three-level Unity Catalog naming (`catalog.schema.table`)873. Include comments explaining non-obvious logic884. For procedural SQL: use proper BEGIN...END blocks, DECLARE variables, and error handling895. For AI functions: always include `LIMIT` during development to control costs9091**⚠️ MANDATORY STOPPING POINT**: Before executing any DDL or DML (CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, MERGE), present the SQL to the user for approval.9293### Step 4: Verify Results9495**Goal:** Confirm the SQL works as expected.9697**Actions:**98991. If the user approved execution, run the SQL1002. Check for errors and suggest fixes if needed1013. For materialized views: verify refresh status1024. For stored procedures: test with sample parameters103104## Quick Reference105106| Feature | Key Syntax | Requires | Reference |107|---------|-----------|----------|-----------|108| SQL Scripting | `BEGIN...END`, `DECLARE`, `IF/WHILE/FOR` | DBR 16.3+ | `references/sql-scripting.md` |109| Stored Procedures | `CREATE PROCEDURE`, `CALL` | DBR 17.0+ | `references/sql-scripting.md` |110| Recursive CTEs | `WITH RECURSIVE` | DBR 17.0+ | `references/sql-scripting.md` |111| Transactions | `BEGIN ATOMIC...END` | Preview | `references/sql-scripting.md` |112| Materialized Views | `CREATE MATERIALIZED VIEW` | Serverless | `references/materialized-views-pipes.md` |113| Temp Tables | `CREATE TEMPORARY TABLE` | All | `references/materialized-views-pipes.md` |114| Pipe Syntax | `\|>` operator | DBR 16.1+ | `references/materialized-views-pipes.md` |115| Geospatial (H3) | `h3_longlatash3()` | DBR 11.2+ | `references/geospatial-collations.md` |116| Geospatial (ST) | `ST_Point()`, `ST_Contains()` | DBR 16.0+ | `references/geospatial-collations.md` |117| Collations | `COLLATE`, `UTF8_LCASE` | DBR 16.1+ | `references/geospatial-collations.md` |118| AI Functions | `ai_query()`, `ai_classify()`, 11+ funcs | Serverless, DBR 15.1+ | `references/ai-functions.md` |119| http_request | `http_request(conn, ...)` | Serverless | `references/ai-functions.md` |120| remote_query | `SELECT * FROM remote_query(...)` | Serverless | `references/ai-functions.md` |121| read_files | `SELECT * FROM read_files(...)` | All | `references/ai-functions.md` |122| Data Modeling | Star schema, Liquid Clustering | All | `references/best-practices.md` |123124## Common Patterns125126### Procedural ETL with SQL Scripting127128```sql129BEGIN130 DECLARE v_count INT;131 SET v_count = (SELECT COUNT(*) FROM catalog.schema.raw_orders WHERE status = 'new');132133 IF v_count > 0 THEN134 INSERT INTO catalog.schema.processed_orders135 SELECT *, current_timestamp() AS processed_at136 FROM catalog.schema.raw_orders137 WHERE status = 'new';138 END IF;139140 SELECT v_count AS rows_processed;141END142```143144### AI-Powered Data Enrichment145146```sql147SELECT148 ticket_id,149 ai_classify(description, ARRAY('billing', 'technical', 'account')) AS category,150 ai_analyze_sentiment(description) AS sentiment151FROM catalog.schema.support_tickets152LIMIT 100;153```154155### Materialized View with Scheduled Refresh156157```sql158CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.daily_revenue159 CLUSTER BY (order_date)160 SCHEDULE EVERY 1 HOUR161AS SELECT162 order_date, region,163 SUM(amount) AS total_revenue,164 COUNT(DISTINCT customer_id) AS unique_customers165FROM catalog.schema.fact_orders166JOIN catalog.schema.dim_store USING (store_id)167GROUP BY order_date, region;168```169170### Pipe Syntax171172```sql173FROM catalog.schema.fact_orders174 |> WHERE order_date >= current_date() - INTERVAL 30 DAYS175 |> AGGREGATE SUM(amount) AS total, COUNT(*) AS cnt GROUP BY region176 |> WHERE total > 10000177 |> ORDER BY total DESC178 |> LIMIT 20;179```180181## Stopping Points182183- Before Step 2: clarify user intent and target objects184- Before executing any DDL/DML in Step 3185- After Step 4 if results are unexpected (diagnose before retrying)186187## Troubleshooting188189| Problem | Solution |190|---------|----------|191| `AI function not available` | Requires Serverless SQL warehouse. Classic SQL warehouses do not support AI functions. |192| `MATERIALIZED VIEW requires serverless` | Create/refresh MVs only on Serverless SQL warehouses. |193| `SQLSTATE error in BEGIN...END` | Check variable scoping and handler declarations. See `references/sql-scripting.md` Exception Handling. |194| `H3 function not found` | Requires DBR 11.2+. Check cluster/warehouse runtime version. |195| `ST_ function not found` | Requires DBR 16.0+. ST functions are in Public Preview. |196| `Pipe syntax parse error` | Requires DBR 16.1+. Each pipe stage must start with `\|>` on a new line. |197| `http_request connection error` | Verify CONNECTION object exists and has correct host/credentials. |198| `Collation mismatch` | Use explicit `COLLATE` in comparisons or align column collations. |199200## Output201202- Working Databricks SQL for the user's use case203- Correct syntax following DBSQL-specific features and requirements204- Performance-optimized queries following Lakehouse best practices