Sub topic 8
Running queries and reading results
This chapter assumes you know basic SQL (SELECT, WHERE, JOIN, GROUP BY), can open the Databricks SQL editor, and have a SQL warehouse you can use. It also assumes you know the catalog.schema.table naming from the previous chapter. Here you run queries, read what comes back, and handle the errors you are most likely to hit.
What happens when you click Run
When you run a query, the editor sends the text to the SQL warehouse attached to that editor tab. The warehouse plans the query, runs it on its cluster, and returns the rows to the editor. If the warehouse is stopped, it starts first, and the query waits.
Two things follow from this path:
- The first query after a stop is slower, because it includes startup time. Serverless warehouses start in seconds. Pro and classic warehouses can take several minutes.
- Every run is recorded in query history, whether it succeeds or fails. The later chapter on query history covers how to use that record.
Running the first queries
Start by checking what you can see, then read a sample table with its full three-level name.
SHOW CATALOGS;
SELECT * FROM samples.nyctaxi.trips LIMIT 10;Select the warehouse in the drop-down at the top right of the editor before you run anything. Then press the Run button, or use Ctrl+Enter (Cmd+Enter on macOS).
Running one statement or many
The editor treats the text in the tab as a script of statements separated by semicolons. The two behaviors you need to know are:
- With no text selected, Run executes the statement where the cursor sits. If your tab holds several statements, only that one runs.
- With text selected, Run (selected) executes only the selection. Use this to run a single statement from the middle of a script or to test one subquery.
Some versions of the editor also let you run all statements in the tab. If you are unsure what will run, select the text yourself first. This avoids accidentally running a destructive statement that sits further down the tab.
Reading results
Results appear in a grid below the editor. Each tab can show several result sets, one per statement that returns rows.
Check these things every time:
- Row count and truncation. The editor shows only a limited number of rows in the grid. If the result is larger, a message says the result was truncated. The full result is not lost, since you can download it, but what you see is a slice.
- Column types. Types such as
DECIMAL,TIMESTAMP, andBIGINTdisplay differently. A timestamp is shown in a time zone that depends on your session settings, so two people can see different values for the same row. - Execution time. The elapsed time includes queue and startup time as well as execution time. For an accurate view of where time went, use the query profile, which a later chapter covers.
- NULL values. These show as
null, which is different from an empty string. Filter withIS NULL, never= NULL.
Why LIMIT matters
LIMIT keeps the amount of data returned small. The grid already truncates, but a limit also lets the engine stop early for simple scans. It does not always make a query cheaper. With ORDER BY or GROUP BY, the warehouse still has to process all the matching data before it can apply the limit.
A query worth reading closely
This aggregation over the sample taxi data gives a result worth charting and a plan worth inspecting.
SELECT
pickup_zip,
COUNT(*) AS trips,
ROUND(AVG(fare_amount), 2) AS avg_fare
FROM samples.nyctaxi.trips
GROUP BY pickup_zip
ORDER BY trips DESC
LIMIT 20;Read it from the result back to the data:
GROUP BY pickup_zipproduces one row per zip code. The warehouse must see every row of the table to count them, so the limit does not shorten the scan.ORDER BY trips DESCsorts the grouped rows, not the original ones. You can sort by an alias liketripsbecauseORDER BYruns afterSELECTin logical order.LIMIT 20keeps the top twenty groups.
The result has three columns: a zip code, a count, and an average fare. Counting with COUNT(*) includes all rows. COUNT(fare_amount) would skip rows where the fare is NULL, so the two can differ.
Looking at the plan before running
Sometimes you want to see how the warehouse would run a query without paying for the run. EXPLAIN prints the plan and does not execute the statement.
EXPLAIN
SELECT pickup_zip, COUNT(*) AS trips
FROM samples.nyctaxi.trips
GROUP BY pickup_zip;The output is text. Read it from the bottom up, since the scan is at the bottom and the final aggregation is at the top. Look for the table scan, any filters pushed down to it, and the shuffle (an exchange step) that moves rows between nodes for the grouping.
EXPLAIN and the query profile answer different questions:
| Tool | When you use it | What it shows |
|---|---|---|
| `EXPLAIN` | Before running | The planned steps, with no timings |
| Query profile | After running | Actual time, rows, and data read for each step |
Use EXPLAIN to check the shape of a plan cheaply. Use the profile to find which step was slow.
Common errors
Most failures in the first weeks fall into a few groups.
| Symptom | Likely cause | Fix |
|---|---|---|
| `TABLE_OR_VIEW_NOT_FOUND` | Wrong name, or no access to the catalog or schema | Use the full `catalog.schema.table` name. Check the name in the catalog browser. |
| `PERMISSION_DENIED` or "does not have USE CATALOG" | You lack Unity Catalog privileges | Ask the data owner for `USE CATALOG`, `USE SCHEMA`, and `SELECT`. |
| `UNRESOLVED_COLUMN` | Misspelled column, or an alias used where it is not allowed | Check the column list. Aliases can't be used in `WHERE`. |
| Query waits a long time before starting | Warehouse is starting, or the queue is full | Wait for startup, or use a serverless warehouse. See the chapters on scaling. |
| Query is canceled after a long run | A statement timeout or a manual cancel | Narrow the data with filters, or ask an admin about the timeout setting. |
Canceling a query
Click Cancel while a query runs to stop it. The warehouse stops work for that statement and frees the capacity. Canceling is safe for SELECT. For statements that write data, check the table afterward, because a write may have partly finished depending on the operation.
Where to look when a result looks wrong
When numbers surprise you, work through these checks in order:
- Confirm the warehouse and the catalog. A default catalog or schema in the session can make an unqualified name point somewhere unexpected. Using the full three-level name avoids this.
- Run a plain
SELECT COUNT(*)on the source table to see the scale of the data. - Remove
LIMITandORDER BYfrom a suspicious query and check the grouped counts against the source count. - Check joins for duplicate keys. A join on a non-unique column multiplies rows, which inflates counts and sums.
For example, if you join trips to a zone table that has two rows per zip code, every trip appears twice, and COUNT(*) doubles.
Exercises
Exercise
You select the whole tab, which holds a SELECT followed by a DROP TABLE statement, and click Run. Then you realize you only wanted the SELECT. What should you do next time before running?
Show answer
Select only the SELECT statement's text, or place the cursor in it with nothing selected, and then run. With no selection the editor runs the statement at the cursor, and with a selection it runs only the selected text. Selecting the exact text removes any doubt about what will execute.
Exercise
A query with GROUP BY and ORDER BY ends with LIMIT 20 and still takes a long time. Why does the limit not make it fast, and which tool shows you which step is slow?
Show answer
The warehouse has to read and group all matching rows before it can sort and keep twenty, so the limit does not shorten the scan. The query profile, which you read after the run, shows actual time, rows, and data read for each step. EXPLAIN shows the plan only, without timings.