---
title: Develop code in Databricks notebooks
description: "Develop code in Databricks notebooks: format Python and SQL cells, mix languages with magic commands, run SQL in parallel, and modularize code with files."
canonical_url: https://docs.databricks.com/aws/en/notebooks/notebooks-code
---

# Develop code in Databricks notebooks

Databricks notebooks support code formatting, autocomplete, multiple languages, and magic commands for developing code in Python, SQL, Scala, and R.

For more details about advanced functionality available with the editor, such as autocomplete, variable selection, multi-cursor support, and side-by-side diffs, see [Navigate the Databricks notebook and file editor](https://docs.databricks.com/aws/en/notebooks/notebook-editor.md).

When you use the notebook or the file editor, Genie Code is available to help you generate, explain, and debug code. See [Use Genie Code](https://docs.databricks.com/aws/en/genie-code/features-capabilities.md) for more information.

Databricks notebooks also include a built-in interactive debugger for Python notebooks. See [Debug Databricks notebooks](https://docs.databricks.com/aws/en/notebooks/debugger.md).

> [!IMPORTANT]
>
> The notebook must be attached to an active [compute session](https://docs.databricks.com/aws/en/notebooks/notebook-compute.md) for code assistance features, including autocomplete, Python code formatting, and the debugger.

## Modularize your code

With Databricks Runtime 11.3 LTS and above, you can create and manage source code files in the Databricks workspace, and then import these files into your notebooks as needed.

For more information on working with source code files, see [Share code between Databricks notebooks](https://docs.databricks.com/aws/en/notebooks/share-code.md) and [Work with Python and R modules](https://docs.databricks.com/aws/en/files/workspace-modules.md).

## <a id="notebook-format" />Format code cells

Databricks provides tools that allow you to format Python and SQL code in notebook cells. These tools reduce the effort to keep your code formatted and help to enforce the same coding standards across your notebooks.

### <a id="format-python-cells" />Python black formatter library

> [!NOTE]
> **Preview**
>
> This feature is in [Public Preview](https://docs.databricks.com/aws/en/release-notes/release-types.md).

Databricks supports Python code formatting using [black](https://black.readthedocs.io/en/stable/) within the notebook. The notebook must be attached to a cluster with `black` and `tokenize-rt` Python packages installed.

On Databricks Runtime 11.3 LTS and above, Databricks preinstalls `black` and `tokenize-rt`. You can use the formatter directly without needing to install these libraries.

On Databricks Runtime 10.4 LTS and below, you must install `black==22.3.0` and `tokenize-rt==4.2.1` from PyPI on your notebook or cluster to use the Python formatter. You can run the following command in your notebook:

```
%pip install black==22.3.0 tokenize-rt==4.2.1
```

or [install the library on your cluster](https://docs.databricks.com/aws/en/libraries/cluster-libraries.md).

For more details about installing libraries, see [Python environment management](https://docs.databricks.com/aws/en/libraries/index.md#python-environment-management).

For files and notebooks in Databricks Git folders, you can configure the Python formatter based on the `pyproject.toml` file. To use this feature, create a `pyproject.toml` file in the Git folder root directory and configure it according to the [Black configuration format](https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#configuration-format). Edit the \[tool.black] section in the file. The configuration is applied when you format any file and notebook in that Git folder.

### <a id="sql-format" />How to format Python and SQL cells

You must have [CAN EDIT permission](https://docs.databricks.com/aws/en/notebooks/notebooks-collaborate.md#notebook-permissions) on the notebook to format code.

Databricks uses a custom SQL formatter to format SQL and the [black](https://github.com/psf/black) code formatter for Python.

You can trigger the formatter in the following ways:

* **Format a single cell**
  * Keyboard shortcut: Press **Cmd+Shift+F**.
  * Command context menu:
    * Format SQL cell: Select **Format SQL** in the command context dropdown menu of a SQL cell. This menu item is visible only in SQL notebook cells or those with a `%sql` [language magic](https://docs.databricks.com/aws/en/notebooks/notebooks-code.md#language-magic).
    * Format Python cell: Select **Format Python** in the command context dropdown menu of a Python cell. This menu item is visible only in Python notebook cells or those with a `%python` [language magic](https://docs.databricks.com/aws/en/notebooks/notebooks-code.md#language-magic).
  * Notebook **Edit** menu: Select a Python or SQL cell, and then select **Edit > Format Cell(s)**.

* **Format multiple cells**

  [Select multiple cells](https://docs.databricks.com/aws/en/notebooks/basic-editing.md#run-selected-cells) and then select **Edit > Format Cell(s)**. If you select cells of more than one language, only SQL and Python cells are formatted. This includes those that use `%sql` and `%python`.

* **Format all Python and SQL cells in the notebook**

  Select **Edit > Format Notebook**. If your notebook contains more than one language, only SQL and Python cells are formatted. This includes those that use `%sql` and `%python`.

To customize how your SQL queries are formatted, see [Custom format SQL statements](https://docs.databricks.com/aws/en/sql/user/sql-editor/custom-format.md).

### Limitations of code formatting

* Black enforces [PEP 8](https://peps.python.org/pep-0008/) standards for 4-space indentation. Indentation is not configurable.
* Formatting embedded Python strings inside a SQL UDF is not supported. Similarly, formatting SQL strings inside a Python UDF is not supported.

## Code languages in notebooks

### <a id="default-language" />Set default language

The default language for the notebook appears below the notebook name.

![Notebook default language](https://docs.databricks.com/aws/en/images/notebooks/toolbar.png)

To change the default language, click the language button and select the new language from the dropdown menu. To ensure that existing commands continue to work, commands of the previous default language are automatically prefixed with a language magic command.

### <a id="language-magic" />Mix languages

By default, cells use the default language of the notebook. You can override the default language in a cell by clicking the language button and selecting a language from the dropdown menu.

![Cell language drop down](https://docs.databricks.com/aws/en/images/notebooks/cell-language-button.png)

Alternatively, you can use the language magic command `%<language>` at the beginning of a cell. The supported magic commands are: `%python`, `%r`, `%scala`, and `%sql`.

> [!NOTE]
>
> When you invoke a language magic command, the command is dispatched to the REPL in the execution context for the notebook. Variables defined in one language (and hence in the REPL for that language) are not available in the REPL of another language. REPLs can share state only through external resources such as files in DBFS or objects in object storage.

Notebooks also support a few auxiliary magic commands:

* `%sh`: Allows you to run shell code in your notebook. To fail the cell if the shell command has a non-zero exit status, add the `-e` option. This command runs only on the Apache Spark driver, and not the workers. To run a shell command on all nodes, use an [init script](https://docs.databricks.com/aws/en/init-scripts/index.md).
* `%fs`: Allows you to use `dbutils` filesystem commands. For example, to run the `dbutils.fs.ls` command to list files, you can specify `%fs ls` instead. For more information, see [Work with files on Databricks](https://docs.databricks.com/aws/en/files/index.md).
* `%md`: Allows you to include various types of documentation, including text, images, and mathematical formulas and equations. See the next section.

### SQL syntax highlighting and autocomplete in Python commands

Syntax highlighting and SQL [autocomplete](https://docs.databricks.com/aws/en/notebooks/notebook-editor.md#autocomplete) are available when you use SQL inside a Python command, such as in a `spark.sql` command.

### <a id="implicit-sql-df" />Explore SQL cell results

In a Databricks notebook, results from a SQL language cell are automatically made available as an implicit DataFrame assigned to the variable `_sqldf`. You can then use this variable in any Python and SQL cells you run afterward, regardless of their position in the notebook.

> [!NOTE]
>
> This feature has the following limitations:
>
> * The `_sqldf` variable is not available in notebooks that use a [SQL warehouse](https://docs.databricks.com/aws/en/compute/sql-warehouse/index.md) for compute.
> * Using `_sqldf` in subsequent Python cells is supported in Databricks Runtime 13.3 and above.
> * Using `_sqldf` in subsequent SQL cells is only supported on Databricks Runtime 14.3 and above.
> * If the query uses the keywords `CACHE TABLE` or `UNCACHE TABLE`, the `_sqldf` variable is not available.

The screenshot below shows how `_sqldf` can be used in subsequent Python and SQL cells:

![sql results dataframe](https://docs.databricks.com/aws/en/images/notebooks/_sqldf_python_sql.png)

> [!IMPORTANT]
>
> The variable `_sqldf` is reassigned each time a SQL cell is run. On supported compute, use a [custom output name](https://docs.databricks.com/aws/en/notebooks/notebooks-code.md#name-sql-cell-results) to keep a reference to a specific result. On other compute that supports `_sqldf`, assign the result to a new variable name before you run the next SQL cell:
>
> #### Python
>
> ```python
> new_dataframe_name = _sqldf
> ```
>
> #### SQL
>
> ```sql
> ALTER VIEW _sqldf RENAME TO new_dataframe_name
> ```

### Name SQL cell results

You can assign a custom name to the result of a SQL cell in notebooks connected to compute running Databricks Runtime 18.2 or above, or in serverless notebooks running [environment version 5](https://docs.databricks.com/aws/en/release-notes/serverless/environment-version/five.md) or above. SQL warehouses do not support custom SQL result names.

To name a result, add `--name <identifier>` to the `%sql` magic command on the first non-empty line of the cell. Use a valid Python identifier that starts with a letter or underscore and contains only letters, digits, and underscores. The identifier must be the last item on the line.

When `_sqldf` is supported for the compute and query, it remains available for compatibility and refers to the most recently run SQL cell result.

You can also rename a result directly in the result banner by clicking the result name.

![SQL cell output saved as nyc\_taxi\_trips in the result banner.](https://docs.databricks.com/aws/en/images/notebooks/name-sql-cell-results.png)

Renaming adds or updates `%sql --name <identifier>` in the cell. If the cell is no longer the source of `_sqldf`, rerun the cell to create the renamed result.

### <a id="sql-run-now" />Run SQL cells in parallel

While a command is running and your notebook is attached to an interactive cluster, you can run a SQL cell simultaneously with the current command. The SQL cell is executed in a new, parallel session.

To run a cell in parallel:

1. [Run the cell](https://docs.databricks.com/aws/en/notebooks/run-notebook.md).
2. Click **Run now**. The cell is immediately executed.

   ![Run a SQL cell in parallel with current running cell.](https://docs.databricks.com/aws/en/images/notebooks/parallel-sql-execution.png)

Because the cell is run in a new session, temporary views, UDFs, and the [implicit Python DataFrame](https://docs.databricks.com/aws/en/notebooks/notebooks-code.md#implicit-sql-df) (`_sqldf`) are not supported for cells that are executed in parallel. In addition, the default catalog and database names are used during parallel execution. If your code refers to a table in a different catalog or database, you must specify the table name using three-level namespace (`catalog`.`schema`.`table`).

### Run SQL cells on a SQL warehouse

You can run SQL commands in a Databricks notebook on a [SQL warehouse](https://docs.databricks.com/aws/en/compute/sql-warehouse/index.md), a type of compute that is optimized for SQL analytics. See [Use a notebook with a SQL warehouse](https://docs.databricks.com/aws/en/notebooks/notebook-compute.md#notebook-sql-warehouse).

## <a id="magic-commands-reference" />Use magic commands

Databricks notebooks support various magic commands that extend functionality beyond standard syntax to simplify common tasks. Line magics are prefixed with `%` and apply to a single line. Cell magics are prefixed with `%%` and apply to the entire cell body.

| **Magic command**                 | **Example**                              | **Description**                                                                                                                                                                                                                                                                           |
| --------------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `%python`                         | `%python`<br />`print("Hello")`          | Switch cell language to Python. Executes Python code in the cell.                                                                                                                                                                                                                         |
| `%r`                              | `%r`<br />`print("Hello")`               | Switch cell language to R. Executes R code in the cell.                                                                                                                                                                                                                                   |
| `%scala`                          | `%scala`<br />`println("Hello")`         | Switch cell language to Scala. Executes Scala code in the cell.                                                                                                                                                                                                                           |
| `%sql`                            | `%sql`<br />`SELECT * FROM table`        | Switch cell language to SQL. Results are available as `_sqldf` or, on supported compute, under a [custom name](https://docs.databricks.com/aws/en/notebooks/notebooks-code.md#name-sql-cell-results) in subsequent Python and SQL cells.                                                  |
| `%md`                             | `%md`<br />`# Title`<br />`Content here` | Switch cell language to Markdown. Renders Markdown content in the cell. Supports text, images, formulas, and LaTeX.                                                                                                                                                                       |
| `%pip`                            | `%pip install pandas`                    | Install Python packages (notebook-scoped). See [Notebook-scoped Python libraries](https://docs.databricks.com/aws/en/libraries/notebooks-python-libraries.md).                                                                                                                            |
| `%run`                            | `%run /path/to/notebook`                 | Execute another notebook, importing its functions and variables. See [Notebook workflows](https://docs.databricks.com/aws/en/notebooks/notebook-workflows.md#run).                                                                                                                        |
| `%fs`                             | `%fs ls /path`                           | Execute dbutils filesystem commands. Shorthand for `dbutils.fs` commands. See [Work with files](https://docs.databricks.com/aws/en/files/index.md).                                                                                                                                       |
| `%sh`                             | `%sh ls -la`                             | Execute shell commands. Runs only on driver node. Use `-e` to fail on error.                                                                                                                                                                                                              |
| `%tensorboard`                    | `%tensorboard --logdir /logs`            | Display TensorBoard UI inline. Available only on Databricks Runtime ML. See [TensorBoard](https://docs.databricks.com/aws/en/machine-learning/train-model/tensorboard.md).                                                                                                                |
| `%set_cell_max_output_size_in_mb` | `%set_cell_max_output_size_in_mb 10`     | Set maximum cell output size. Range: 1-20 MB. Applies to all subsequent cells in notebook.                                                                                                                                                                                                |
| `%skip`                           | `%skip`<br />`print("This won't run")`   | Skip cell execution. Prevents the cell from running when the notebook is executed.                                                                                                                                                                                                        |
| `%%profile`                       | `%%profile`<br />`my_function()`         | Profile Python code execution. Displays a hierarchical call tree with timing information. Requires Databricks Runtime 17.2 and above.                                                                                                                                                     |
| `%%oprofile`                      | `%%oprofile`<br />`my_function()`        | Profile object creation during cell execution. Displays a table of net new objects created, grouped by type. Requires Databricks Runtime 17.2 and above.                                                                                                                                  |
| `%uv pip`                         | `%uv pip install simplejson`             | Install and manage Python packages (notebook-scoped) with `uv` and standard pip subcommands (`install`, `uninstall`, `list`, `show`, `freeze`, `check`, `tree`). See [Faster installs with `%uv pip`](https://docs.databricks.com/aws/en/libraries/notebooks-python-libraries.md#uv-pip). |

> [!NOTE]
>
> **IPython Automagic**: Databricks notebooks have IPython automagic enabled by default, allowing certain commands like `pip` to work without the `%` prefix. For example, `pip install pandas` works the same as `%pip install pandas`.

> [!IMPORTANT]
>
> * Variables and state are isolated between different language REPLs. For example, Python variables are not accessible in Scala cells.
> * A notebook cell can only have one cell magic command, and it must be the first line of the cell.
> * `%run` must be in a cell by itself, because it runs the entire notebook inline.
> * When using `%pip` on Databricks Runtime 12.2 LTS and below, place all package installation commands at the beginning of your notebook as the Python state is reset after installation.
