Databricks Dbsql

作者 databrickse77e37e8a4da無授權條款345 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

Databricks SQL (DBSQL) advanced features and SQL warehouse capabilities. This skill MUST be invoked when the user mentions: "DBSQL", "Databricks SQL", "SQL warehouse", "SQL scripting", "stored procedure", "CALL procedure", "materialized view", "CREATE MATERIALIZED VIEW", "pipe syntax", "|>", "geospatial", "H3", "ST_", "spatial SQL", "collation", "COLLATE", "ai_query", "ai_classify", "ai_extract", "ai_gen", "AI function", "http_request", "remote_query", "read_files", "Lakehouse Federation", "recursive CTE", "WITH RECURSIVE", "multi-statement transaction", "temp table", "temporary view", "pipe operator". SHOULD also invoke when the user asks about SQL best practices, data modeling patterns, or advanced SQL features on Databricks.

AI 產生的概覽

針對 Databricks SQL 進階功能的參考指南,涵蓋 SQL 指令碼、具體化檢視、地理空間函式與 AI 函式。

功能
此技能提供在 SQL 倉儲上撰寫進階 Databricks SQL(DBSQL)的說明與參考資料。內容涵蓋 SQL 指令碼、預存程序、遞迴 CTE、交易、具體化檢視、暫存物件、管道語法、地理空間與定序函式、AI 函式、http_request、remote_query、read_files,以及資料建模指引。它產出 SQL 模式與語法指引,本身不執行查詢。
適用情境
當使用者詢問 DBSQL、SQL 倉儲、SQL 指令碼、預存程序、具體化檢視、管道語法、地理空間或定序 SQL、AI 函式或相關 Databricks SQL 功能時使用。它也適用於關於 SQL 最佳實務、資料建模模式與 Databricks 上進階 SQL 的問題。
執行需求
根據技能的相容性說明,需要 Databricks CLI(>= v1.0.0)。它不隨附指令碼,僅包含說明、參考 Markdown 檔案與影像資源。文中提到的部分功能需要 Serverless 或 Pro SQL 倉儲,以及對應版本的 Databricks Runtime。

Databricks SQL (DBSQL) - Advanced Features

Quick Reference

FeatureKey SyntaxSinceReference
SQL ScriptingBEGIN...END, DECLARE, IF/WHILE/FORDBR 16.3+references/sql-scripting.md [blocked]
Stored ProceduresCREATE PROCEDURE, CALLDBR 17.0+references/sql-scripting.md [blocked]
Recursive CTEsWITH RECURSIVEDBR 17.0+references/sql-scripting.md [blocked]
TransactionsBEGIN ATOMIC...ENDPreviewreferences/sql-scripting.md [blocked]
Materialized ViewsCREATE MATERIALIZED VIEWPro/Serverlessreferences/materialized-views-pipes.md [blocked]
Temp TablesCREATE TEMPORARY TABLEAllreferences/materialized-views-pipes.md [blocked]
Pipe Syntax|> operatorDBR 16.1+references/materialized-views-pipes.md [blocked]
Geospatial (H3)h3_longlatash3(), h3_polyfillash3()DBR 11.2+references/geospatial-collations.md [blocked]
Geospatial (ST)ST_Point(), ST_Contains(), 80+ funcsDBR 16.0+references/geospatial-collations.md [blocked]
CollationsCOLLATE, UTF8_LCASE, locale-awareDBR 16.1+references/geospatial-collations.md [blocked]
AI Functionsai_query(), ai_classify(), 11+ funcsDBR 15.1+references/ai-functions.md [blocked]
http_requesthttp_request(conn, ...)Pro/Serverlessreferences/ai-functions.md [blocked]
remote_querySELECT * FROM remote_query(...)Pro/Serverlessreferences/ai-functions.md [blocked]
read_filesSELECT * FROM read_files(...)Allreferences/ai-functions.md [blocked]
Data ModelingStar schema, Liquid ClusteringAllreferences/best-practices.md [blocked]

Common Patterns

SQL Scripting - Procedural ETL

