Sub topic 1
Working in a Databricks notebook
A Databricks notebook is where you will write and run every example in this tutorial. This chapter covers how the notebook is built, how it connects to compute, how cells run, and which habits prevent common problems. It does not cover DataFrames themselves. Those start in later chapters.
Prerequisites
This chapter assumes you have:
- Basic Python or SQL. You can read a short function and a
SELECTstatement. - Familiarity with tabular data: rows, columns, and column types.
- Access to a Databricks workspace, and permission to create a notebook and attach it to compute.
You do not need to know Spark yet.
What a notebook is
A notebook is a document made of cells. Each cell holds code or text. You run a code cell, and its output appears directly beneath it. The notebook is saved in your workspace, so you can come back to it, share it, and run it again.
Three parts work together:
- The notebook holds your code, text, and saved output.
- The compute is the cluster or serverless resource that actually runs the code. Your notebook does not run anything by itself.
- The REPL is the Python process on the compute that holds your variables. It exists only while the notebook is attached and active.
Spark does the heavy work on the compute. Your Python code in the notebook only describes what Spark should do.
Attaching to compute
A new notebook has no compute until you attach it. Use the compute selector at the top of the notebook. Typical choices are:
- Serverless compute. Starts quickly and needs no cluster setup. It may be the only option in some workspaces.
- An all-purpose cluster. A cluster that you or your team created and can reuse across notebooks.
When you run a cell on a stopped cluster, you wait while it starts. This can take several minutes. Once attached, the first cell also takes a moment to start the Python process.
If you detach the notebook, or the compute restarts, you lose all variables. The code stays, but the state does not. Re-run the cells from the top to rebuild it.
Running cells
You can run a cell with the run button, or with Shift+Enter, which runs the cell and moves to the next one. The menu also offers "Run all" and "Run all above" or "Run all below" the current cell.
Cells share state. A variable you define in one cell is available in every cell you run afterwards. This is useful, and it is also the main source of confusion.
Consider this sequence:
total = 10total = total + 5
print(total)If you run the second cell twice, the output is 15 and then 20. The result depends on how many times you ran the cell, not on the order the cells appear on the page. This is called hidden state.
Languages and magic commands
A notebook has a default language, usually Python. You can override it for a single cell by starting the cell with a magic command, a line that begins with %.
| Command | Effect |
|---|---|
| `%python` | Run the cell as Python. |
| `%sql` | Run the cell as SQL. |
| `%scala` | Run the cell as Scala. |
| `%md` | Render the cell as Markdown text. |
| `%sh` | Run shell commands on the driver node. |
| `%pip` | Install Python libraries for this notebook. |
A % command must be the first line of its cell. This tutorial uses Python as the default and shows SQL only where the text says so.
Two details are easy to miss:
- Variables from a Python cell are not automatically visible in a
%sqlcell. Chapter "Mixing SQL and DataFrames" shows how to share data between them with temporary views. %pip installrestarts the Python process for the notebook in some environments, which clears your variables. Put it in the first cell of the notebook and run it before anything else.
Output, display and printing
A cell shows the value of its last expression and anything you print. Databricks also provides display(), which renders a DataFrame as an interactive table. You can sort it, scroll it, and switch it to a chart. You will use display() and show() in the chapter on inspecting data.
Output is limited. Databricks truncates very large results, so a notebook is a place to look at samples and summaries, not to read millions of rows.
Files, folders and paths
Notebooks live in the workspace file tree, usually under your user folder. Data does not. Data lives in tables and in storage locations.
In current Databricks workspaces with Unity Catalog, you will see two kinds of names:
- Table names with three levels:
catalog.schema.table, for examplemain.default.orders. - Volume paths for files, such as
/Volumes/main/default/raw/orders.csv.
The paths and names in this tutorial are placeholders. Replace them with a catalog, schema, and volume that you can read and write. If a cell fails with a permissions error, the cause is usually the name or your access, not the code.
Useful habits
- Keep cells small. One idea per cell makes errors easier to find, and you can re-run a single step without repeating the whole notebook.
- Put imports and setup at the top. For this tutorial, that means
from pyspark.sql import functions as F. - Add
%mdcells. A sentence explaining why a step exists helps the next reader, who may be you in a month. - Restart cleanly when confused. Detach and reattach, or restart the Python process, then use "Run all". If the result changes, you had hidden state.
- Do not leave expensive cells in "Run all". A cell that scans a very large table will run every time. Comment it out or move it to a separate notebook.
- Never type secrets into a cell. Passwords and tokens end up in the notebook history. Use the workspace's secret management instead.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NameError: name 'x' is not defined` | The cell defining `x` has not run since the last restart. | Re-run the defining cell, or use "Run all above". |
| A cell hangs on "Waiting" or "Pending" | Compute is starting, or another command is running. | Wait for the compute to start, or cancel the earlier command. |
| Results differ from yesterday | Hidden state, or the underlying data changed. | Restart and run all cells in order. |
| `Table or view not found` | Wrong catalog or schema, or no access. | Check the full three-level name and your permissions. |
| A `%sql` cell cannot see a Python variable | Python and SQL do not share variables. | Register a temporary view. |
Exercise
You define rate = 0.2 in cell 1, then change the value to 0.5 in cell 1 but forget to run it again. Cell 2 uses rate and still produces results based on 0.2. Why, and what is the safest way to confirm the notebook is correct?
Show answer
The notebook keeps the value from the last time cell 1 ran. Editing the text of a cell does not change the variable until you run the cell. To confirm the notebook is correct, restart the Python process (or detach and reattach the compute) and use "Run all" from the top, so every result comes from the code as written.
Exercise
A teammate says your notebook fails with NameError on cell 5, but it works for you. Name two possible causes related to how notebooks run.
Show answer
First, you may have run cells out of order, or defined the variable in a cell that you later deleted or edited, so the variable exists only in your session. Second, your session may hold state from earlier runs that a fresh session does not. Run all cells from the top on freshly attached compute to reproduce the error.