SQL Dojo
Modeling

Semantic layer: define a metric once

A semantic layer stores each metric's definition once, with its joins and filters, so dashboards and AI agents ask for it by name and get one number.

Ask "what was revenue in 2025?" and one shop's data gives seven defensible answers, 15 % apart: cancelled orders kept or not, discounts, payments joined. A semantic layer stores the one definition: entities (keys, and which way each join goes), dimensions, measures and metrics. Dashboards and agents ask for revenue by name; the layer writes the SQL.

semantic_model:
  name: fct_order_lines   # one row per order line
  entities: [{ name: order_line, type: primary }, { name: customer, type: foreign }]
  dimensions: [{ name: ordered_at, type: time }]
metrics:
  - { name: revenue, agg: sum, expr: quantity * unit_price, filter: status <> 'cancelled' }

Asked for revenue by month, it writes:

SELECT DATE_TRUNC('month', ordered_at) AS month, SUM(quantity * unit_price) AS revenue
FROM fct_order_lines
WHERE status <> 'cancelled'
GROUP BY DATE_TRUNC('month', ordered_at);

The trap. Going around the layer. A dashboard that rewrites the filter in its own WHERE, or an agent that joins payments "to keep the paid orders", brings the seven numbers back: an order paid in two parts counts each of its lines twice. Send every consumer to the metrics, and declare joins many to one only, so the layer refuses a path that fans out instead of guessing.

On your warehouse. dbt's semantic layer (MetricFlow, open source) declares it in YAML, under each model in its 2026 spec; Snowflake keeps it in semantic views, Databricks in metric views queried with MEASURE(revenue); the Open Semantic Interchange works on a shared format. The spellings change fast; entities, dimensions, measures and metrics stay.

WITH lines AS (
  SELECT o.order_id, o.status, l.quantity * l.unit_price AS amount
  FROM orders o
  JOIN order_lines l ON l.order_id = o.order_id
  WHERE o.ordered_at >= DATE '2025-01-01' AND o.ordered_at < DATE '2026-01-01')
SELECT
  (SELECT SUM(amount) FROM lines) AS every_status,
  (SELECT SUM(x.amount) FROM lines x JOIN payments p ON p.order_id = x.order_id
   WHERE x.status <> 'cancelled') AS payments_joined,
  (SELECT SUM(amount) FROM lines WHERE status <> 'cancelled') AS the_definition;
every_statuspayments_joinedthe_definition
83242.3085384.4078934.40
Try it in Randori