sql
BEGIN  DECLARE v_count INT;  DECLARE v_status STRING DEFAULT 'pending';
  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';
    SET v_status = 'completed';  ELSE    SET v_status = 'skipped';  END IF;
  SELECT v_status AS result, v_count AS rows_processed;END

Stored Procedure with Error Handling

sql
CREATE OR REPLACE PROCEDURE catalog.schema.upsert_customers(  IN p_source STRING,  OUT p_rows_affected INT)LANGUAGE SQLSQL SECURITY INVOKERBEGIN  DECLARE EXIT HANDLER FOR SQLEXCEPTION  BEGIN    SET p_rows_affected = -1;    SIGNAL SQLSTATE '45000'      SET MESSAGE_TEXT = concat('Upsert failed for source: ', p_source);  END;
  MERGE INTO catalog.schema.dim_customer AS t  USING (SELECT * FROM identifier(p_source)) AS s  ON t.customer_id = s.customer_id  WHEN MATCHED THEN UPDATE SET *  WHEN NOT MATCHED THEN INSERT *;
  SET p_rows_affected = (SELECT COUNT(*) FROM identifier(p_source));END;
-- Invoke:CALL catalog.schema.upsert_customers('catalog.schema.staging_customers', ?);

Materialized View with Scheduled Refresh

sql
CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.daily_revenue  CLUSTER BY (order_date)  SCHEDULE EVERY 1 HOUR  COMMENT 'Hourly-refreshed daily revenue by region'AS SELECT    order_date,    region,    SUM(amount) AS total_revenue,    COUNT(DISTINCT customer_id) AS unique_customersFROM catalog.schema.fact_ordersJOIN catalog.schema.dim_store USING (store_id)GROUP BY order_date, region;

Pipe Syntax - Readable Transformations

sql
-- Traditional SQL rewritten with pipe syntaxFROM catalog.schema.fact_orders  |> WHERE order_date >= current_date() - INTERVAL 30 DAYS  |> AGGREGATE SUM(amount) AS total, COUNT(*) AS cnt GROUP BY region, product_category  |> WHERE total > 10000  |> ORDER BY total DESC  |> LIMIT 20;

AI Functions - Enrich Data with LLMs

sql
-- Classify support ticketsSELECT  ticket_id,  description,  ai_classify(description, ARRAY('billing', 'technical', 'account', 'feature_request')) AS category,  ai_analyze_sentiment(description) AS sentimentFROM catalog.schema.support_ticketsLIMIT 100;
-- Extract entities from textSELECT  doc_id,  ai_extract(content, ARRAY('person_name', 'company', 'dollar_amount')) AS entitiesFROM catalog.schema.contracts;
-- General-purpose AI query with structured outputSELECT ai_query(  'databricks-meta-llama-3-3-70b-instruct',  concat('Summarize this customer feedback in JSON with keys: topic, sentiment, action_items. Feedback: ', feedback),  returnType => 'STRUCT<topic STRING, sentiment STRING, action_items ARRAY<STRING>>') AS analysisFROM catalog.schema.customer_feedbackLIMIT 50;

Geospatial - Proximity Search with H3

sql
-- Find stores within 5km of each customer using H3 indexingWITH customer_h3 AS (  SELECT *, h3_longlatash3(longitude, latitude, 7) AS h3_cell  FROM catalog.schema.customers),store_h3 AS (  SELECT *, h3_longlatash3(longitude, latitude, 7) AS h3_cell  FROM catalog.schema.stores)SELECT  c.customer_id,  s.store_id,  ST_Distance(    ST_Point(c.longitude, c.latitude),    ST_Point(s.longitude, s.latitude)  ) AS distance_mFROM customer_h3 cJOIN store_h3 s ON h3_ischildof(c.h3_cell, h3_toparent(s.h3_cell, 5))WHERE ST_Distance(  ST_Point(c.longitude, c.latitude),  ST_Point(s.longitude, s.latitude)) < 5000;

Collation - Case-Insensitive Search

sql
-- Create table with case-insensitive collationCREATE TABLE catalog.schema.products (  product_id BIGINT GENERATED ALWAYS AS IDENTITY,  name STRING COLLATE UTF8_LCASE,  category STRING COLLATE UTF8_LCASE,  price DECIMAL(10, 2));
-- Queries automatically case-insensitive (no LOWER() needed)SELECT * FROM catalog.schema.productsWHERE name = 'MacBook Pro';  -- matches 'macbook pro', 'MACBOOK PRO', etc.

