From scripts to models: source(), ref() and the graph
A model is just a SELECT. Two functions wire everything together.
How Alice worked before dbt
Until now, Alice's job lived in a Snowflake worksheet (the web UI's SQL editor): a few hundred lines of CREATE OR REPLACE TABLE ... AS SELECT blocks. She'd highlight a block, hit run, wait, highlight the next one. The order mattered, and it lived only in her head: run the customers block before the orders block, or the join returns nothing.
It worked the way a house of cards works. When marketing wanted the same numbers filtered differently, she copied the script, and now there were two. Nobody could tell which version was real, the tables were called orders_final and orders_final_v2, and the day she was ill, nobody could refresh anything.
The worksheet
The dbt project
SELECT, the filename is the table.dbt run builds the whole thing in the right order.The rest of this lesson is the mechanics of that move: a model instead of a script, source() instead of a hardcoded raw table name, and ref() instead of remembering what to run first.
A model is a SELECT
Every model is a .sql file with one SELECT in it. dbt wraps it in the DDL, runs it, and creates a Snowflake object named after the file. By default that object is a view; step 4 shows how to make it a table. That is the whole concept.
Alice's raw orders table is messy: amounts in cents, statuses with stray spaces, a timestamp where she wants a date. She writes a model to clean it:
-- models/staging/ SELECT order_id, customer_id, amount_cents / 100.0 AS amount_eur, lower(trim(status)) AS status, created_at::date AS order_date -- :: is Snowflake's short CAST FROM {{ source(stg_ orders. sql 'raw', 'orders') }}
The {{ ... }} part is Jinja, a template language dbt runs before Snowflake sees anything. {{ ... }} prints a value into the SQL (here, the raw table's full name). {% ... %} runs logic, like an if, and prints nothing. {# ... #} is a comment that vanishes. So the file only becomes valid SQL once dbt compiles it. Step 5 (macros) shows the rest.
No semicolon at the end: dbt wraps your SELECT in its own statement, and a stray ; can break it.
source(): point at raw tables
First, where dbt sits. dbt is an ELT tool, and it only does the T. An ingestion tool like Fivetran or Airbyte does Extract and Load: it copies raw data into Snowflake as-is. Then dbt Transforms it, in place, with SQL.
So dbt doesn't build the raw tables. You declare them once in a .yml file and read them with source(). (Models you build use ref(), below.) If the raw table moves, you fix one line. dbt can also draw it on the graph (below) and check it's still fresh.
# models/staging/ sources: - name: raw # a label you pick, not a schema database: RAW_DB # where the tables really are schema: PUBLIC tables: - name: orders - name: customers_ sources. yml
source('raw', 'orders') compiles to RAW_DB.PUBLIC.ORDERS, the real table. The pictures' raw.orders is shorthand for it. dbt reads every .yml under models/, whatever its name; the leading _ just sorts it first.
RAW_DB yet. Run this once in a worksheet for two tiny raw tables:USE ROLE ACCOUNTADMIN; CREATE DATABASE IF NOT EXISTS RAW_DB; CREATE OR REPLACE TABLE RAW_DB. (order_id INT, customer_id INT, amount_cents INT, status STRING, created_at TIMESTAMP); INSERT INTO RAW_PUBLIC. ORDERS DB. (1, 10, 1000, 'PAID ', '2024-05-25 08:13:00'), (2, 11, 2700, 'pending', '2024-05-25 19:42:00'); CREATE OR REPLACE TABLE RAW_PUBLIC. ORDERS VALUES DB. INSERT INTO RAW_PUBLIC. CUSTOMERS (customer_id INT, name STRING, country STRING); DB. GRANT USAGE ON DATABASE RAW_DB TO ROLE USERLAND_PUBLIC. CUSTOMERS VALUES (10, 'Marco', 'IT'), (11, 'Lea', 'FR'); ROLE; GRANT USAGE ON SCHEMA RAW_DB. GRANT SELECT ON ALL TABLES IN SCHEMA RAW_PUBLIC TO ROLE USERLAND_ ROLE; DB. PUBLIC TO ROLE USERLAND_ ROLE;
What goes in the .yml files
Two kinds of YAML sit next to your SQL, and each answers a different question:
_sources.yml, "where does raw data live?" The sourcename, the realdatabaseandschema, the list oftables. Optionally afreshnessblock, whichdbt source freshnesschecks (step 7)._models.yml, "what do my models promise?" For each model: adescription, itscolumns, thedata_testson those columns, and an owner undermeta.
# models/staging/ models: - name: stg_orders description: "One row per order, amounts in EUR, statuses normalised." config: meta: # under config: since dbt 1.10 owner: team-finance columns: - name: order_id description: "Primary key." data_tests: [unique, not_null] # called tests: before dbt 1.8 - name: status description: "Lowercase, trimmed order status."_ models. yml
An entry is optional: dbt builds a model without one, but then it has no description and no tests. Tests run with dbt test, not dbt run, and a failing one prints how many bad rows it found. YAML tests are the reusable kind; one-off SQL checks go in tests/ (both in step 7).
So _sources.yml describes the raw tables you read (someone else made them), and _models.yml the models you build (you promise what they contain). A third file joins them later:
_sources.ymlloaded_at_field, freshness: warn_after 24h_models.ymldata_tests: [unique, not_null], descriptions_exposures.ymldepends_on: ref('fct_orders'), an ownerWrite the YAML with the model, not in a cleanup sprint. The descriptions become the docs site (dbt docs generate, step 9), the tests the safety net, and meta.owner what the dbt-score linter checks (step 12).
dbt compile --select stg_orders and open target/compiled/my_project/models/staging/stg_orders.sql . Every ref(), source() and macro is resolved into plain SQL you can paste into Snowflake. target/ is dbt's scratch folder, rebuilt on every command and kept out of Git. When a model misbehaves, look there first.ref(): wire models together
When one model builds on another, reference it with ref(), never a hardcoded name. Here's what that one function actually does:
- At compile time, it becomes the real table name.
{{ ref('stg_orders') }}turns intoUSERLAND.DBT_ALICE.STG_ORDERSwhen Alice runs it andPROD_DB.STAGING.STG_ORDERSwhen Airflow runs production. (WhySTAGING? Step 4 gives each layer its own schema, and step 14 sets the final names.) Same SQL, right table everywhere. - It declares a dependency. Before running anything, dbt reads every
ref()andsource()in the project and draws the dependency graph, the DAG. - The graph decides the build order. dbt runs parents before children, in parallel where possible. You never write "run this first, then that": the refs already say it.
fct_orders needs the customers too, so Alice adds their staging model first:
-- models/staging/ SELECT customer_id, name AS customer_stg_ customers. sql name, country FROM {{ source('raw', 'customers') }}
-- models/marts/ SELECT o.order_id, o.fct_ orders. sql amount_ FROM {{ ref(eur, c.country 'stg_ o JOIN {{ ref(orders') }} 'stg_ c USING (customers') }} customer_ id)
As a project grows, a join like this often moves into an intermediate model (step 3), and the graph dbt draws looks like this:
raw.ordersraw.customerssource()stg_ordersstg_customersref()int_orders_enrichedref()fct_ordersYou never maintain that graph: dbt builds it from your ref() and source() calls. Rename a model and forget one ref, and the run fails loudly instead of building against a ghost.
Build it: dbt run and --select
# build every model dbt run # stg_orders and everything downstream of it (the + is on the right) dbt run --select stg_orders+ # stg_orders and everything upstream it needs (the + is on the left) dbt run --select +stg_orders # run the data tests (dbt build runs everything, tests included) dbt test
dbt run prints a line per model (OK created sql view model dbt_alice.stg_orders) and a summary that should show ERROR=0. In Snowsight, your views are under USERLAND → DBT_ALICE.
The naming convention that maps to the layers
Each layer has a prefix, and the prefix tells you what a model is before you even open it. This is the convention the rest of the guide leans on, and the one dbt-score will later enforce automatically:
source().Next step: what each layer is really for, and how to shape the marts so the business questions have answers.

