Sub topic 8
Working in Notebooks
A notebook is the main place where you write and run code in a Databricks workspace. This chapter assumes you know basic SQL and Python, and that you have read the chapters on compute and the workspace. You should also know that a notebook needs compute to run.
The working model
A notebook is an ordered list of cells. Each cell holds code or Markdown text. You run cells one at a time or all together, and the output appears under each cell.
A notebook does not run anything by itself. You attach it to compute, such as a cluster or serverless compute. The compute runs your code and keeps the state, such as variables and temporary views, until you detach it or the compute stops.
Each notebook has a default language, such as Python or SQL. A cell can override it with a magic command on its first line: %sql, %python, %scala, %r, or %md for Markdown.
Predefined objects
Databricks creates a Spark session for you and calls it spark. You do not build it yourself. The display function shows a DataFrame as an interactive table, and you can switch the view to a chart.
This cell reads the table from the earlier chapters and totals the amount for each customer:
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)The next cell is in the same notebook, but it switches to SQL for one step:
%sql
SELECT customer_id, COUNT(*) AS order_count
FROM main.tutorial.orders
GROUP BY customer_idBoth cells use the same three-level name, catalog.schema.table. They read the same governed data, so you can mix Python and SQL freely.
Sharing state between languages
Variables do not cross languages. A Python variable is not visible in a %sql cell. To pass data, register a temporary view in Python and query it from SQL:
totals.createOrReplaceTempView("customer_totals")%sql
SELECT * FROM customer_totals ORDER BY total_amount DESCCommon errors
- Not attached to compute. Cells fail or will not start. Attach the notebook and wait for the compute to reach the running state.
- Stale state after a restart. When compute restarts, all variables and views are lost. Run the cells again from the top.
- Running cells out of order. A cell can use a variable defined further down. The notebook works for you now and fails when someone runs it top to bottom. Use "Run all" before you share it.
- Missing permissions. A
TABLE_OR_VIEW_NOT_FOUNDor permission error often means you lackUSE CATALOG,USE SCHEMA, orSELECT, or that the name is wrong.
Exercise
You define totals in a Python cell. A later %sql cell runs SELECT * FROM totals and fails. Why, and how do you fix it?
Show answer
Python variables are not visible to SQL cells. Register the DataFrame as a temporary view in Python with totals.createOrReplaceTempView("totals"). Then the SQL cell can query it.