Sub topic 1
What a Databricks notebook is
Prerequisites
This chapter assumes you have the following:
- Basic Python or SQL, enough to read a short script or query.
- Basic Git concepts: commit, branch, push, pull, and merge.
- Familiarity with the Databricks workspace UI, such as the sidebar and the workspace file browser.
- A Git account with a provider Databricks supports, such as GitHub, GitLab, Azure DevOps, or Bitbucket. You will not use it until later chapters.
You do not need to have written a Databricks notebook before.
The working model
A Databricks notebook is an ordered list of cells that you run against a compute resource. Each cell holds code or formatted text. The notebook is the unit you edit, share, schedule, and, in later chapters, version in Git.
Three parts make up the model:
- The document. The cells, their order, and their saved outputs. It lives in the workspace and is stored as an object with a default language.
- The compute. A cluster or serverless compute that executes the code. The notebook does not run anything by itself.
- The session. The running state created when the notebook is attached to compute: variables, imported modules, temporary views, and widget values. The session is not part of the document.
Keeping these three apart explains most surprises. If you detach a notebook, the document stays, but the session state is gone. If two people open the same notebook, they share the document but each has a separate session unless they attach to the same compute, and even then each notebook has its own isolated Python state.
Default language and cell types
Every notebook has a default language, chosen when you create it: Python, SQL, Scala, or R. A cell without a prefix runs in that language. You can override the language for one cell with a magic command such as %sql on its first line. Later chapters cover magics in detail. For now, remember that the default language is a property of the notebook, and that individual cells can differ.
Cells come in two kinds:
- Code cells run on the compute and show output below the cell.
- Markdown cells use the
%mdmagic and render as formatted text. Use them for titles, explanations, and links.
Here is a short notebook with a Markdown cell, a Python cell, and a SQL cell, shown the way Databricks stores a Python notebook as a source file:
# Databricks notebook source
# MAGIC %md
# MAGIC # Daily load
# COMMAND ----------
df = spark.range(5)
display(df)
# COMMAND ----------
# MAGIC %sql
# MAGIC SELECT 1 AS oneIn the editor you see three separate cells. In the stored file, the line # COMMAND ---------- separates them, and magic cells are written as # MAGIC comments. The notebook source format has its own chapter, so treat this only as a preview.
In the Python cell, spark is a SparkSession that Databricks creates for you, and display() renders a DataFrame as an interactive table. You do not create or import either one.
How cells run
A cell runs when you press Shift+Enter, use the run button, or choose Run all. The important rules are these:
- Cells share one session per language runtime, so a variable defined in one cell is visible in later cells.
- Execution order is the order you trigger, not the order on the page. You can run cell 5 before cell 2.
- Output is saved with the notebook until you clear it. Seeing a result does not prove the current code produces it.
The second rule is the source of the most common notebook bug: hidden state. Suppose you define threshold = 10 in a cell, run a later cell that uses it, then edit the first cell to threshold = 20 and forget to re-run the later cell. The page shows 20, but the output was computed with 10. Before you trust or share a notebook, use Run all on fresh compute to confirm the cells work top to bottom.
Creating a notebook and a first run
To create a notebook in the workspace UI, choose New, then Notebook, or use the Create option in the workspace folder you want. Give it a name and a default language, then attach it to compute from the selector at the top of the notebook (the next chapter covers this).
Run this in a Python notebook to see the pieces of the model:
import sys
print(sys.version.split()[0])
print(spark.version)
data = [("alice", 3), ("bob", 5)]
df = spark.createDataFrame(data, ["name", "score"])
display(df)The first two lines tell you which Python and Spark versions the compute provides. The DataFrame is created in the session. If you detach and reattach the notebook to compute, df is gone and you must run the cell again.
What is and is not saved
| Item | Saved with the notebook | Lost when the session ends |
|---|---|---|
| Cell code and order | Yes | No |
| Default language | Yes | No |
| Cell outputs | Yes, until cleared | No |
| Variables and DataFrames | No | Yes |
| Temporary views | No | Yes |
| Installed notebook-scoped libraries | No | Yes |
| Tables written to storage | Not part of the notebook | No |
Data you write to a table or file persists independently of the notebook. A notebook that only builds a DataFrame and never writes it leaves nothing behind once the session ends.
Common errors
- "Cell does not run" or a long wait for the first cell. The notebook is not attached to compute, or the compute is still starting. Check the selector at the top.
NameErrorfor a variable you are sure you defined. The cell that defines it has not run in the current session. This often follows a compute restart or reattach.- Wrong results after editing earlier cells. Later cells are stale. Re-run them, or use Run all.
- A SQL cell fails with a Python-looking error, or the reverse. The cell ran in the notebook's default language because the magic was missing or not on the first line.
- Large saved outputs. Notebooks with many large displayed results become slow to open and awkward to review in Git. Display samples with
limit()rather than whole tables.
Where notebooks fit in the rest of this tutorial
The notebook is the starting point of the path this tutorial follows. You will attach it to compute, add parameters, call it from other notebooks, then store it in a Git repository and run it as a job. Each step depends on the model in this chapter: a document, a compute, and a session that is separate from both.
Exercise
You edit a cell that sets threshold = 20, run only the cell below it, and the output still looks like it used threshold = 10. Which part of the notebook model explains this, and what is the quickest way to get a trustworthy result?
Show answer
The variable lives in the session, not in the document. The edited cell was never re-run, so the session still holds threshold = 10, and the displayed output is stale. Re-run the edited cell and then the dependent cells, or use Run all, ideally on freshly attached compute, so the results reflect the code on the page.
Exercise
A colleague opens your notebook, which is attached to the same cluster as theirs, and expects to see your DataFrame df. Why will it not be there, and what would make the data available to them?
Show answer
Each notebook has its own isolated session state, so variables are not shared between notebooks, even on the same compute. Write the data to a table or file, which persists independently of any session, and have the colleague read it from there.