Sub topic 8
Working in Notebooks
This chapter assumes you know basic SQL and Python, and that you have read the chapters on compute and the workspace. You should know that a notebook runs on compute that you attach to it. About 1,200 words follow, so the coverage is selective.
What a notebook is
A Databricks notebook is a document made of ordered cells. Each cell holds code or Markdown text. You run cells one at a time, in any order, and the output appears beneath each cell. The notebook itself is stored in the workspace. The code runs on compute in the compute plane.
Two facts explain most notebook behavior:
- The notebook and the compute are separate. The notebook is a file. The compute is a cluster or serverless resource that you attach it to.
- Each attached notebook gets its own execution context, called a REPL. A REPL (read-eval-print loop) holds the variables and imports for that notebook. Two notebooks on the same cluster do not share Python variables.
Attaching compute
A new notebook does nothing until you attach it. Use the compute selector at the top right of the notebook. You can pick all-purpose compute, which is a cluster shared by interactive users, or serverless compute, if your workspace offers it.
If the cluster is stopped, attaching it starts it, and startup can take several minutes. Serverless compute usually starts faster.
A common error is "cluster not running" or a cell that waits for a long time. Check the compute selector first. Then check that your account has permission to attach to that compute.
Languages and magic commands
Every notebook has a default language, such as Python or SQL. You can override it for one cell with a magic command on the first line of the cell.
| Magic command | Effect |
|---|---|
| `%python` | Run the cell as Python |
| `%sql` | Run the cell as SQL |
| `%scala` | Run the cell as Scala |
| `%r` | Run the cell as R |
| `%md` | Render the cell as Markdown |
| `%sh` | Run shell commands on the driver node only |
| `%run` | Run another notebook inline, so its definitions become available |
| `%pip` | Install Python libraries for this notebook |
Mixing languages is convenient, but variables do not cross language boundaries. A Python variable is not visible in a %sql cell. To pass data between languages, write it to a table or a temporary view.
Predefined objects
In a Python notebook, Databricks creates several objects for you:
sparkis the SparkSession, your entry point to the Spark engine.dbutilsprovides helper utilities for files, secrets, widgets, and notebook workflows.display()renders a DataFrame as an interactive table that you can sort, chart, and download.
You do not create or configure spark. Creating your own session is unnecessary and can cause confusion.
Querying a table from a notebook
The same Delta table can be read from SQL or from PySpark. Assume the main.tutorial.orders table exists, as created in the Unity Catalog chapter. The table uses the three-level name catalog.schema.table.
In a Python cell:
from pyspark.sql import functions as F
df = spark.table("main.tutorial.orders")
totals = (
df.groupBy("customer_id")
.agg(F.sum("amount").alias("total_amount"))
)
display(totals)spark.table returns a DataFrame. A DataFrame is a distributed table that Spark evaluates lazily. The groupBy and agg calls only build a plan. Spark runs the work when an action such as display needs the result.
The equivalent query in a SQL cell:
SELECT customer_id, SUM(amount) AS total_amount
FROM main.tutorial.orders
GROUP BY customer_id;Both versions produce the same result. Choose SQL for set-based queries and Python when you need loops, functions, or libraries.
Widgets: parameterizing a notebook
Widgets add input controls at the top of a notebook. They make a notebook reusable, and they are also how a scheduled job passes parameters into it.
dbutils.widgets.text("min_amount", "20")
min_amount = float(dbutils.widgets.get("min_amount"))
big_orders = (
spark.table("main.tutorial.orders")
.filter(f"amount >= {min_amount}")
)
display(big_orders)Widget values are always strings. Convert them yourself, as the code does with float. Be careful when you place widget values into SQL text, because the value is user input. Convert it to a number first, as shown, or use parameter markers in SQL.
Cell execution and state
Cells share state in order of execution, not in order of position. If you run cell 5, then cell 2, then cell 5 again, the state reflects that sequence. This is the most common source of "works on my screen, fails in the job" bugs.
The state problems you will meet most often:
- Stale variables. You deleted a cell that defined a variable, but the variable is still in memory. The notebook works until you detach and rerun it from the top.
- Out-of-order runs. A later cell depends on a value set by an earlier cell that you skipped.
- State lost after detaching. Detaching or restarting the compute clears the REPL. You must rerun the setup cells.
- Library changes. After
%pip install, Python may restart, and earlier variables are lost. Put%pipcommands in the first cells.
Before you schedule a notebook, run Run all on freshly attached compute. If it succeeds from top to bottom, it has no hidden dependency on state.
Output, versions, and sharing
Databricks saves a notebook's revision history automatically, and you can restore an earlier version from the history panel. Cell outputs are saved with the notebook, so anyone who opens it sees the last results without rerunning. Large outputs are truncated, and display shows a limited number of rows. Do not rely on the on-screen output as your record of full results. Write results to a table instead.
Notebook permissions are separate from data permissions. Being able to open a notebook does not let you read the tables it queries. Unity Catalog checks the running user's privileges on each table when the cell runs. If you see a "permission denied" error on a table, request USE CATALOG, USE SCHEMA, and SELECT on the right objects, not access to the notebook.
From notebook to job
A notebook is also a unit of scheduled work. A job can run a notebook on job compute, which exists only for the run and is cheaper than all-purpose compute. To prepare a notebook for that:
- Run it top to bottom on fresh compute.
- Replace hard-coded values with widgets.
- Remove exploratory cells that call
displayon large data orcollect(). - Write results to a table.
The later chapter on jobs covers scheduling in detail.
Exercise
You run cell 4 of a notebook, then cell 2, and the result looks right. A colleague runs the notebook top to bottom and gets an error in cell 4. What is the likely cause, and how do you check for it before scheduling the notebook?
Show answer
Cell 4 depends on a variable or import defined in a cell that ran later or was skipped in the colleague's order, so the state depended on execution order. Before scheduling, attach the notebook to fresh compute (or detach and reattach it) and use Run all. If it passes from top to bottom, it has no hidden state dependency.
Exercise
A Python cell sets region = "EU". The next cell starts with %sql and uses region in a query. It fails. Why, and what are two ways to fix it?
Show answer
Variables do not cross language boundaries, so the SQL cell cannot see the Python variable. One fix is to put the value in a widget and read it in both languages. Another is to write the data to a table or temporary view that both languages can query. Using spark.sql inside a Python cell, with the value formatted into the query, also works.