---
title: Connect to dbt Cloud
description: Learn how to connect your Databricks workspace to dbt Cloud, a hosted service that helps data analysts and engineers productionize dbt deployments.
canonical_url: https://docs.databricks.com/aws/en/partners/prep/dbt-cloud
---

# Connect to dbt Cloud

dbt (data build tool) is a development environment that enables data analysts and data engineers to transform data by simply writing select statements. dbt handles turning these select statements into tables and views. dbt compiles your code into raw SQL and then runs that code on the specified database in Databricks. dbt supports collaborative coding patterns and best practices such as version control, documentation, and modularity.

dbt does not extract or load data. dbt focuses on the transformation step only, using a “transform after load” architecture. dbt assumes that you already have a copy of your data in your database.

This article focuses on dbt Cloud. dbt Cloud comes equipped with turnkey support for scheduling jobs, CI/CD, serving documentation, monitoring and alerting, and an integrated development environment (IDE).

A local version of dbt called dbt Core is also available. dbt Core enables you to write dbt code in the text editor or IDE of your choice on your local development machine and then run dbt from the command line. dbt Core includes the dbt Command Line Interface (CLI). The dbt CLI is free to use and open source. For more information, see [Connect to dbt Core](https://docs.databricks.com/aws/en/partners/prep/dbt.md).

Because dbt Cloud and dbt Core can use hosted git repositories (for example, on GitHub, GitLab or BitBucket), you can use dbt Cloud to create a dbt project and then make it available to your dbt Cloud and dbt Core users. For more information, see [Creating a dbt project](https://docs.getdbt.com/docs/building-a-dbt-project/projects#creating-a-dbt-project) and [Using an existing project](https://docs.getdbt.com/docs/building-a-dbt-project/projects#using-an-existing-project) on the dbt website.

For a general overview of dbt, watch the following YouTube video (26 minutes).

[Video](https://www.youtube.com/watch?v=zoHoIGE6tPc)

## <a id="partner-connect" />Connect to dbt Cloud using Partner Connect

This section describes how to connect a Databricks SQL warehouse to dbt Cloud using Partner Connect, then give dbt Cloud read access to your data.

### <a id="differences" />Differences between standard connections and dbt Cloud

To connect to dbt Cloud using Partner Connect, you follow the steps in [Connect to data prep partners using Partner Connect](https://docs.databricks.com/aws/en/partner-connect/prep.md). The dbt Cloud connection is different from standard data preparation and transformation connections in the following ways:

* In addition to a service principal and a personal access token, Partner Connect creates a SQL warehouse (formerly SQL endpoint) named **DBT\_CLOUD\_ENDPOINT** by default.

### <a id="partner-connect-steps" />Steps to connect

To connect to dbt Cloud using Partner Connect, do the following:

1. [Connect to data prep partners using Partner Connect](https://docs.databricks.com/aws/en/partner-connect/prep.md).
2. After you connect to dbt Cloud, your dbt Cloud dashboard appears. To explore your dbt Cloud project, in the menu bar, next to the dbt logo, select your dbt account name from the first drop-down if it is not displayed, and then select the **Databricks Partner Connect Trial** project from the second drop-down menu if it is not displayed.

   > [!TIP]
   >
   > To view your project's settings, click the “three stripes” or “hamburger” menu, click **Account Settings > Projects**, and click the name of the project. To view the connection settings, click the link next to **Connection**. To change any settings, click **Edit**.
   >
   > To view the Databricks personal access token information for this project, click the “person” icon on the menu bar, click **Profile > Credentials > Databricks Partner Connect Trial**, and click the name of the project. To make a change, click **Edit**.

### <a id="read-access" />Steps to give dbt Cloud read access to your data

Partner Connect gives create-only permission to the **DBT\_CLOUD\_USER** service principal only on the default catalog. Follow these steps in your Databricks workspace to give the **DBT\_CLOUD\_USER** service principal read access to the data that you choose.

> [!WARNING]
>
> You can adapt these steps to give dbt Cloud additional access across catalogs, databases, and tables within your workspace. However, as a security best practice, Databricks strongly recommends that you give access only to the individual tables that you need the **DBT\_CLOUD\_USER** service principal to work with and only read access to those tables.

1. Click ![Data icon.](https://docs.databricks.com/aws/en/images/product-icons/DataIcon.svg) **Catalog** in the sidebar.

2. Select the SQL warehouse (**DBT\_CLOUD\_ENDPOINT**) in the drop-down list at the top right.

   ![Select warehouse](https://docs.databricks.com/aws/en/images/sql/data-explorer/select-endpoint.png)

   1. Under **Catalog Explorer**, select the catalog that contains the database for your table.
   2. Select the database that contains your table.
   3. Select your table.

   > [!TIP]
   >
   > If you do not see your catalog, database, or table listed, enter any portion of the name in the **Select Catalog**, **Select Database**, or **Filter tables** boxes, respectively, to narrow down the list.
   >
   > ![Filter tables](https://docs.databricks.com/aws/en/images/sql/data-explorer/filter-tables.png)

3. Click **Permissions**.

4. Click **Grant**.

5. For **Type to add multiple users or groups**, select **DBT\_CLOUD\_USER**. This is the Databricks service principal that Partner Connect created for you in the previous section.

   > [!TIP]
   >
   > If you do not see **DBT\_CLOUD\_USER**, begin typing `DBT_CLOUD_USER` in the **Type to add multiple users or groups** box until it appears in the list, and then select it.

6. Grant read access only by selecting `SELECT` and `READ METADATA`.

7. Click **OK**.

Repeat steps 4-9 for each additional table that you want to give dbt Cloud read access to.

### <a id="troubleshoot-partner-connect" />Troubleshoot the dbt Cloud connection

If someone deletes the project in dbt Cloud for this account, and you the click the **dbt** tile, an error message appears, stating that the project cannot be found. To fix this, click **Delete connection**, and then start from the beginning of this procedure to create the connection again.

## <a id="manual-connection" />Connect to dbt Cloud manually

This section describes how to connect a Databricks cluster or a Databricks SQL warehouse in your Databricks workspace to dbt Cloud.

> [!IMPORTANT]
>
> Databricks recommends connecting to a SQL warehouse. If you don't have the Databricks SQL access entitlement, or if you want to run Python models, you can connect to a cluster instead.

### <a id="manual-requirements" />Requirements

* A cluster or SQL warehouse in your Databricks workspace.
  * [Compute configuration reference](https://docs.databricks.com/aws/en/compute/configure.md).
  * [Create a SQL warehouse](https://docs.databricks.com/aws/en/compute/sql-warehouse/create.md).
* The connection details for your cluster or SQL warehouse, specifically the **Server Hostname**, **Port**, and **HTTP Path** values.
  * [Get connection details for a Databricks compute resource](https://docs.databricks.com/aws/en/integrations/compute-details.md).
* A Databricks [personal access token](https://docs.databricks.com/aws/en/dev-tools/auth/pat.md). To create a personal access token, follow the steps in [Create personal access tokens for workspace users](https://docs.databricks.com/aws/en/dev-tools/auth/pat.md#pat-user).

  > [!NOTE]
  >
  > As a security best practice when you authenticate with automated tools, systems, scripts, and apps, Databricks recommends that you use [OAuth tokens](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m.md).
  >
  > If you use personal access token authentication, Databricks recommends using personal access tokens belonging to [service principals](https://docs.databricks.com/aws/en/admin/users-groups/service-principals.md) instead of workspace users. To create tokens for service principals, see [Manage tokens for a service principal](https://docs.databricks.com/aws/en/admin/users-groups/manage-service-principals.md#tokens).

- To connect dbt Cloud to data managed by Unity Catalog, dbt version 1.1 or above.

  The steps in this article create a new environment that uses the latest dbt version. For information about upgrading the dbt version for an existing environment, see [Upgrading to the latest version of dbt in Cloud](https://docs.getdbt.com/docs/dbt-versions/upgrade-core-in-cloud#upgrading-to-the-latest-version-of-dbt-in-cloud) in the dbt documentation.

### <a id="sign-up" />Step 1: Sign up for dbt Cloud

Go to [dbt Cloud - Signup](https://www.getdbt.com/signup/) and enter your email, name, and company information. Create a password and click **Create my account**.

### <a id="create-project" />Step 2: Create a dbt project

In this step, you create a dbt *project*, which contains a connection to a Databricks cluster or a SQL warehouse, a repository that contains your source code, and one or more environments (such as testing and production environments).

1. [Sign in to dbt Cloud](https://cloud.getdbt.com/login/).

2. Click the settings icon, and then click **Account Settings**.

3. Click **New Project**.

4. For **Name**, enter a unique name for your project, and then click **Continue**.

5. Select a Databricks compute connection from the **Choose a connection** drop-down menu or create a new connection:
   1. Click **Add new connection**.

      The **Add new connection** wizard opens in a new tab.

   2. Click **Databricks**, and then click **Next**.

      > [!NOTE]
      >
      > Databricks recommends using `dbt-databricks`, which supports Unity Catalog, instead of `dbt-spark`. By default, new projects use `dbt-databricks`. To migrate an existing project to `dbt-databricks`, see [Migrating from dbt-spark to dbt-databricks](https://docs.getdbt.com/guides/migration/tools/migrating-from-spark-to-databricks) in the dbt documentation.

   3. Under **Settings**, for **Server Hostname**, enter the server hostname value from the requirements.

   4. For **HTTP Path**, enter the HTTP path value from the requirements.

   5. If your workspace is Unity Catalog-enabled, under **Optional Settings**, enter the name of the catalog for dbt to use.

   6. Click **Save**.

   7. Return to the **New project** wizard and select the connection you just created from the **Connection** drop-down menu.

6. Under **Development Credentials**, for **Token**, enter the personal access token from the requirements.

7. For **Schema**, enter the name of the schema where you want dbt to create the tables and views.

8. Click **Test Connection**.

9. If the test completes successfully, click **Save**.

For more information, see [Connecting to Databricks ODBC](https://docs.getdbt.com/docs/dbt-cloud/cloud-configuring-dbt-cloud/connecting-your-database#connecting-to-databricks) on the dbt website.

> [!TIP]
>
> To view or change the settings for this project, or to delete the project altogether, click the settings icon, click **Account Settings > Projects**, and click the name of the project. To change the settings, click **Edit**. To delete the project, click **Edit > Delete Project**.
>
> To view or change your Databricks personal access token value for this project, click the “person” icon, click **Profile > Credentials**, and click the name of the project. To make a change, click **Edit**.

After you connect to a Databricks cluster or a Databricks SQL warehouse, follow the on-screen instructions to **Setup a Repository**, and then click **Continue**.

After you set up the repository, follow the on-screen instructions to invite users and then click **Complete**. Or click **Skip & Complete**.

## <a id="tutorial" />Tutorial

In this section, you use your dbt Cloud project to work with some sample data. This section assumes that you have already created your project and have the dbt Cloud IDE open to that project.

### <a id="create-model" />Step 1: Create and run models

In this step, you use the dbt Cloud IDE to create and run *models*, which are `select` statements that create either a new view (the default) or a new table in a database, based on existing data in that same database. This procedure creates a model based on the sample `diamonds` table from the [Sample datasets](https://docs.databricks.com/aws/en/discover/databricks-datasets.md).

> [!TIP]
>
> If your workspace is enabled for Unity Catalog with a serverless SQL warehouse, Databricks recommends materializing production models that must stay current as materialized views or streaming tables rather than as tables or views. These materializations refresh incrementally instead of recomputing the full result on every run. See [Step 4: Keep models fresh with materialized views and streaming tables](https://docs.databricks.com/aws/en/partners/prep/dbt-cloud.md#materialized-views).

Use the following code to create this table.

```sql
DROP TABLE IF EXISTS diamonds;

CREATE TABLE diamonds USING CSV OPTIONS (path "/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", header "true")
```

This procedure assumes this table has already been created in your workspace's `default` database.

1. With the project open, click **Develop** at the top of the UI.

2. Click **Initialize dbt project**.

3. Click **Commit and sync**, enter a commit message, and then click **Commit**.

4. Click **Create branch**, enter a name for your branch, and then click **Submit**.

5. Create the first model: Click **Create New File**.

6. In the text editor, enter the following SQL statement. This statement selects only the carat, cut, color, and clarity details for each diamond from the `diamonds` table. The `config` block instructs dbt to create a table in the database based on this statement.

   ```
   {{ config(
     materialized='table',
     file_format='delta'
   ) }}
   ```

   ```sql
   select carat, cut, color, clarity
   from diamonds
   ```

   > [!TIP]
   >
   > For additional `config` options such as the `merge` incremental strategy, see [Databricks configurations](https://docs.getdbt.com/reference/resource-configs/databricks-configs) in the dbt documentation.

7. Click **Save As**.

8. For the filename, enter `models/diamonds_four_cs.sql` and then click **Create**.

9. Create a second model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

10. In the text editor, enter the following SQL statement. This statement selects unique values from the `colors` column in the `diamonds_four_cs` table, sorting the results in alphabetical order first to last. Because there is no `config` block, this model instructs dbt to create a view in the database based on this statement.

    ```sql
    select distinct color
    from diamonds_four_cs
    sort by color asc
    ```

11. Click **Save As**.

12. For the filename, enter `models/diamonds_list_colors.sql`, and then click **Create**.

13. Create a third model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

14. In the text editor, enter the following SQL statement. This statement averages diamond prices by color, sorting the results by average price from highest to lowest. This model instructs dbt to create a view in the database based on this statement.

    ```sql
    select color, avg(price) as price
    from diamonds
    group by color
    order by price desc
    ```

15. Click **Save As**.

16. For the filename, enter `models/diamonds_prices.sql` and click **Create**.

17. Run the models: In the command line, run the `dbt run` command with the paths to the three preceding files. In the `default` database, dbt creates one table named `diamonds_four_cs` and two views named `diamonds_list_colors` and `diamonds_prices`. dbt gets these view and table names from their related `.sql` file names.

    ```bash
    dbt run --model models/diamonds_four_cs.sql models/diamonds_list_colors.sql models/diamonds_prices.sql
    ```

    ```console
    ...
    ... | 1 of 3 START table model default.diamonds_four_cs.................... [RUN]
    ... | 1 of 3 OK created table model default.diamonds_four_cs............... [OK ...]
    ... | 2 of 3 START view model default.diamonds_list_colors................. [RUN]
    ... | 2 of 3 OK created view model default.diamonds_list_colors............ [OK ...]
    ... | 3 of 3 START view model default.diamonds_prices...................... [RUN]
    ... | 3 of 3 OK created view model default.diamonds_prices................. [OK ...]
    ... |
    ... | Finished running 1 table model, 2 view models ...

    Completed successfully

    Done. PASS=3 WARN=0 ERROR=0 SKIP=0 TOTAL=3
    ```

18. Run the following SQL code to list information about the new views and to select all rows from the table and views.

    If you are connecting to a cluster, you can run this SQL code from a [notebook](https://docs.databricks.com/aws/en/notebooks/notebooks-manage.md#create-a-notebook) that is attached to the cluster, specifying SQL as the default language for the notebook. If you are connecting to a SQL warehouse, you can run this SQL code from a [query](https://docs.databricks.com/aws/en/sql/user/sql-editor/write-queries.md#create-a-query).

    ```sql
    SHOW views IN default
    ```

    ```console
    +-----------+----------------------+-------------+
    | namespace | viewName             | isTemporary |
    +===========+======================+=============+
    | default   | diamonds_list_colors | false       |
    +-----------+----------------------+-------------+
    | default   | diamonds_prices      | false       |
    +-----------+----------------------+-------------+
    ```

    ```sql
    SELECT * FROM diamonds_four_cs
    ```

    ```console
    +-------+---------+-------+---------+
    | carat | cut     | color | clarity |
    +=======+=========+=======+=========+
    | 0.23  | Ideal   | E     | SI2     |
    +-------+---------+-------+---------+
    | 0.21  | Premium | E     | SI1     |
    +-------+---------+-------+---------+
    ...
    ```

    ```sql
    SELECT * FROM diamonds_list_colors
    ```

    ```console
    +-------+
    | color |
    +=======+
    | D     |
    +-------+
    | E     |
    +-------+
    ...
    ```

    ```sql
    SELECT * FROM diamonds_prices
    ```

    ```console
    +-------+---------+
    | color | price   |
    +=======+=========+
    | J     | 5323.82 |
    +-------+---------+
    | I     | 5091.87 |
    +-------+---------+
    ...
    ```

### <a id="complex-models" />Step 2: Create and run more complex models

In this step, you create more complex models for a set of related data tables. These data tables contain information about a fictional sports league of three teams playing a season of six games. This procedure creates the data tables, creates the models, and runs the models.

1. Run the following SQL code to create the necessary data tables.

   If you are connecting to a cluster, you can run this SQL code from a [notebook](https://docs.databricks.com/aws/en/notebooks/notebooks-manage.md#create-a-notebook) that is attached to the cluster, specifying SQL as the default language for the notebook. If you are connecting to a SQL warehouse, you can run this SQL code from a [query](https://docs.databricks.com/aws/en/sql/user/sql-editor/write-queries.md#create-a-query).

   The tables and views in this step start with `zzz_` to help identify them as part of this example. You do not need to follow this pattern for your own tables and views.

   ```sql
   DROP TABLE IF EXISTS zzz_game_opponents;
   DROP TABLE IF EXISTS zzz_game_scores;
   DROP TABLE IF EXISTS zzz_games;
   DROP TABLE IF EXISTS zzz_teams;

   CREATE TABLE zzz_game_opponents (
   game_id INT,
   home_team_id INT,
   visitor_team_id INT
   ) USING DELTA;

   INSERT INTO zzz_game_opponents VALUES (1, 1, 2);
   INSERT INTO zzz_game_opponents VALUES (2, 1, 3);
   INSERT INTO zzz_game_opponents VALUES (3, 2, 1);
   INSERT INTO zzz_game_opponents VALUES (4, 2, 3);
   INSERT INTO zzz_game_opponents VALUES (5, 3, 1);
   INSERT INTO zzz_game_opponents VALUES (6, 3, 2);

   -- Result:
   -- +---------+--------------+-----------------+
   -- | game_id | home_team_id | visitor_team_id |
   -- +=========+==============+=================+
   -- | 1       | 1            | 2               |
   -- +---------+--------------+-----------------+
   -- | 2       | 1            | 3               |
   -- +---------+--------------+-----------------+
   -- | 3       | 2            | 1               |
   -- +---------+--------------+-----------------+
   -- | 4       | 2            | 3               |
   -- +---------+--------------+-----------------+
   -- | 5       | 3            | 1               |
   -- +---------+--------------+-----------------+
   -- | 6       | 3            | 2               |
   -- +---------+--------------+-----------------+

   CREATE TABLE zzz_game_scores (
   game_id INT,
   home_team_score INT,
   visitor_team_score INT
   ) USING DELTA;

   INSERT INTO zzz_game_scores VALUES (1, 4, 2);
   INSERT INTO zzz_game_scores VALUES (2, 0, 1);
   INSERT INTO zzz_game_scores VALUES (3, 1, 2);
   INSERT INTO zzz_game_scores VALUES (4, 3, 2);
   INSERT INTO zzz_game_scores VALUES (5, 3, 0);
   INSERT INTO zzz_game_scores VALUES (6, 3, 1);

   -- Result:
   -- +---------+-----------------+--------------------+
   -- | game_id | home_team_score | visitor_team_score |
   -- +=========+=================+====================+
   -- | 1       | 4               | 2                  |
   -- +---------+-----------------+--------------------+
   -- | 2       | 0               | 1                  |
   -- +---------+-----------------+--------------------+
   -- | 3       | 1               | 2                  |
   -- +---------+-----------------+--------------------+
   -- | 4       | 3               | 2                  |
   -- +---------+-----------------+--------------------+
   -- | 5       | 3               | 0                  |
   -- +---------+-----------------+--------------------+
   -- | 6       | 3               | 1                  |
   -- +---------+-----------------+--------------------+

   CREATE TABLE zzz_games (
   game_id INT,
   game_date DATE
   ) USING DELTA;

   INSERT INTO zzz_games VALUES (1, '2020-12-12');
   INSERT INTO zzz_games VALUES (2, '2021-01-09');
   INSERT INTO zzz_games VALUES (3, '2020-12-19');
   INSERT INTO zzz_games VALUES (4, '2021-01-16');
   INSERT INTO zzz_games VALUES (5, '2021-01-23');
   INSERT INTO zzz_games VALUES (6, '2021-02-06');

   -- Result:
   -- +---------+------------+
   -- | game_id | game_date  |
   -- +=========+============+
   -- | 1       | 2020-12-12 |
   -- +---------+------------+
   -- | 2       | 2021-01-09 |
   -- +---------+------------+
   -- | 3       | 2020-12-19 |
   -- +---------+------------+
   -- | 4       | 2021-01-16 |
   -- +---------+------------+
   -- | 5       | 2021-01-23 |
   -- +---------+------------+
   -- | 6       | 2021-02-06 |
   -- +---------+------------+

   CREATE TABLE zzz_teams (
   team_id INT,
   team_city VARCHAR(15)
   ) USING DELTA;

   INSERT INTO zzz_teams VALUES (1, "San Francisco");
   INSERT INTO zzz_teams VALUES (2, "Seattle");
   INSERT INTO zzz_teams VALUES (3, "Amsterdam");

   -- Result:
   -- +---------+---------------+
   -- | team_id | team_city     |
   -- +=========+===============+
   -- | 1       | San Francisco |
   -- +---------+---------------+
   -- | 2       | Seattle       |
   -- +---------+---------------+
   -- | 3       | Amsterdam     |
   -- +---------+---------------+
   ```

2. Create the first model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

3. In the text editor, enter the following SQL statement. This statement creates a table that provides the details of each game, such as team names and scores. The `config` block instructs dbt to create a table in the database based on this statement.

   ```sql
   -- Create a table that provides full details for each game, including
   -- the game ID, the home and visiting teams' city names and scores,
   -- the game winner's city name, and the game date.
   ```

   ```
   {{ config(
     materialized='table',
     file_format='delta'
   ) }}
   ```

   ```sql
   -- Step 4 of 4: Replace the visitor team IDs with their city names.
   select
     game_id,
     home,
     t.team_city as visitor,
     home_score,
     visitor_score,
     -- Step 3 of 4: Display the city name for each game's winner.
     case
       when
         home_score > visitor_score
           then
             home
       when
         visitor_score > home_score
           then
             t.team_city
     end as winner,
     game_date as date
   from (
     -- Step 2 of 4: Replace the home team IDs with their actual city names.
     select
       game_id,
       t.team_city as home,
       home_score,
       visitor_team_id,
       visitor_score,
       game_date
     from (
       -- Step 1 of 4: Combine data from various tables (for example, game and team IDs, scores, dates).
       select
         g.game_id,
         go.home_team_id,
         gs.home_team_score as home_score,
         go.visitor_team_id,
         gs.visitor_team_score as visitor_score,
         g.game_date
       from
         zzz_games as g,
         zzz_game_opponents as go,
         zzz_game_scores as gs
       where
         g.game_id = go.game_id and
         g.game_id = gs.game_id
     ) as all_ids,
       zzz_teams as t
     where
       all_ids.home_team_id = t.team_id
   ) as visitor_ids,
     zzz_teams as t
   where
     visitor_ids.visitor_team_id = t.team_id
   order by game_date desc
   ```

4. Click **Save As**.

5. For the filename, enter `models/zzz_game_details.sql` and then click **Create**.

6. Create a second model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

7. In the text editor, enter the following SQL statement. This statement creates a view that lists team win-loss records for the season.

   ```sql
   -- Create a view that summarizes the season's win and loss records by team.

   -- Step 2 of 2: Calculate the number of wins and losses for each team.
   select
     winner as team,
     count(winner) as wins,
     -- Each team played in 4 games.
     (4 - count(winner)) as losses
   from (
     -- Step 1 of 2: Determine the winner and loser for each game.
     select
       game_id,
       winner,
       case
         when
           home = winner
             then
               visitor
         else
           home
       end as loser
     from zzz_game_details
   )
   group by winner
   order by wins desc
   ```

8. Click **Save As**.

9. For the filename, enter `models/zzz_win_loss_records.sql` and then click **Create**.

10. Run the models: In the command line, run the `dbt run` command with the paths to the two preceding files. In the `default` database (as specified in your project settings), dbt creates one table named `zzz_game_details` and one view named `zzz_win_loss_records`. dbt gets these view and table names from their related `.sql` file names.

    ```bash
    dbt run --model models/zzz_game_details.sql models/zzz_win_loss_records.sql
    ```

    ```console
    ...
    ... | 1 of 2 START table model default.zzz_game_details.................... [RUN]
    ... | 1 of 2 OK created table model default.zzz_game_details............... [OK ...]
    ... | 2 of 2 START view model default.zzz_win_loss_records................. [RUN]
    ... | 2 of 2 OK created view model default.zzz_win_loss_records............ [OK ...]
    ... |
    ... | Finished running 1 table model, 1 view model ...

    Completed successfully

    Done. PASS=2 WARN=0 ERROR=0 SKIP=0 TOTAL=2
    ```

11. Run the following SQL code to list information about the new view and to select all rows from the table and view.

    If you are connecting to a cluster, you can run this SQL code from a [notebook](https://docs.databricks.com/aws/en/notebooks/notebooks-manage.md#create-a-notebook) that is attached to the cluster, specifying SQL as the default language for the notebook. If you are connecting to a SQL warehouse, you can run this SQL code from a [query](https://docs.databricks.com/aws/en/sql/user/sql-editor/write-queries.md#create-a-query).

    ```sql
    SHOW VIEWS FROM default LIKE 'zzz_win_loss_records';
    ```

    ```console
    +-----------+----------------------+-------------+
    | namespace | viewName             | isTemporary |
    +===========+======================+=============+
    | default   | zzz_win_loss_records | false       |
    +-----------+----------------------+-------------+
    ```

    ```sql
    SELECT * FROM zzz_game_details;
    ```

    ```console
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | game_id | home          | visitor       | home_score | visitor_score | winner        | date       |
    +=========+===============+===============+============+===============+===============+============+
    | 1       | San Francisco | Seattle       | 4          | 2             | San Francisco | 2020-12-12 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | 2       | San Francisco | Amsterdam     | 0          | 1             | Amsterdam     | 2021-01-09 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | 3       | Seattle       | San Francisco | 1          | 2             | San Francisco | 2020-12-19 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | 4       | Seattle       | Amsterdam     | 3          | 2             | Seattle       | 2021-01-16 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | 5       | Amsterdam     | San Francisco | 3          | 0             | Amsterdam     | 2021-01-23 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    | 6       | Amsterdam     | Seattle       | 3          | 1             | Amsterdam     | 2021-02-06 |
    +---------+---------------+---------------+------------+---------------+---------------+------------+
    ```

    ```sql
    SELECT * FROM zzz_win_loss_records;
    ```

    ```console
    +---------------+------+--------+
    | team          | wins | losses |
    +===============+======+========+
    | Amsterdam     | 3    | 1      |
    +---------------+------+--------+
    | San Francisco | 2    | 2      |
    +---------------+------+--------+
    | Seattle       | 1    | 3      |
    +---------------+------+--------+
    ```

### <a id="tests" />Step 3: Create and run tests

In this step, you create *tests*, which are assertions you make about your models. When you run these tests, dbt tells you if each test in your project passes or fails.

There are two type of tests. *Schema tests*, written in YAML, return the number of records that do not pass an assertion. When this number is zero, all records pass, therefore the tests pass. *Data tests* are specific queries that must return zero records to pass.

1. Create the schema tests: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

2. In the text editor, enter the following content. This file includes schema tests that determine whether the specified columns have unique values, are not null, have only the specified values, or a combination.

   ```yaml
   version: 2

   models:
     - name: zzz_game_details
       columns:
         - name: game_id
           tests:
             - unique
             - not_null
         - name: home
           tests:
             - not_null
             - accepted_values:
                 values: ['Amsterdam', 'San Francisco', 'Seattle']
         - name: visitor
           tests:
             - not_null
             - accepted_values:
                 values: ['Amsterdam', 'San Francisco', 'Seattle']
         - name: home_score
           tests:
             - not_null
         - name: visitor_score
           tests:
             - not_null
         - name: winner
           tests:
             - not_null
             - accepted_values:
                 values: ['Amsterdam', 'San Francisco', 'Seattle']
         - name: date
           tests:
             - not_null
     - name: zzz_win_loss_records
       columns:
         - name: team
           tests:
             - unique
             - not_null
             - relationships:
                 to: ref('zzz_game_details')
                 field: home
         - name: wins
           tests:
             - not_null
         - name: losses
           tests:
             - not_null
   ```

3. Click **Save As**.

4. For the filename, enter `models/schema.yml`, and then click **Create**.

5. Create the first data test: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

6. In the text editor, enter the following SQL statement. This file includes a data test to determine whether any games happened outside of the regular season.

   ```sql
   -- This season's games happened between 2020-12-12 and 2021-02-06.
   -- For this test to pass, this query must return no results.

   select date
   from zzz_game_details
   where date < '2020-12-12'
   or date > '2021-02-06'
   ```

7. Click **Save As**.

8. For the filename, enter `tests/zzz_game_details_check_dates.sql`, and then click **Create**.

9. Create a second data test: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

10. In the text editor, enter the following SQL statement. This file includes a data test to determine whether any scores were negative or any games were tied.

    ```sql
    -- This sport allows no negative scores or tie games.
    -- For this test to pass, this query must return no results.

    select home_score, visitor_score
    from zzz_game_details
    where home_score < 0
    or visitor_score < 0
    or home_score = visitor_score
    ```

11. Click **Save As**.

12. For the filename, enter `tests/zzz_game_details_check_scores.sql`, and then click **Create**.

13. Create a third data test: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

14. In the text editor, enter the following SQL statement. This file includes a data test to determine whether any teams had negative win or loss records, had more win or loss records than games played, or played more games than were allowed.

    ```sql
    -- Each team participated in 4 games this season.
    -- For this test to pass, this query must return no results.

    select wins, losses
    from zzz_win_loss_records
    where wins < 0 or wins > 4
    or losses < 0 or losses > 4
    or (wins + losses) > 4
    ```

15. Click **Save As**.

16. For the filename, enter `tests/zzz_win_loss_records_check_records.sql`, and then click **Create**.

17. Run the tests: In the command line, run the `dbt test` command.

### <a id="materialized-views" />Step 4: Keep models fresh with materialized views and streaming tables

When a model must stay current as new data arrives, materialize it as a materialized view or a streaming table instead of a table or view. A materialized view incrementally refreshes the results of its query, so Databricks updates only what changed instead of recomputing the entire result on each run, which makes materialized views a good fit for aggregations and data served to dashboards. A streaming table incrementally ingests append-only or streaming source data, such as files that arrive in cloud storage, without reprocessing rows it has already read. Both are backed by Lakeflow pipelines and are the recommended materializations for production transformations that must stay up to date.

> [!NOTE]
>
> This step requires a workspace that is enabled for Unity Catalog with a serverless SQL warehouse. The `materialized_view` materialization is built into dbt, while `streaming_table` is provided by the `dbt-databricks` adapter.

1. Create the materialized view model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

2. In the text editor, enter the following SQL statement. This is the same aggregation as the `diamonds_prices` view, but the `config` block instructs dbt to create a materialized view. Unlike the view, which recomputes on every query, the materialized view precomputes the result and refreshes it incrementally.

   ```
   {{ config(
     materialized='materialized_view'
   ) }}
   ```

   ```sql
   select color, avg(price) as price
   from diamonds
   group by color
   order by price desc
   ```

3. Click **Save As**.

4. For the filename, enter `models/diamonds_prices_mv.sql` and then click **Create**.

5. Create the streaming table model: Click ![Create New File icon](https://docs.databricks.com/aws/en/images/third-party-integrations/dbt-cloud-create-new-file.png) (**Create New File**) in the upper-right corner.

6. In the text editor, enter the following SQL statement. The `config` block instructs dbt to create a streaming table that incrementally ingests the source `diamonds` CSV file. The `read_files` table-valued function reads the file, and the `STREAM` keyword processes only newly arrived data on each refresh.

   ```
   {{ config(
     materialized='streaming_table'
   ) }}
   ```

   ```sql
   select * from stream read_files(
     '/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv',
     format => 'csv',
     header => true
   )
   ```

7. Click **Save As**.

8. For the filename, enter `models/diamonds_raw_stream.sql` and then click **Create**.

9. Run the models: In the command line, run the `dbt run` command with the paths to the two preceding files.

   ```bash
   dbt run --model models/diamonds_prices_mv.sql models/diamonds_raw_stream.sql
   ```

Keep the following behaviors in mind when you update these models:

* Changing the query of a streaming table doesn't reprocess data that was already ingested. dbt uses `CREATE OR REFRESH`, which applies the updated query to future rows only. To reprocess the available source data, run with `--full-refresh`.
* Changing the configuration of a materialized view requires dbt to drop and recreate it, except for schedule changes.
* Tags that you set with `databricks_tags` can't be removed through dbt after they're applied. To remove a tag, use Databricks directly or a post-hook.

For the full list of supported configurations, such as scheduled refreshes, partitioning, and row filters, see [Materialized views and streaming tables](https://docs.getdbt.com/reference/resource-configs/databricks-configs#materialized-views-and-streaming-tables) in the dbt documentation.

### <a id="clean-up" />Step 5: Clean up

You can delete the tables and views you created for this example by running the following SQL code.

If you are connecting to a cluster, you can run this SQL code from a [notebook](https://docs.databricks.com/aws/en/notebooks/notebooks-manage.md#create-a-notebook) that is attached to the cluster, specifying SQL as the default language for the notebook. If you are connecting to a SQL warehouse, you can run this SQL code from a [query](https://docs.databricks.com/aws/en/sql/user/sql-editor/write-queries.md#create-a-query).

```sql
DROP TABLE zzz_game_opponents;
DROP TABLE zzz_game_scores;
DROP TABLE zzz_games;
DROP TABLE zzz_teams;
DROP TABLE zzz_game_details;
DROP VIEW zzz_win_loss_records;

DROP MATERIALIZED VIEW diamonds_prices_mv;
DROP TABLE diamonds_raw_stream;
DROP TABLE diamonds;
DROP TABLE diamonds_four_cs;
DROP VIEW diamonds_list_colors;
DROP VIEW diamonds_prices;
```

> [!NOTE]
>
> If you didn't complete [Step 4](https://docs.databricks.com/aws/en/partners/prep/dbt-cloud.md#materialized-views), omit the `DROP MATERIALIZED VIEW diamonds_prices_mv` and `DROP TABLE diamonds_raw_stream` statements.

## <a id="next-steps" />Next steps

* Learn more about dbt [models](https://docs.getdbt.com/docs/building-a-dbt-project/building-models).
* Learn how to [test](https://docs.getdbt.com/docs/building-a-dbt-project/tests) your dbt projects.
* Learn how to use [Jinja](https://docs.getdbt.com/docs/building-a-dbt-project/jinja-macros), a templating language, for programming SQL in your dbt projects.
* Learn about dbt [best practices](https://docs.getdbt.com/docs/guides/best-practices).
* Learn more about the materializations that keep your data fresh. See [Use standalone materialized views](https://docs.databricks.com/aws/en/sql/mv-st/materialized.md) and [Use standalone streaming tables](https://docs.databricks.com/aws/en/sql/mv-st/streaming.md).

## <a id="additional-resources" />Additional resources

* [What, exactly, is dbt?](https://www.getdbt.com/blog/what-exactly-is-dbt)
* [General dbt documentation](https://docs.getdbt.com/docs/introduction)
* [Databricks configurations, including materialized views and streaming tables](https://docs.getdbt.com/reference/resource-configs/databricks-configs#materialized-views-and-streaming-tables)
* [dbt-core GitHub repository](https://github.com/dbt-labs/dbt)
* [dbt CLI](https://docs.getdbt.com/dbt-cli/cli-overview)
* [dbt pricing](https://www.getdbt.com/pricing/)
* [Analytics Engineering for Everyone: Databricks in dbt Cloud](https://blog.getdbt.com/analytics-engineering-for-everyone-databricks-in-dbt-cloud/)
* [dbt Cloud overview](https://docs.getdbt.com/docs/dbt-cloud/cloud-overview)
* [Connecting to Databricks](https://docs.getdbt.com/docs/dbt-cloud/cloud-configuring-dbt-cloud/connecting-your-database#connecting-to-databricks)
* [dbt blog](https://blog.getdbt.com/)
* [Support](https://docs.getdbt.com/docs/dbt-cloud/cloud-dbt-cloud-support)
