Sub topic 1
What a Databricks notebook is
A Databricks notebook is a document in your workspace that holds ordered cells of code and text. You run cells one at a time against a compute resource and see results directly below each cell. This chapter gives you the working model for the rest of the tutorial.
Prerequisites
This chapter assumes you have:
- Basic Python or SQL.
- Basic Git concepts: commit, branch, push, pull, merge.
- Familiarity with the Databricks workspace UI.
You do not need a Git account yet. Git folders come later in the tutorial.
The working model
A notebook has three parts that you should keep separate in your head.
- Cells. Each cell holds code or Markdown text. Cells run in the order you trigger them, not necessarily top to bottom.
- A default language. Each notebook has one default language, such as Python or SQL. A cell can override it with a magic command like
%sql. - Compute. The notebook does not run code itself. You attach it to a cluster or other compute, and that compute executes the cells.
The notebook stores code and results. The compute holds state, such as variables and temporary views. If the compute restarts or you detach the notebook, that state is gone, but the code stays.
A first notebook
Create a notebook from the workspace with New > Notebook. Choose a default language and attach compute from the selector at the top. In the first cell, run this:
df = spark.range(5)
display(df)spark is a SparkSession that Databricks creates for you on attached compute. spark.range(5) builds a DataFrame with one column, id, holding the numbers 0 to 4. display renders it as an interactive table.
In a new cell, switch language with a magic command:
%sql
SELECT 1 AS oneThe %sql line must be the first line of the cell. Only that cell runs as SQL. The rest of the notebook stays in the default language.
Common errors
- Running cells out of order. A cell that uses
dffails with aNameErrorif the cell that defines it has not run on the current compute. Use Run all to check that the notebook works top to bottom. - Forgetting to attach compute. Without attached compute, a cell cannot run. Attach compute first.
- Assuming state survives a restart. Variables disappear when compute restarts. Rerun the cells that create them.
- Wrong magic placement. A magic command that is not on the first line of its cell is not treated as a magic command.
Exercise
You define df in cell 3, detach the notebook, and attach it to a different cluster. Cell 4 uses df. What happens when you run cell 4, and why?
Show answer
It fails with a NameError. The variable df lived in the memory of the previous compute. The new compute has no such state, so you must rerun cell 3 first.