Sub topic 11
Querying with Databricks SQL
This chapter assumes you know basic SQL (SELECT, JOIN, GROUP BY), and that you have met Delta tables and the Unity Catalog three-level name catalog.schema.table in earlier chapters. It also assumes you know that compute runs in the compute plane, and that clusters and SQL warehouses are two kinds of compute.
What Databricks SQL is
Databricks SQL is the part of the platform built for SQL analytics. It gives analysts a SQL editor, saved queries, dashboards, alerts, and a connection point for BI tools. Queries run on a SQL warehouse, which is compute built for SQL. You do not need to write notebooks or manage Spark settings.
The same tables are available from notebooks and from Databricks SQL. A table in Unity Catalog is stored once. A notebook on a cluster and a query on a warehouse both read it through its three-level name, and Unity Catalog checks permissions in both cases.
SQL warehouses
A SQL warehouse is a compute resource that accepts only SQL. It is not a data warehouse in the storage sense. Your data stays in Delta tables on cloud storage. The warehouse only supplies processing power.
Warehouses come in three types:
| Type | Where it runs | Startup | Typical use |
|---|---|---|---|
| Serverless | Databricks-managed compute | Seconds | Interactive queries, dashboards, and bursty workloads |
| Pro | Your cloud account (classic compute plane) | A few minutes | Workloads that need Pro features but not serverless |
| Classic | Your cloud account (classic compute plane) | A few minutes | Basic SQL exploration |
Availability of types and features varies by cloud and region, so check your workspace's warehouse creation page.
Key settings when you create a warehouse:
- Cluster size. Sizes use T-shirt names such as 2X-Small, Small, and Large. A larger size gives each query more processing power. It helps a single heavy query finish sooner.
- Scaling. You set a minimum and maximum number of clusters. More clusters help when many users run queries at the same time. They do not speed up one query.
- Auto stop. The warehouse stops after a set number of idle minutes. This limits cost.
The distinction between size and scaling is a common source of confusion. Slow single query: increase size. Queries queuing because many people use the warehouse: increase the maximum cluster count.
Writing queries in the SQL editor
Open SQL Editor in the sidebar and pick a warehouse from the compute selector at the top. If the warehouse is stopped, running a query starts it. The first query then waits for startup.
You can name tables fully, or set a default catalog and schema so you can use short names:
USE CATALOG main;
USE SCHEMA tutorial;
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY total_amount DESC;This query uses the main.tutorial.orders table from the earlier examples. The short name orders resolves against the current catalog and schema. If you forget the USE statements, the name fails to resolve. Fully qualified names are safer in saved queries and dashboards, because they do not depend on session state.
The editor lets you save queries, share them with other users, and run only the selected text. Results appear in a grid below the editor, and you can add a visualization to a result.
Parameters
You can put parameters in a query so that users can change a value without editing the SQL. In the editor, a named marker with a leading colon creates an input widget:
SELECT order_id, customer_id, amount
FROM main.tutorial.orders
WHERE customer_id = :customer
AND amount >= :min_amount;The editor shows a field for customer and one for min_amount. Parameter markers are bound as values, not pasted in as text. Use them for values. They cannot stand in for table or column names.
Dashboards and alerts
A dashboard collects visualizations built from queries. Each visualization reads from a dataset, which is a query. Filters and parameters on the dashboard can change what the datasets return. You can schedule a dashboard to refresh and share it with people who do not have SQL experience.
An alert runs a query on a schedule and compares a value to a threshold. For example, an alert might run a query that counts failed orders in the last hour and notify a group when the count exceeds zero.
Scheduled refreshes and alerts start the warehouse. If a warehouse has a short auto stop time and a schedule runs every few minutes, it will rarely stop. Plan schedules and auto stop together.
Connecting other tools
Warehouses expose standard connection endpoints. Drivers for JDBC, ODBC, Python, Go, Node.js, and others let external tools and applications send SQL. BI tools such as Tableau and Power BI use these endpoints. Each warehouse shows its server hostname and HTTP path in the connection details tab. Authentication uses a personal access token or OAuth, and the user's Unity Catalog permissions still apply.
A short Python example using the Databricks SQL connector:
import os
from databricks import sql
with sql.connect(
server_hostname=os.environ["DATABRICKS_SERVER_HOSTNAME"],
http_path=os.environ["DATABRICKS_HTTP_PATH"],
access_token=os.environ["DATABRICKS_TOKEN"],
) as connection:
with connection.cursor() as cursor:
cursor.execute(
"SELECT customer_id, SUM(amount) AS total_amount "
"FROM main.tutorial.orders GROUP BY customer_id"
)
for row in cursor.fetchall():
print(row)Install the connector with pip install databricks-sql-connector. Keep the token in an environment variable or secret store, not in source code.
Permissions needed to run a query
To query a table, a user needs three things:
CAN USEon the SQL warehouse, so they may run queries on it.USE CATALOGandUSE SCHEMAon the parent catalog and schema.SELECTon the table.
Missing any one of these produces an error. The grants below give a group access to the data. Warehouse access is set separately, in the warehouse's permissions dialog.
GRANT USE CATALOG ON CATALOG main TO `data-analysts`;
GRANT USE SCHEMA, SELECT ON SCHEMA main.tutorial TO `data-analysts`;Understanding performance
Several habits keep SQL warehouse queries fast and cheap:
- Select only the columns you need. Delta tables store data in columnar Parquet files, so unused columns are not read.
- Filter early. Filters on columns that data is organized by let the engine skip files.
- Avoid
SELECT *on wide tables in dashboards. - Use the query history to find slow queries. It shows duration and bytes read for each run, and the query profile shows where time went.
- Reuse results. Warehouses cache query results, so repeating the same query on unchanged data can return faster.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TABLE_OR_VIEW_NOT_FOUND` | Short name used without `USE CATALOG` and `USE SCHEMA`, or a typo | Use the full three-level name |
| Permission denied on a table you can see | Missing `USE SCHEMA` or `USE CATALOG` | Grant the parent privileges |
| First query is slow | Warehouse was stopped and had to start | Use serverless, or accept the startup time |
| Many users see queued queries | Maximum cluster count too low | Raise the maximum scaling value |
| One query is slow even with few users | Warehouse too small for the data volume | Increase cluster size |
| Cost higher than expected | Short auto stop with frequent schedules, or oversized warehouse | Review schedules and size |
Warehouse or cluster?
Use a SQL warehouse for SQL queries, dashboards, alerts, and BI connections. Use all-purpose compute for notebooks that need Python, Scala, or R, and for machine learning libraries. A warehouse cannot run arbitrary Python code. A notebook on a cluster can run SQL, and it is a reasonable choice when you mix SQL with other steps in one workflow.
Exercise
An analyst has SELECT on main.tutorial.orders and CAN USE on a warehouse, but a query on the table fails with a permission error. Name the likely missing privileges, and say what you would change on the warehouse if one heavy query is slow while only two people use it.
Show answer
The analyst is probably missing USE CATALOG on main and USE SCHEMA on main.tutorial, since SELECT alone is not enough. For a single slow query with few users, increase the warehouse cluster size. Raising the maximum cluster count would not help because it only adds capacity for concurrent queries.
Exercise
A dashboard refreshes every 5 minutes on a warehouse with an auto stop of 10 minutes. Why is this setup costly, and what could you change?
Show answer
Each refresh starts or keeps the warehouse running, and the 10-minute idle timeout means it never stops. You are billed for continuous uptime. You could refresh less often, or use a serverless warehouse with a short auto stop, so it stops quickly between refreshes and starts in seconds.