http_request - Call External APIs

sql
-- Set up connection first (one-time)CREATE CONNECTION my_api_conn  TYPE HTTP  OPTIONS (host 'https://api.example.com', bearer_token secret('scope', 'token'));
-- Call API from SQLSELECT  order_id,  http_request(    conn => 'my_api_conn',    method => 'POST',    path => '/v1/validate',    json => to_json(named_struct('order_id', order_id, 'amount', amount))  ).text AS api_responseFROM catalog.schema.ordersWHERE needs_validation = true;

read_files - Ingest Raw Files

sql
-- Read JSON files from a Volume with schema hintsSELECT *FROM read_files(  '/Volumes/catalog/schema/raw/events/',  format => 'json',  schemaHints => 'event_id STRING, timestamp TIMESTAMP, payload MAP<STRING, STRING>',  pathGlobFilter => '*.json',  recursiveFileLookup => true);
-- Read CSV with optionsSELECT *FROM read_files(  '/Volumes/catalog/schema/raw/sales/',  format => 'csv',  header => true,  delimiter => '|',  dateFormat => 'yyyy-MM-dd',  schema => 'sale_id INT, sale_date DATE, amount DECIMAL(10,2), store STRING');

Recursive CTE - Hierarchy Traversal

sql
WITH RECURSIVE org_chart AS (  -- Anchor: top-level managers  SELECT employee_id, name, manager_id, 0 AS depth, ARRAY(name) AS path  FROM catalog.schema.employees  WHERE manager_id IS NULL
  UNION ALL
  -- Recursive: direct reports  SELECT e.employee_id, e.name, e.manager_id, o.depth + 1, array_append(o.path, e.name)  FROM catalog.schema.employees e  JOIN org_chart o ON e.manager_id = o.employee_id  WHERE o.depth < 10  -- safety limit)SELECT * FROM org_chart ORDER BY depth, name;

remote_query - Federated Queries

sql
-- Query PostgreSQL via Lakehouse FederationSELECT *FROM remote_query(  'my_postgres_connection',  database => 'my_database',  query    => 'SELECT customer_id, email, created_at FROM customers WHERE active = true');

Reference Files

Load these for detailed syntax, full parameter lists, and advanced patterns:

FileContentsWhen to Read
references/sql-scripting.md [blocked]SQL Scripting, Stored Procedures, Recursive CTEs, TransactionsUser needs procedural SQL, error handling, loops, dynamic SQL
references/materialized-views-pipes.md [blocked]Materialized Views, Temp Tables/Views, Pipe SyntaxUser needs MVs, refresh scheduling, temp objects, pipe operator
references/geospatial-collations.md [blocked]39 H3 functions, 80+ ST functions, Collation types and hierarchyUser needs spatial analysis, H3 indexing, case/accent handling
references/ai-functions.md [blocked]13 AI functions, http_request, remote_query, read_files (all options)User needs AI enrichment, API calls, federation, file ingestion
references/best-practices.md [blocked]Data modeling, performance, Liquid Clustering, anti-patternsUser needs architecture guidance, optimization, or modeling advice

Key Guidelines

  • Always use Serverless SQL warehouses for AI functions, MVs, and http_request
  • Use LIMIT during development with AI functions to control costs
  • Prefer Liquid Clustering over partitioning for new tables (1-4 keys max)
  • Use CLUSTER BY AUTO when unsure about clustering keys
  • Star schema in Gold layer for BI; OBT acceptable in Silver
  • Define PK/FK constraints on dimensional models for query optimization
  • Use COLLATE UTF8_LCASE for user-facing string columns that need case-insensitive search
  • Test SQL via CLI (databricks experimental aitools tools query) or notebooks before deploying. If --warehouse is rejected on your CLI version, set DATABRICKS_WAREHOUSE_ID in the environment instead.

來源與署名

來源:databricks/databricks-agent-skills位於plugins/databricks/claude/skills/databricks-dbsql提交e77e37e

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架