Databricks notebooks are an interactive development environment that supports four languages: Python, SQL, Scala, and R. You can switch languages within a single notebook using magic commands, and real-time collaborative editing is fully supported.
This article systematically covers every magic command, the collaboration and permission model, execution contexts (interactive vs. job), parameterization with widgets, notebook chaining, and Git integration via Repos.
When you create a notebook, you pick one default language (Python / SQL / Scala / R). Each cell runs in the default language, but you can switch languages per cell by putting a magic command (%python, %sql, etc.) at the top of the cell.
%python
# Python cell: create a DataFrame and register it as a TempView
df = spark.range(100).toDF("id")
df.createOrReplaceTempView("numbers")
%sql
-- SQL cell: reference the TempView created in Python
SELECT id, id * 10 AS multiplied FROM numbers WHERE id < 10;
%scala
// Scala cell: shares the same SparkSession
val df = spark.sql("SELECT * FROM numbers LIMIT 5")
df.show()The SparkSession is shared across languages, so a TempView created in Python can be referenced from SQL or Scala. However, Python and Scala variables cannot be shared directly — you exchange data through TempViews or Delta tables.
| Command | Purpose | Execution Target | Typical Use Case |
|---|---|---|---|
| %python | Run as a Python cell | Attached cluster (driver) | DataFrame ops, pandas, library calls |
| %sql | Run as a SQL cell | Attached cluster (Spark SQL) | SELECT / DDL / DML; results auto-displayed |
| %scala | Run as a Scala cell | Attached cluster (JVM) | Type-safe Spark code, Java interop |
| %r | Run as an R cell | Attached cluster (SparkR) | Statistical analysis and R-based visualization |
| %md | Render as Markdown | Client-side (no execution) | Documentation, section headers, explanatory text |
| %run | Inline-load another notebook into the same session | Attached cluster | Load shared setup or utility functions |
| %sh | Run shell commands | Driver node OS | File checks, package info, curl |
| %fs | DBFS file system operations | DBFS (shortcut for dbutils.fs) | ls, cp, head, mkdirs |
| %pip | Install Python packages | Cluster's Python environment | pip install package==version |
%sh runs on the driver node's OS, not on worker nodes. Its output also cannot be passed directly to Spark processing, so use it for file inspection and debugging.
Databricks notebooks support real-time collaborative editing. Multiple users can edit cells simultaneously, and changes are reflected to others instantly. Comments and @mentions enable in-line review discussions.
Notebooks and folders have four tiers of access permissions:
| Permission Level | View | Run | Edit | Manage Permissions | Use Case |
|---|---|---|---|---|---|
| CAN VIEW | Yes | No | No | No | Reviewers, view-only stakeholders |
| CAN RUN | Yes | Yes | No | No | Analysts, job operators |
| CAN EDIT | Yes | Yes | Yes | No | Developers responsible for code changes |
| CAN MANAGE | Yes | Yes | Yes | Yes | Administrators, project owners |
Notebooks have two execution modes — choose the right one for the job at hand.
| Execution Mode | Compute Resource | Session State | Best For |
|---|---|---|---|
| Interactive execution | All-Purpose Cluster (shareable) | Variables and caches persist across cells | Exploration, development, debugging, ad-hoc analysis |
| Job execution | Job Cluster (dedicated; start then terminate) | Starts from a clean state every time | Scheduled batches, production ETL, workloads needing reproducibility |
# Interactive execution
# Notebook -> attached to an All-Purpose Cluster -> run cells interactively
#
# Job execution
# Workflows -> spin up a Job Cluster -> run the notebook top to bottom -> terminate
#
# +-------------+ attach +--------------------+
# | Notebook |------------->| All-Purpose Cluster| (interactive)
# | (dev/explore)| | (shared, stateful) |
# +-------------+ +--------------------+
#
# +-------------+ task +--------------------+
# | Workflow |------------->| Job Cluster | (job)
# | (scheduled) | create | (dedicated, fresh) |
# +-------------+ +--------------------+In interactive execution, results from earlier cells (variables, temp views, etc.) carry over to later cells. Job execution starts from a clean environment every time, so designs that do not depend on external state (idempotent writes, explicit parameter passing) are critical.
To reuse the same notebook across dates, environments, or filter conditions, parameterize it with widgets. Widgets integrate with Workflows task parameters (Base parameters), so values can be injected at job run time.
%python
# Create widgets (4 types)
dbutils.widgets.text("proc_date", "2026-01-01", "Processing date")
dbutils.widgets.dropdown("env", "dev", ["dev", "staging", "prod"], "Environment")
dbutils.widgets.combobox("region", "APAC", ["APAC", "EMEA", "NA"], "Region")
dbutils.widgets.multiselect("status", "active", ["active", "inactive", "pending"], "Status")
# Read widget values
proc_date = dbutils.widgets.get("proc_date")
env = dbutils.widgets.get("env")
# Use the values in a query
df = spark.sql(f"""
SELECT * FROM {env}_catalog.orders.daily
WHERE order_date = '{proc_date}'
""")
df.display()
# Return a result when the notebook ends (parent job receives it)
dbutils.notebook.exit(f"OK: {proc_date}, rows={df.count()}")There are four widget types: text (free entry), dropdown (single choice), combobox (choice plus free entry), and multiselect (multiple choice). When Workflows runs the job, values are auto-injected as long as Base parameter keys match widget names.
There are two ways to call one notebook from another, and they differ critically in whether they share state.
| Invocation Method | Execution Context | Variable Sharing | Return Value | Recommended Use |
|---|---|---|---|---|
| %run ./path/to/notebook | Same session (inline load) | Fully shared (variables, functions, UDFs) | None (reference session variables directly) | Loading shared setup, debugging during development |
| dbutils.notebook.run() | Isolated session | None (fully isolated) | String (returned via dbutils.notebook.exit) | Production jobs, isolated execution of child tasks |
%python
# Option 1: %run - inline load into the same session (shared state)
# %run ./includes/common_setup
# -> all variables and functions defined in common_setup are available
# -> state can leak, so be careful in production
# Option 2: dbutils.notebook.run - isolated execution (recommended for production)
result = dbutils.notebook.run(
"./jobs/etl_daily",
timeout_seconds=3600,
arguments={"proc_date": "2026-03-27", "env": "prod"}
)
print(f"Child notebook result: {result}")
# -> e.g., "OK: 2026-03-27, rows=15234"
# Run multiple notebooks in parallel (with ThreadPoolExecutor)
from concurrent.futures import ThreadPoolExecutor
notebooks = ["./jobs/etl_orders", "./jobs/etl_customers", "./jobs/etl_products"]
with ThreadPoolExecutor(max_workers=3) as executor:
futures = [
executor.submit(dbutils.notebook.run, nb, 3600, {"proc_date": "2026-03-27"})
for nb in notebooks
]
results = [f.result() for f in futures]Databricks Repos integrates with Git providers (GitHub, GitLab, Bitbucket, Azure DevOps) and lets you manage notebooks and Python modules at the branch level.
%python
# Import a Python module from a Repo
# /Repos/[email protected]/my-project/mypkg/transform.py
from mypkg.transform import run_etl, validate_output
# Keep the notebook focused on orchestration
result_df = run_etl(spark, source="s3://landing/orders/", date="2026-03-27")
validation = validate_output(result_df, expected_min_rows=1000)
if not validation["passed"]:
dbutils.notebook.exit(f"VALIDATION_FAILED: {validation['reason']}")
result_df.write.format("delta").mode("overwrite").saveAsTable("gold.daily_orders")Data Engineer Associate
問題 1
From notebook A, you want to call notebook B, inspect B's result (a success/failure status string) in A, and branch downstream processing on it. The variable namespaces of A and B must be isolated. Which approach is most appropriate?
正解: B
dbutils.notebook.run executes a notebook in an isolated context and lets you receive the string returned by dbutils.notebook.exit. %run loads the notebook into the same session, so variable namespaces are shared. Folder layout and the %sql magic do not implement notebook chaining or state isolation.
What is the difference between %run and dbutils.notebook.run?
%run loads the called notebook into the same session, sharing all variables, functions, and UDFs. dbutils.notebook.run executes in an isolated context, and the only return value is the string passed to dbutils.notebook.exit. For production jobs, dbutils.notebook.run is recommended because of the state isolation.
Does %sql in a notebook run on a SQL Warehouse?
%sql in a regular notebook executes on the attached Spark cluster. The SQL Warehouse is the execution engine for Databricks SQL (SQL Editor and dashboards). To connect from a notebook to a SQL Warehouse, you use a JDBC/ODBC connection or the Databricks SQL Connector instead of spark.sql().
How should I manage packages inside a notebook?
For production jobs, pin the Databricks Runtime version and pin package versions with %pip install package==version. A common pattern is to place requirements.txt under a Repo and run %pip install -r requirements.txt at the top of the notebook. You can also install packages as cluster libraries, but be careful of dependency conflicts across jobs.
Practice with certification-focused question sets
無料で問題を解いてみるNicheeLab Editorial Team
NicheeLab editorial team focused on data engineering and cloud certification learning. Content is structured around practical study needs and official exam domains.
Databricks Certifications: All 7 Exams, Difficulty & Study Plan (2026)
Complete guide to all 7 Databricks certifications — Data Eng...
Databricks Exam Difficulty Ranking: All 7 Certs Compared (2026)
Every Databricks certification ranked by difficulty, with st...
Databricks Study Guide: Fastest Pass Route & Time Estimates (2026)
How to pass Databricks certifications efficiently. Official ...
Databricks Data Engineer Associate: Complete Guide (2026)
Domain-by-domain breakdown of the Databricks Certified Data ...
Databricks Data Engineer Professional: Complete Guide (2026)
Tactics for the Databricks Certified Data Engineer Professio...