Skip to content

Analytics engineering

Check the grain of a table, read type 2 history, build a date spine and do as-of joins to the latest value before a date.

Practise: 20 questions

When you need it

Analytics engineer screens ask about the shape of data, not just the answers. "Is order id unique in this table?", "what tier was the customer on the day of the order?", "show every day, even days with no sales", "convert each order to USD using the rate on that day". Words that signal it: "grain", "history", "as of", "valid from", "spine", "every day", "latest before".

The job is to make the table's grain explicit, then join other tables to it without changing the grain.

The shape of the query

Checking grain:

select count(*) as rows_total, count(distinct order_id) as distinct_orders
from stg_orders;

If the two numbers differ, the table is not one row per order.

A type 2 history table has one row per version, valid from valid_from up to, but not including, valid_to. The version in force on a date is:

join dim d
  on d.customer_id = f.customer_id
 and f.ts >= d.valid_from
 and (f.ts < d.valid_to or d.valid_to is null)

Step by step:

  1. State the grain of each input in one sentence.
  2. Reduce the fact table to its grain (see the deduplication lesson) before joining.
  3. Join to history on the key and the date range, half-open (>= start, < end).
  4. Re-check that the row count of the result equals the fact table's.
with latest as (
  select order_id, customer_id, order_total, updated_at,
         row_number() over (partition by order_id order by updated_at desc, loaded_at desc) as rn
  from stg_orders
)
select l.order_id, l.order_total, h.tier, h.region
from latest l
join dim_customers_history h
  on h.customer_id = l.customer_id
 and l.updated_at >= h.valid_from
 and (l.updated_at < h.valid_to or h.valid_to is null)
where l.rn = 1
order by l.order_id
limit 10;

A date spine lists every date so quiet days show as zero. An as-of join then picks the latest rate on or before each day:

with spine as (
  select d::date as day
  from generate_series(date '2025-01-01', date '2025-01-14', interval '1 day') as g(d)
)
select s.day,
       (select r.usd_per_unit
        from fx_rates r
        where r.currency = 'EUR' and r.rate_date <= s.day
        order by r.rate_date desc
        limit 1) as eur_rate_as_of
from spine s
order by s.day;

Weekends have no rows in fx_rates, so the lookup returns Friday's rate for Saturday and Sunday.

Traps interviewers look for

Variations

In other warehouses

Practise analytics engineering