sql-analytics-and-dbt
БесплатноБез исполняемых скриптовНе проверенUse when writing or changing analytical SQL or a dbt model — CTE structure, window functions, grain and join correctness, dbt data tests, unit tests…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
SQL Analytics and dbt
Overview
Analytical SQL fails quietly: a join that fans out, a NULL that drops rows from a NOT IN, a running total over the wrong frame. The query runs, the dashboard shows a number, the number is wrong. dbt gives you the tools to make SQL testable — use them the way you use pytest.
Core principle: every model declares its grain and tests it; logic is proven with a dbt unit test before it is trusted with a real table.
1. Detect the project's conventions
Read dbt_project.yml, packages.yml (is dbt_utils installed?), the adapter in profiles.yml or CI (Postgres, Snowflake, BigQuery, Databricks, DuckDB), any .sqlfluff config, and the existing folder and naming scheme (staging/stg_<source>__<entity>, intermediate/, marts/fct_*, dim_*). Follow them. SQLMesh projects follow SQLMesh's own model and audit conventions — never mix the two.
2. Model structure
with
orders as (
select * from {{ ref('stg_shop__orders') }}
),
order_lines as (
select * from {{ ref('stg_shop__order_lines') }}
),
line_totals as (
select
order_id,
sum(amount) as order_value,
count(*) as line_count
from order_lines
where status != 'cancelled'
group by order_id
),
final as (
select
orders.order_id,
orders.customer_id,
orders.ordered_at,
coalesce(line_totals.order_value, 0) as order_value,
coalesce(line_totals.line_count, 0) as line_count
from orders
left join line_totals using (order_id)
)
select * from final
ref()andsource()only — never a hard-codedschema.table.- Aggregate to the join key before joining (
line_totals), so the join stays one-to-one. - One transformation per CTE, named for what it holds; explicit column lists in the final select.
3. Window functions without surprises
-- latest row per key, deterministic tie-break
select *
from events
qualify row_number() over (partition by event_id order by loaded_at desc, _row_id desc) = 1
-- running total: say ROWS, or ties on order_date are summed together
sum(amount) over (
partition by customer_id
order by order_date, order_id
rows between unbounded preceding and current row
) as running_spend
-- previous value
lag(order_date) over (partition by customer_id order by order_date, order_id) as previous_order_date
QUALIFY exists in Snowflake, BigQuery, Databricks and DuckDB; elsewhere filter row_number() = 1 in an outer query. A window ORDER BY without a unique tie-breaker gives a different "latest row" on each run.
4. SQL pitfalls checklist
| Pitfall | Fix |
|---|---|
x not in (select y ...) where y can be NULL returns no rows |
not exists (...) |
Integer division (1 / 2 = 0 in Postgres, Redshift, SQL Server) |
cast one side to numeric/float |
| Division by zero | x / nullif(y, 0) |
between on timestamps includes the end instant |
half-open: >= start and < end |
Filter on the right table of a LEFT JOIN in WHERE turns it into an inner join |
move the condition into ON |
count(col) skips NULLs, count(*) does not |
choose deliberately; count(distinct key) for entities through joins |
select distinct masking a fan-out |
fix the join grain instead |
| Date truncation in local time vs UTC | convert to one timezone first, state which |
| Average of per-group averages | aggregate from rows, or weight by group size |
union silently deduplicating |
union all unless dedup is intended |
5. Tests: grain, relationships, contracts
models:
- name: fct_orders
config:
contract:
enforced: true
columns:
- name: order_id
data_type: varchar
constraints:
- type: not_null
data_tests:
- unique
- not_null
- name: customer_id
data_type: varchar
data_tests:
- relationships:
to: ref('dim_customers')
field: customer_id
- name: order_value
data_type: numeric
- Every model:
unique+not_nullon its key. A composite key usesdbt_utils.unique_combination_of_columnswhen the repo has dbt_utils, otherwise a surrogate key column with the two tests. - Enforced contracts on marts that other teams or dashboards consume: a column rename or type change fails the build instead of the dashboard.
- Newer dbt versions accept generic-test arguments nested under
arguments:— write tests in the form the repository's YAML already uses.
6. dbt unit tests — TDD for SQL (dbt 1.8+)
unit_tests:
- name: fct_orders_excludes_cancelled_lines
model: fct_orders
given:
- input: ref('stg_shop__orders')
rows:
- {order_id: o1, customer_id: c1, ordered_at: '2026-01-05'}
- {order_id: o2, customer_id: c1, ordered_at: '2026-01-06'}
- input: ref('stg_shop__order_lines')
rows:
- {order_id: o1, amount: 10, status: ok}
Установить sql-analytics-and-dbt в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл sql-analytics-and-dbt?
Use when writing or changing analytical SQL or a dbt model — CTE structure, window functions, grain and join correctness, dbt data tests, unit tests, contracts and incremental models, and how to run them
Как установить скилл sql-analytics-and-dbt?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл sql-analytics-and-dbt запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic