Sub topic 3
Cells, languages, and magic commands
This chapter assumes you can read basic Python or SQL, know how to open a notebook in the Databricks workspace, and have already attached a notebook to compute. It covers how a notebook is divided into cells, how each cell picks its language, and what the magic commands do.
Cells are the unit of execution
A notebook is an ordered list of cells. Each cell holds either code or Markdown text. When you run a cell, Databricks sends its contents to the attached compute and shows the output below the cell. The compute keeps one session per notebook, so state from earlier cells stays available to later ones until you detach or restart.
Two consequences matter in practice:
- Order of execution is what counts, not order on the page. If you run cell 5 before cell 3, the session reflects that order. "Run all" from the top is the only way to be sure the notebook works as written.
- Re-running a cell does not undo its earlier effects. A variable you deleted from the code still exists in the session until the session is cleared.
The default language and per-cell overrides
Every notebook has a default language: Python, SQL, Scala, or R. It is set when you create the notebook and can be changed in the notebook header. Cells run in that language unless the first line of the cell is a language magic command.
| Magic | What the cell runs |
|---|---|
| `%python` | Python |
| `%sql` | SQL |
| `%scala` | Scala |
| `%r` | R |
| `%md` | Markdown, rendered as text |
The magic must be the first line of the cell. Putting a comment above it turns the whole cell back into the default language, and the %sql line then causes a syntax error.
%sql
SELECT current_date() AS today, 1 + 1 AS twoIn a Python notebook, this cell runs as SQL. In a SQL notebook, the %sql line is optional.
Languages share the Spark session, not variables
A Python variable is not visible in a SQL or Scala cell, and the reverse is also true. Each language has its own interpreter state. What they all share is the Spark session. Anything registered in that session, such as a temporary view, can be read from any language in the same notebook.
df = spark.range(5).withColumnRenamed("id", "n")
df.createOrReplaceTempView("numbers")%sql
SELECT n, n * n AS square FROM numbersThe Python cell creates the view. The SQL cell reads it by name. To go the other way, call spark.sql from Python:
squares = spark.sql("SELECT n, n * n AS square FROM numbers")
display(squares)Recent Databricks Runtime versions also expose the result of the last %sql cell to Python as a DataFrame named _sqldf. Treat it as a convenience for exploration. Code that other people will run should use an explicit view or spark.sql, because _sqldf is overwritten by every SQL cell.
A temporary view lives only as long as the notebook's session. Another notebook attached to the same cluster has its own session and does not see it. For data that must outlive the session, write a table.
Non-language magics
Some magic commands change what a cell does instead of choosing a language.
| Magic | Purpose |
|---|---|
| `%sh` | Run shell commands on the driver node |
| `%fs` | Shortcut for file system commands, equivalent to `dbutils.fs` |
| `%pip` | Install Python libraries for this notebook |
| `%run` | Run another notebook inline |
%sh runs on the driver only
%sh executes a shell on the driver node of the compute. It does not run on workers, and the files it sees are the driver's local disk. Files written there are lost when the compute terminates.
%sh
ls -la /tmp
python --versionA common error is to download a file with %sh wget and then expect Spark executors to read it by local path. The executors run on other machines and cannot see it. Copy the file to cloud storage or a volume first.
%pip installs notebook-scoped libraries
%pip install adds a package for the current notebook session only, so other notebooks on the same compute are unaffected.
%pip install requests==2.32.3Two rules prevent most problems:
- Put
%pipcells at the top of the notebook. Installing a package can restart the Python interpreter and clear your Python variables. - If you need the restart without an install, call
dbutils.library.restartPython()in its own cell.
%run is covered later
%run ./shared_setup runs another notebook inline so its functions and variables land in your session. It must be alone in its cell. The chapter on reusing notebooks compares it with dbutils.notebook.run, so this chapter does not go further.
Markdown cells
A %md cell renders as formatted text. Use it for headings, explanations, and links to documentation. It gives a notebook structure that reviewers can follow, and it costs nothing at run time.
# MAGIC %md
# MAGIC ## Load step
# MAGIC Reads yesterday's files and writes the bronze table.The snippet above is not something you type into a cell. It shows how the same Markdown cell looks in the notebook's source file, where every magic line is prefixed with # MAGIC. The chapter on the source format explains that layout.
Running output and display
print writes plain text. display(df) renders a DataFrame as an interactive table that you can sort and turn into a chart. A %sql cell shows its result in the same table format automatically. Rendering is capped at a limited number of rows in the browser, so display is for inspection and not for exporting data.
Common errors
- Magic not on the first line. The cell runs in the default language and fails with a confusing syntax error.
- Expecting a variable across languages.
NameErrorin Python or "table or view not found" in SQL usually means the value was never put in the shared session. - Relying on cell order. A notebook that works only after cells are run in a private order breaks when run as a job, which runs top to bottom.
- Using
%shfor distributed work. It runs on one machine. %pipin the middle. It can wipe Python state defined earlier.
Exercise
A Python notebook has a cell that creates a DataFrame orders and a later %sql cell containing SELECT * FROM orders. The SQL cell fails. Give a fix that keeps the SQL cell unchanged, and say why the failure happened.
Show answer
Add orders.createOrReplaceTempView("orders") to the Python cell. The Python variable orders exists only in the Python interpreter, and SQL cells cannot see it. A temporary view registers the data in the shared Spark session, where the SQL cell can find it by name.