Module 8 · Information Systems · Lesson 6 · Week 5

Instruction session · Tuesday, November 10, 2026 · one hour of demonstration, one hour in groups

Data Cubes and Data Marts

A landing table with what TCGplayer published about the Pokémon TCG sets of 2026 becomes a star schema, a cube and a data mart inside the browser, and the model answers which cards appreciated most during the year. In the second hour each group repeats the same steps with the partner data in the ClickHouse of the class.

db_ingestionGrain and dimensionsPeriodic snapshotCUBE and ROLLUPData martRoll-up, slice, dice, pivot

Project ritual

Daily · 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda · two hours
One hour of modelling, one hour with the partner data

In the first hour the professor builds the model live: each step starts with a CREATE prompt to the coding agent, the SQL it writes runs in the lab page, and the slides explain the concept while the agent works. In the second hour the groups apply the same steps to their own data.

0:20 · step 01DimensionsAgent: 01_dimensions.sqlGrain, dimensions and hierarchies, as views over the landing table
0:30 · step 02FactAgent: 02_fact.sqlThe fact as a view; kinds of fact and additivity of measures
0:36 · step 03Cube and martAgent: 03_cube_and_mart.sqlCUBE and ROLLUP as a view; data mart and conformed dimensions
0:46 · step 04Frozen and live reportsAgent: 04_reports.sqlA month materialized in a table, the last capture in a view
0:53 · step 05Five questionsAgent: 05_questions.sqlRoll-up, slice, pivot, dice and the cards that appreciated most
1:00 · groupsYour data in ClickHouseAgent of each groupThe same model over the partner data, in lab.gNN_ on shrek2
Where the work happensThe demonstration runs in the lab page of the module, with DuckDB compiled for the browser. Nothing is installed: the landing table and the statements of the model are kept in the localStorage of the browser. The group work of the second hour runs in the ClickHouse of the class, as in Lesson 5.
0:15 · Running case
The market of Pokémon cards on TCGplayer

TCGplayer is the largest marketplace of collectible cards in the United States. For every product it publishes a market price per printing, computed from recent sales, and the public mirror tcgcsv.com keeps one copy of those prices per day.

Collector

What is a card worth today?

The price of one card, in one printing, on one date: a Pikachu ex numbered 276/217 in Holofoil cost US$ 571.17 on 07/11/2026.

Store

Which rarities and printings pay off?

The average price by rarity and the premium of a Reverse Holofoil over the Normal print of the same card decide what a store keeps in stock.

Investor

Which cards gained value during the year?

A card that appreciates is compared with itself on two dates. The sum of a whole set changes for other reasons, such as cards that only start to be priced later.

Question of the sessionAmong the cards of the seven Pokémon TCG sets released in 2026, which ones appreciated most between their first price capture and 07/11/2026, in percentage and in dollars?
0:17 · The data
One landing table with three columns

The capture keeps every record exactly as TCGplayer published it, in the same shape as the landing table of Lesson 4 and the enriched table of Lesson 5. The model of the session reads only this table.

data_tagOne record isRowstimestamp
tcgplayer.set.v1a set, with code and release date71794081927
tcgplayer.product.v1a card (1,273) or a sealed product (217), with rarity, number and type in extendedData1,4901794081927
tcgplayer.price.v1the prices of one product in one printing (Normal, Holofoil, Reverse Holofoil)5,951noon UTC of 01/03, 01/05, 01/07, 01/09 and 07/11/2026
db_ingestion
timestamp  BIGINT      Unix time of the capture
data_json  JSON        the record, as published
data_tag   VARCHAR     the kind of record
Unix timeEvery date of the lesson is Unix time, in seconds since 1970-01-01 UTC: 1794052800 is 07/11/2026 at 12:00. 2.2 MB of JSON, 131 KB compressed. The lab keeps the compressed copy in the localStorage of the browser, which holds about 5 MB per site.

Source: tcgcsv.com, public daily mirror of the catalogue and the prices of TCGplayer (category 3, Pokémon). The long text of the cards and the image addresses were removed to fit the browser storage.

0:19 · The lab
DuckDB inside the browser

The lab page loads DuckDB compiled to WebAssembly. On the first visit it downloads the landing table and keeps it in the localStorage; every statement that creates an object is also kept and runs again when the page reloads.

1Prompt

The professor copies the CREATE prompt of the step from the lab and sends it to the coding agent.

2Plan and SQL

The agent shows its plan, receives the go-ahead and writes the SQL file of the step.

3Run

The SQL is pasted into the editor of the lab and runs with Ctrl+Enter, one result per statement.

4Review

The results are checked against the numbers of the rehearsal, written in the prompt itself.

Each step also has the reference SQL of the professor, for when the agent takes longer than the slot of the step.

Step 01 · 0:20 · Dimensions

Dimensions over the landing table

The first decision of a dimensional model is the grain, and the dimensions follow from it. The agent declares both in a specification and writes the dimensions as views over the JSON of db_ingestion.

Files

specs/dimensional_model.md and sql/01_dimensions.sql.

Review before moving on
  • Is the grain one product, in one variant, on one capture date?
  • Are the four dimensions views, and not tables?
  • Do the counts match: 7 sets, 1,490 products (1,273 cards), 3 variants, 5 dates?
Prompt 01 · CREATE
[C] Character
You are a dimensional modeller. A table called db_ingestion holds what was
captured from TCGplayer about the Pokemon TCG sets released in 2026, exactly
as it arrived. You write the dimensions of a star schema over it, in DuckDB,
for a lab that runs inside the browser.

[R] Request
1. specs/dimensional_model.md: the business process (the market price of a
   product on a capture date), the grain of the fact (one product, in one
   variant, on one capture date), the four dimensions with their
   hierarchies and a Mermaid ER diagram of the star.
2. sql/01_dimensions.sql, schema gold, every dimension a view over
   db_ingestion:
   - dim_set from tcgplayer.set.v1: set_id, set_name, set_code,
     released_at (Unix time of publishedOn), release_month ('YYYY-MM');
   - dim_product from tcgplayer.product.v1: product_id, set_id,
     product_name, kind ('card' when the product has a collector Number,
     otherwise 'sealed'), number, rarity, card_type, hp, stage;
   - dim_variant: the distinct subTypeName of tcgplayer.price.v1;
   - dim_date: date_unix (Unix time of 00:00 UTC of the day of the
     capture), month ('YYYY-MM'), quarter, year of the capture dates of the
     prices;
   - a final SELECT with the number of rows of each dimension.

Facts measured on 07/11/2026 (confirm before use):
- db_ingestion: 7 sets, 1,490 products, 5,951 prices.
- 1,273 products are cards; 3 variants; 5 capture dates, date_unix
  1772323200 (2026-03-01), 1777593600 (2026-05-01), 1782864000
  (2026-07-01), 1788220800 (2026-09-01) and 1794009600 (2026-11-07).

[E] Example
db_ingestion(timestamp BIGINT, data_json JSON, data_tag VARCHAR)
timestamp is Unix time in seconds, UTC: 1794052800 = 2026-11-07 12:00.
tcgplayer.set.v1     {"groupId":24541,"name":"ME: Ascended Heroes",
                      "abbreviation":"ASC","publishedOn":"2026-01-30T00:00:00",...}
tcgplayer.product.v1 {"productId":676088,"name":"Pikachu ex - 276/217",
                      "groupId":24541,"extendedData":[
                      {"name":"Number","value":"276/217"},
                      {"name":"Rarity","value":"Special Illustration Rare"},...]}
tcgplayer.price.v1   {"productId":676088,"marketPrice":571.17,
                      "lowPrice":504.9,"subTypeName":"Holofoil",...}

[A] Adjustments
- Every date of the model is Unix time in seconds (BIGINT), never DATE or
  TIMESTAMP. The day of a timestamp is timestamp // 86400 * 86400; to
  extract a label such as the month, use epoch_ms(timestamp * 1000),
  which returns a TIMESTAMP in UTC, never to_timestamp, which depends on
  the time zone of the browser.
- Read a field with data_json->>'field'.
- The attributes of a product are a list of {name, value} in extendedData.
  Inside a macro or a lambda, use json_extract(j, '$.extendedData') and
  the syntax lambda e: ..., because -> is ambiguous there.
- The rarity of a sealed product is 'n/a'.
- The script is pasted into the lab page and runs in DuckDB-WASM 1.32
  (DuckDB 1.4): no files, no COPY, no read_json.

[T] Type of output
The two files and nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 01 · While the agent works

What this step implements

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the results comes after them.

Theory of this step
  1. Dimensional modelling in four decisions
  2. Dimensions and their hierarchies
  3. A natural key that repeats
Back at the lab

Run the file in the lab and read the counts of the final SELECT.

Excerpt of prompt 01
- The attributes of a product are a list of {name, value} in
  extendedData. Inside a macro or a lambda, use
  json_extract(j, '$.extendedData') and the syntax lambda e: ...
Step 01 · Theory 1
Dimensional modelling in four decisions

Kimball designs a model from a business process and its questions, not from the tables of the source. Each decision constrains the next, and the grain is the one that costs most to change later.

1 · Process

Pricing a product

The process measured is the market price that TCGplayer publishes for each product, recomputed every day from recent sales.

2 · Grain

Product × variant × date

One row is one product, in one printing, on one capture date. The same card in Holofoil and in Reverse Holofoil has two prices.

3 · Dimensions

Set, product, variant, date

They describe the context of each price: which set, which card and rarity, which printing and which day.

4 · Facts

Market, low, mid, high

The four prices of the record, plus the days since the release of the set, computed when the fact is built.

The grain decides the questionsA grain of one set per date would answer how much a set is worth, but never which card appreciated. The finer grain answers both, because the value of a set is the sum of its cards on one date.
Step 01 · Theory 2
Dimensions and their hierarchies

A hierarchy orders the attributes of a dimension from the general to the specific. It is the path that roll-up climbs and drill-down descends.

DimensionFrom the tagHierarchyRowsStored as
gold.dim_settcgplayer.set.v1release month › set7view
gold.dim_producttcgplayer.product.v1kind (card or sealed) › rarity › product1,490view
gold.dim_varianttcgplayer.price.v1Normal, Holofoil, Reverse Holofoil3view
gold.dim_datetimestamp of the prices; key date_unixyear › quarter › month › day5view
Why views

A dimension is read in every query but changes little, and here it is small. As a view it keeps no copy and always shows the current landing table, at the cost of reading the JSON again.

The JSON of a product

Rarity, number and type arrive as a list of pairs in extendedData. A macro gold.attr(json, name) filters the list and returns the value, so each attribute is one line of the view.

Dates in Unix time

The key of the day is date_unix, the Unix time of 00:00 UTC: timestamp // 86400 * 86400. Month, quarter and year are labels of the hierarchy, taken from epoch_ms(timestamp * 1000).

Step 01 · Theory 3
A natural key that repeats

The code of a set looks like a key, but TCGplayer gave the code 30C to two different sets released on the same day. A model that groups by the code merges them.

set_idset_codeset_namereleased_at (Unix)Cards
24541ASCME: Ascended Heroes1769731200 · 2026-01-30575
24587PORME03: Perfect Order1774569600 · 2026-03-27124
24655CRIME04: Chaos Rising1779408000 · 2026-05-22122
24688PBLME05: Pitch Black1784246400 · 2026-07-17120
2472230CME: 30th Celebration1789516800 · 2026-09-16161
2483730CME: 30th Celebration Classic Collection1789516800 · 2026-09-1630
24831DLRME06: Delta Reign1793923200 · 2026-11-06141
Consequence for the modelThe fact refers to a set by set_id, the identifier that TCGplayer guarantees, and the cube groups by set_name. The code stays in the dimension as an attribute for display, which is the role a natural key has in a star schema.

Step 02 · 0:30 · Fact

The fact of the prices, as a view, and the test of the grain

The fact is the object of the star that grows with every capture. Like every object of gold it is a view over the landing table, so it always shows the last capture, and the agent proves its grain with a query.

Files

sql/02_fact.sql.

Review before moving on
  • Is gold.fact_price a view, with one row per product, variant and date?
  • Rows = distinct keys of the grain: 5,951 = 5,951?
  • Are there 49 prices without market price, kept and not discarded?
Prompt 02 · CREATE
[C] Character
You are the same dimensional modeller. The dimensions exist in gold; now
the fact that measures the business process.

[R] Request
sql/02_fact.sql:
1. view gold.fact_price, a periodic snapshot with one row per product,
   variant and capture date: date_unix, product_id, set_id, variant,
   market_price, low_price, mid_price, high_price (DECIMAL(10,2)) and
   days_since_release (whole days between released_at of the set and
   date_unix), from tcgplayer.price.v1;
2. the test of the grain: number of rows, number of distinct
   (date_unix, product_id, variant) and rows without market_price;
3. the number of prices per capture date and set.

Facts measured on 07/11/2026 (confirm before use):
- 5,951 rows, 5,951 distinct keys of the grain, 49 without market_price.
- Prices per date grow as the sets are released: on 2026-03-01 only ASC
  (642) and POR (15); on 2026-11-07 all seven sets.

[E] Example
SELECT timestamp // 86400 * 86400                    AS date_unix,
       CAST(data_json->>'productId' AS INTEGER)       AS product_id,
       data_json->>'subTypeName'                      AS variant
FROM db_ingestion WHERE data_tag = 'tcgplayer.price.v1';

[A] Adjustments
- The whole gold layer is views, the fact included: nothing is stored,
  and the fact always shows the last capture of db_ingestion.
- date_unix is the Unix time of 00:00 UTC of the day, as in dim_date.
- The price record has no set: take set_id from dim_product.
- fact_price and dim_product both have set_id: join dim_set with ON, not
  with USING, to avoid an ambiguous column.
- The price is semi-additive: it adds up across products on one date,
  never across dates. Write this in a comment of the file.

[T] Type of output
The file and the three results.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 02 · While the agent works

What this step implements

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the results comes after them.

Theory of this step
  1. Three kinds of fact table
  2. Additive, semi-additive and non-additive measures
  3. The test of the grain
Back at the lab

Run the file and compare the three results with the prompt.

Excerpt of prompt 02
- The price is semi-additive: it adds up across products on one
  date, never across dates. Write this in a comment of the file.
Step 02 · Theory 1
Three kinds of fact table

Kimball distinguishes facts by what one row records. The kind decides how rows arrive and which sums are valid.

Transaction

One event

One row per event, inserted once and never updated, such as one item of one order in the star of Lesson 5. Its measures usually add up in every direction.

Periodic snapshot · this lesson

One state per period

One row per entity per period, even when nothing happened, such as the price of a card on each capture date. It shows how a state evolves.

Accumulating snapshot

One process with milestones

One row per process, updated as it advances, such as an order with the dates of approval, shipping and delivery and the days between them.

Why a periodic snapshot hereThe question compares the price of the same card on different dates. TCGplayer does not publish each sale, only the price of the day, so the state on each capture date is the finest fact available.
Step 02 · Theory 2
Additive, semi-additive and non-additive measures

A measure is classified by the dimensions across which its sum still means something. The classification decides how the cube and every report may aggregate it.

KindAdds up acrossExample in this lessonExample in Lesson 5
additiveevery dimensionnumber of price recordsprice and freight of the items
semi-additiveevery dimension except timemarket price: the cards of a set on one date add up to the cost of the set; one card over five dates does notopen orders on a day
non-additiveno dimensionaverage price of a rarity; percentage of appreciationdistinct count of orders
Rule for semi-additive

Every aggregation keeps the time dimension, or takes one point of it (the last date, the first date), never the sum over it.

Rule for non-additive

The value is recomputed from the fact at each level. An average of averages, or a sum of distinct counts, gives a wrong number.

Step 02 · Result
The fact grows with the sets

The grain test passes: 5,951 rows and 5,951 distinct combinations of date, product and variant. The number of prices grows with each capture, because a set only has prices after it is released.

date_unix · dayPricesProductsSets priced
1772323200 · 03-01657619ASC; POR in pre-sale
1777593600 · 05-01896779+ POR; CRI in pre-sale
1782864000 · 07-011,153960+ CRI; PBL and 30th Celebration in pre-sale
1788220800 · 09-011,4141,147+ PBL; Delta Reign in pre-sale
1794009600 · 11-071,8311,477all seven sets
5,951 = 5,951rows = distinct (date_unix, product_id, variant)
49prices without market price, kept in the fact view
Coverage changes over timeA set is priced first through its sealed products in pre-sale, and its cards enter the fact only after the release, many of them weeks later. This affects every sum over a set, as step 04 shows.

Step 03 · 0:36 · Cube and mart

The cube and the mart of the collectors, as views

The collectors area asks by set, rarity and printing, again and again. The agent writes every combination as a summarised fact table in one view, and publishes two views with friendly names in a data mart.

Files

sql/03_cube_and_mart.sql.

Review before moving on
  • Are the cube and the mart views, like the rest of gold?
  • Does the cube keep date_unix in every grouping?
  • 524 cells in 8 levels, with grouping_id from 0 to 7?
Prompt 03 · CREATE
[C] Character
You are the same dimensional modeller. The collectors area of the business
wants fast answers by set, rarity and variant, and a few views with
friendly names that a dashboard can read.

[R] Request
sql/03_cube_and_mart.sql:
1. view gold.agg_price_cube, the cube as a summarised fact table, only
   for cards with a market price: GROUP BY date_unix, CUBE (set_name,
   rarity, variant), with grouping_id (grouping() of the three), 'all' in
   place of the NULL of a total, and the measures prices (count),
   market_value (sum), avg_market_price and max_market_price;
2. schema mart_collectors with two views:
   - card_price: captured_at (date_unix), month, set_code, set_name,
     released_at, card, number, rarity, variant, market_price,
     days_since_release, cards only;
   - set_value: captured_at, month, set_name, prices, market_value, from
     the level "set" of the cube;
3. the number of cells of each level of the cube (grouping_id 0 to 7);
4. on 2026-11-07 (date_unix 1794009600), the market value of all cards,
   next to the sum of that value over the five dates.

Facts measured on 07/11/2026 (confirm before use):
- 524 cells: 182 set x rarity x variant, 137 set x rarity, 48 set x
  variant, 18 set, 68 rarity x variant, 51 rarity, 15 variant, 5 all.
- All cards on 2026-11-07: US$ 18,989.68; summed over the five dates:
  US$ 51,967.84, a number without meaning.

[E] Example
SELECT f.date_unix, grouping(s.set_name, p.rarity, f.variant) AS grouping_id,
       coalesce(s.set_name, 'all') AS set_name, ...
FROM gold.fact_price AS f ...
GROUP BY f.date_unix, CUBE (s.set_name, p.rarity, f.variant);

[A] Adjustments
- The date stays in every grouping, because the price is semi-additive.
- Group by set_name, not set_code: the code 30C belongs to two sets.
- grouping_id 0 is the finest cell and 7 the total of all cards.
- The cube and the mart are views, like the rest of gold.
- The mart reads gold and never db_ingestion.

[T] Type of output
The file and the two results.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Step 03 · While the agent works

What this step implements

The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the results comes after them.

Theory of this step
  1. What a data cube is
  2. CUBE, ROLLUP and GROUPING SETS
  3. Data mart and conformed dimensions
Back at the lab

Run the file, read the cells of each level and the value of all cards on the last date.

Excerpt of prompt 03
- The date stays in every grouping, because the price is
  semi-additive.
- Group by set_name, not set_code: the code 30C belongs to two sets.
Step 03 · Theory 1
What a data cube is

A cube organises a measure by several dimensions at once. Each cell is the measure for one combination of members, and the totals along each dimension are cells too.

Dimensions of the cube

Set × rarity × variant

Three axes, with the date fixed in each slice. A cell answers: on this date, the cards of this set, of this rarity, in this printing.

Levels

2³ = 8 combinations

All three dimensions, each pair, each one alone and none. The level where a dimension is aggregated shows all in its place.

Storage

MOLAP, ROLAP, HOLAP

A cube can live in a dedicated engine (MOLAP), as summary tables of a relational warehouse (ROLAP), or both. This lesson builds the relational kind.

Summarised fact tableThe cube is an aggregate fact: a fact table with a coarser grain, computed from the base fact. Here it is a view, computed at each read and always current; when the volume grows, or when a result must stay as it was published, it is materialized, which is the subject of step 04.
Step 03 · Theory 2
CUBE, ROLLUP and GROUPING SETS

The three extensions of GROUP BY compute several groupings in one statement. They differ in which combinations they generate, and grouping() tells each row apart.

ClauseGeneratesFor three columns
CUBE (a, b, c)every combination8 groupings
ROLLUP (a, b, c)the hierarchy from left to right4: (a,b,c), (a,b), (a), ()
GROUPING SETS (...)only the listed onesas many as listed
grouping(a, b, c)a bit per aggregated column0 = finest, 7 = total
the cube of the session
SELECT f.date_unix,
       grouping(s.set_name, p.rarity, f.variant)
                                   AS grouping_id,
       coalesce(s.set_name, 'all') AS set_name,
       ...
       sum(f.market_price)         AS market_value
FROM gold.fact_price AS f ...
GROUP BY f.date_unix,
         CUBE (s.set_name, p.rarity, f.variant);
ROLLUP for a hierarchyWhen the columns form a hierarchy, such as year, quarter and month, ROLLUP generates only the meaningful levels. CUBE over a hierarchy would also produce month without year, which repeats the same month of different years.
Step 03 · Result
524 cells in eight levels

The cube view answers every question by set, rarity and variant. Each level is filtered by its grouping_id, and the five capture dates multiply the cells.

grouping_idLevelCells
0set × rarity × variant182
1set × rarity137
2set × variant48
3set18
4rarity × variant68
5rarity51
6variant15
7all cards5
US$ 18,989.68one copy of every card, on 07/11/2026
US$ 51,967.84the same value summed over the five dates
The second number has no meaningIt adds the same cards five times. This is why the date is in every grouping of the cube: the price is semi-additive, and a sum over time is the most common error of a report built on a snapshot.
Step 03 · Theory 3
Data mart and conformed dimensions

A data mart is the part of the warehouse that serves one area of the business, with the names and the granularity that this area uses. Kimball builds the warehouse as the union of marts that share dimensions.

mart_collectors

Two views over gold

card_price joins the fact to its four dimensions with readable names; set_value exposes the level "set" of the cube. A dashboard reads the mart and never the landing table.

Conformed dimensions

The same set, the same date

A second mart, for a store with its own sales, would reuse dim_set, dim_product and dim_date. A question that crosses both marts then compares the same members.

Bus matrixdim_setdim_productdim_variantdim_date
prices (mart_collectors, this lesson)✓✓✓✓
sales of a store (hypothetical mart)✓✓✓✓

Step 04 · 0:46 · Reports

Reports frozen in time and reports always current

Every object of gold is a view and follows the last capture. A report sent to the partner, however, must stay as it was published. The agent materializes the prices of September in tables and keeps the last capture in views, then shows what each one does when a new capture arrives.

Files

sql/04_reports.sql.

Review before moving on
  • Are the two September reports tables and the two latest reports views?
  • Before the simulated capture: 1,049.08 frozen and 571.17 live?
  • After it: 1,049.08 frozen and 600.00 live, and the simulated record deleted?
Prompt 04 · CREATE
[C] Character
You are the same dimensional modeller. Every object of gold and of the
mart is a view, so the model always shows the last capture. The collectors
area also needs reports that stay as they were published.

[R] Request
sql/04_reports.sql, schema report:
1. two materialized reports frozen in September 2026, as tables built with
   CREATE TABLE ... AS from the mart:
   - report.mv_card_price_2026_09: set_name, card, rarity, variant,
     market_price of the capture of month '2026-09';
   - report.mv_set_value_2026_09: set_name, prices, market_value of the
     same capture;
2. two live reports, as normal views over the last capture:
   - report.v_card_price_latest and report.v_set_value_latest, with
     captured_at (Unix time) of the capture;
3. a demonstration in three statements: the market price of
   "Pikachu ex - 276/217" in the frozen report and in the live one; an
   INSERT into db_ingestion of a SIMULATED price record of that card
   (productId 676088, Holofoil, marketPrice 600.0, timestamp 1794312000,
   that is 2026-11-10 12:00 UTC); the same comparison again; then a
   DELETE of the simulated record;
4. a final SELECT that lists every object of gold, mart_collectors and
   report with its kind (table or view).

Facts measured on 07/11/2026 (confirm before use):
- The frozen report keeps 1,226 card prices and the value of 5 sets.
- Pikachu ex 276/217: 1,049.08 in September (frozen), 571.17 captured at
  1794009600 (live); after the simulated capture the live view shows
  600.00 captured at 1794268800 and the frozen report still 1,049.08.

[E] Example
CREATE OR REPLACE TABLE report.mv_set_value_2026_09 AS
SELECT set_name, prices, market_value
FROM mart_collectors.set_value
WHERE month = '2026-09';

[A] Adjustments
- DuckDB has no materialized view: the materialized report is a table,
  and refreshing it means running its CREATE again.
- The live views filter the last capture with max(captured_at), never a
  fixed value.
- Every date is Unix time in seconds, as in the rest of the model.
- Mark the INSERT as simulated in a comment, and remove it at the end.

[T] Type of output
The file and the results of the two comparisons.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 04 · Theory
Views, materialized views and the time of a report

A view keeps its query and computes it at every read, so it follows the source. A materialized result keeps the rows of the moment it was built and stays as it was until it is built again. Which one a report needs depends on what it promises.

ObjectKeeps dataWhen it is computedIn this lesson
view (DuckDB and ClickHouse)no, only the queryat every readall of gold, the mart and report.v_*_latest
table from CREATE TABLE AS (DuckDB)yes, the rows of that momentonce; refreshing means running it againreport.mv_*_2026_09, frozen in September
incremental materialized view (ClickHouse)yes, in a target tableat every INSERT, over the inserted blocksecond hour, for loads in batches
refreshable materialized view (ClickHouse)yes, replaced at onceon a schedule, over the whole sourcesecond hour, for heavy reports
Frozen: a closed period

The prices of September, the sales of a closed month, the figures of a board meeting. Once published they must not move, even if the source is corrected later, because someone already decided on them.

Live: the current state

The prices of today, the stock of now, the queue of the operation. They must follow every capture, so they are views, at the cost of computing the query again at each read.

Step 04 · Result
A new capture reaches only the view

The script compares the Pikachu ex 276/217 in the frozen report of September and in the live report, inserts a simulated capture of 10/11/2026 at US$ 600.00, compares again and removes the simulated record.

MomentFrozen · SeptemberLive · last capturecaptured_at of the live report
before1,049.08571.171794009600
after the simulated capture1,049.08600.001794268800
1,226 · 5card prices and set values kept in the reports of September
What the frozen report also showsThe Pikachu ex 276/217 was worth US$ 1,049.08 in September, almost twice its price of March and of November. A report frozen at the peak keeps a value that the live view no longer shows, which is exactly what a closed report is for.

The record of 10/11/2026 is simulated for the demonstration and is deleted at the end of the script, so that step 05 uses only the real captures.

Step 05 · 0:53 · Five questions

Five questions, one OLAP operation each

The model exists to answer the business. The agent writes one query per question, each reading the cube or the mart, and names the operation of OLAP that it performs.

Files

sql/05_questions.sql.

Review before moving on
  • Does no query read db_ingestion?
  • Does Q5 compare the same card and variant on two dates?
  • Is Pikachu ex 276/217 the only card that appreciated?
Prompt 05 · CREATE
[C] Character
You are an analyst of the collectors area. The cube and the mart are
ready, and five questions came from the business.

[R] Request
sql/05_questions.sql, one query per question, each reading the cube or the
mart and never db_ingestion, with a comment naming the OLAP operation:
Q1 roll-up: on 2026-11-07 (date_unix 1794009600), the average and the
   maximum market price of a card of each rarity;
Q2 slice: the five most expensive cards of Ascended Heroes (ASC) on
   2026-11-07;
Q3 pivot: the market value of each set (rows) in each month of capture
   (columns);
Q4 dice and pivot: for Common, Uncommon, Rare and Double Rare on
   2026-11-07, the average price of each variant (Normal, Reverse
   Holofoil, Holofoil) as columns;
Q5 the question of the session: which cards appreciated most between
   their first capture and 2026-11-07, in percent and in US$, among cards
   that cost at least US$ 5 at the first capture.

Facts measured on 07/11/2026 (confirm before use):
- Q1: RGB Rare averages US$ 3,973.48; Special Illustration Rare 76.32;
  Common 0.20.
- Q2: Mega Gengar ex - 284/217 at US$ 614.27 leads.
- Q3: ME: Ascended Heroes went from US$ 5,910.16 on 2026-03-01 to
  3,516.89; ME: 30th Celebration jumps from 1,349.93 to 12,403.41 only
  because most of its cards had no market price on 2026-09-01.
- Q4: a Common costs 0.15 Normal and 0.25 Reverse Holofoil.
- Q5: only Pikachu ex - 276/217 (Holofoil) appreciated, from 480.58 to
  571.17, +18.9 % and +US$ 90.59; every other card lost value.

[E] Example
PIVOT (SELECT set_name, month, market_value
       FROM mart_collectors.set_value)
ON month USING sum(market_value) GROUP BY set_name;

[A] Adjustments
- Q5 compares the same card and variant on two dates, with arg_min and
  arg_max of market_price by captured_at, never the sum of a set.
- Every date is Unix time in seconds; filter a day by its date_unix.
- Ignore products without market price.

[T] Type of output
The file, the five results and one sentence per question with the answer.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 05 · Theory
The five operations of OLAP

Every multidimensional question is a movement over the cube: along a hierarchy, inside a dimension or across the axes.

Roll-upClimb a hierarchy

From the card to its rarity, from the day to the month. Fewer cells, higher level.

Drill-downDescend a hierarchy

From the rarity to its cards, from the year to the quarters.

SliceFix one member

Only Ascended Heroes: the cube loses one dimension.

DiceFix several members

Four rarities, three variants, one date: a smaller cube.

PivotTurn the axes

Dates as columns, sets as rows: the same cells in another layout.

In SQLRoll-up and drill-down choose a level by grouping_id, slice and dice are WHERE clauses, and pivot is the PIVOT of DuckDB.
Q1 · Roll-up · Q2 · Slice
How much a rarity is worth, and the top of a set

Q1 climbs from the card to the rarity on 07/11/2026. Q2 fixes one set and descends to its cards. The average of a rarity is non-additive, so the cube computes it from the fact.

RarityPricesAverage US$Maximum US$
RGB Rare33,973.484,492.45
Mega Hyper Rare6160.91284.88
Special Illustration Rare5676.32614.27
Illustration Rare984.6040.65
Ultra Rare852.9413.76
Double Rare900.987.66
Common6480.200.81
Ascended Heroes · 07/11/2026RarityUS$
Mega Gengar ex - 284/217Special Illustration Rare614.27
Pikachu ex - 276/217Special Illustration Rare571.17
Mega Dragonite ex - 290/217Special Illustration Rare402.35
Pikachu ex - 277/217Special Illustration Rare243.04
Mega Charizard Y ex - 294/217Mega Hyper Rare223.84

Seven of the thirteen rarities are shown. All prices are the market price of TCGplayer, in US dollars, all variants of the card included.

Q3 · Pivot
The value of each set on each date

One copy of every card of a set, priced on each capture date. The sum is valid inside a date and the dates sit side by side, never added.

Set2026-032026-052026-072026-092026-11
ME: Ascended Heroes5,910.167,699.407,576.395,712.333,516.89
ME03: Perfect Order917.08781.93627.94459.14
ME04: Chaos Rising953.79653.84436.91
ME05: Pitch Black795.37534.94
ME: 30th Celebration1,349.9312,403.41
ME: 30th Celebration Classic Collection621.24
ME06: Delta Reign1,017.15
What the table shows

Every set loses value after its release: Ascended Heroes peaks in May and ends at 59 % of its value in March.

What it does not show

The 30th Celebration did not appreciate ninefold. On 01/09 most of its cards had no market price yet; the RGB Rare cards, about US$ 4,000 each, entered the sum later.

Q4 · Dice and pivot
The price of each printing of the same rarity

A sub-cube with four rarities, three variants and one date, turned so that the variants become columns. A cell left empty means that the rarity is not printed in that variant.

Rarity · 07/11/2026NormalReverse HolofoilHolofoil
Common0.150.250.18
Uncommon0.160.28
Rare0.320.20
Double Rare0.98
≈ 1.7 ×a Reverse Holofoil over the Normal print of a Common or an Uncommon
Reading a diceThe question fixed members of three dimensions at once (rarity, variant and date) and kept the full grid. Without the cube, the same answer would join the fact to the product dimension and average the prices of that date.
Q5 · The question of the session
One card out of 137 appreciated

Each card is compared with itself, in the same variant, on its first capture and on 07/11/2026. Only cards that cost at least US$ 5 at the first capture enter, so that a few cents do not become a large percentage.

SetCardRarityFirst capture (Unix)First US$07/11 US$Gain US$Gain %
ASCPikachu ex - 276/217Special Illustration Rare1772323200480.58571.17+90.59+18.9
PBLCrushing HammerUltra Rare17882208005.204.37−0.83−16.0
PBLMega Zeraora ex - 098/084Ultra Rare17882208006.695.61−1.08−16.1
ASCPikachu ex - 277/217Special Illustration Rare1772323200327.88243.04−84.84−25.9
ASCMega Dragonite ex - 290/217Special Illustration Rare1772323200574.74402.35−172.39−30.0
AnswerAmong the 137 cards that cost at least US$ 5 on their first capture, only the Pikachu ex 276/217 of Ascended Heroes appreciated, by 18.9 % and US$ 90.59. All the others lost value, which is the usual path of a set after its release. The same model, with a longer window or a lower threshold, would show the cards that recover later.
1:00 · Second hour · in groups
The same model over the partner data

Each group repeats the four steps with its own data in the ClickHouse of the class, in the database lab, with every object named with the prefix of the group, as in Lesson 5.

1:00Loadlab.gNN_db_ingestionThe enriched partner data, in the three columns of the landing table
1:15Specificationspecs/dimensional_model.mdProcess, grain, dimensions, measures and five questions, reviewed before any SQL
1:25Dimensions and factviews onlyJSONExtract over the landing table; the test of the grain
1:40Cube and reportsa view and one frozen tableWITH CUBE over three dimensions; a closed month materialized
1:50Answersdocs/answers.mdFive questions of the partner, each with its query and operation

Step 06 · 1:00 · Groups

Prompt for the partner data in ClickHouse

The prompt asks the agent of the group for the specification first and stops there, so that the group reviews the grain and the questions before any SQL reaches the shared server.

Files

specs/dimensional_model.md, sql/clickhouse/00 to 05 and docs/answers.md.

Review before moving on
  • Is every object named lab.gNN_…, and no object of another group touched?
  • Does the grain test pass on the fact of the group?
  • Does each of the five answers name its OLAP operation and its query?
Prompt 06 · CREATE
[C] Character
You are the dimensional modeller of our group. Our partner data already
went through the enrichment of Lesson 5. Now it becomes a star and a cube
in the ClickHouse of the class (shrek2), in the database lab, where every
object of the group starts with gNN_.

[R] Request
1. specs/dimensional_model.md: the business process of the partner that
   we measure, the grain of the fact in one sentence, the dimensions with
   their hierarchies, the measures classified as additive, semi-additive or
   non-additive, and five questions of the partner, each one with the OLAP
   operation that answers it (roll-up, drill-down, slice, dice or pivot).
2. sql/clickhouse/00_db_ingestion.sql: table lab.gNN_db_ingestion
   (timestamp Int64, data_json String, data_tag LowCardinality(String)),
   MergeTree ORDER BY (data_tag, timestamp), with timestamp in Unix time
   (seconds, UTC), and the command that loads our enriched data into it.
3. sql/clickhouse/01_dimensions.sql: one view lab.gNN_dim_<name> per
   dimension, with JSONExtractString, JSONExtractFloat and JSONExtractInt.
4. sql/clickhouse/02_fact.sql: the fact as a view lab.gNN_fact_<process>,
   and the test of the grain.
5. sql/clickhouse/03_cube.sql: the cube as a view lab.gNN_agg_<process>_cube
   with GROUP BY ... WITH CUBE (or GROUPING SETS) over at least three
   dimensions and grouping() of each one.
6. sql/clickhouse/04_reports.sql: one report frozen in time, for a closed
   month of the partner, materialized with CREATE TABLE ... ENGINE =
   MergeTree ORDER BY ... AS SELECT; and the same report as a normal view
   over the last period, always current.
7. sql/clickhouse/05_questions.sql and docs/answers.md: the five
   questions, each answer with the number and the query that produced it.

[E] Example
CREATE OR REPLACE VIEW lab.g01_dim_customer AS
SELECT JSONExtractString(data_json, 'customer_id') AS customer_id,
       JSONExtractString(data_json, 'state')       AS state
FROM lab.g01_db_ingestion
WHERE data_tag = 'partner.customer.v1';

[A] Adjustments
- Every date of the model is Unix time in seconds (Int64), never Date or
  DateTime: the day is intDiv(timestamp, 86400) * 86400, and a label such
  as the month comes from formatDateTime(toDateTime(timestamp, 'UTC'),
  '%Y-%m').
- Replace gNN with the number of the group in every object; never drop an
  object of another group.
- The console http://10.8.8.10:8123/play runs one statement at a time:
  keep every statement self-contained and end each file with the
  statements that check it.
- To load the data, use clickhouse-connect from Python or
  INSERT ... FORMAT JSONEachRow over HTTP with curl; the Play console does
  not upload files.
- A distinct count does not add up across a dimension: compute the totals
  of the cube in the cube, never by summing finer cells.
- If a measure is semi-additive, keep its time dimension in every grouping
  of the cube.
- The whole gold layer of the group (dimensions, fact and cube) is views;
  only the frozen report stores data.

[T] Type of output
The files, the rows of every object of the group and the five answers.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop after the specification and wait for our review before the SQL.
Second hour · Delivery
What each group delivers at the end of the session

The delivery is the repository of the group with the files of the prompt and the objects in lab. Each check has a statement that the professor can run on the server.

CheckStatement on shrek2Expected
the landing table existsSELECT data_tag, count() FROM lab.gNN_db_ingestion GROUP BY data_tagone row per tag of the partner
the grain holdsSELECT count(), uniqExact(<key of the grain>) FROM lab.gNN_fact_…the two numbers are equal
the cube has every levelSELECT grouping_id, count() FROM lab.gNN_agg_…_cube GROUP BY 12ⁿ levels for n dimensions
the closed month is frozenSELECT name, engine FROM system.tables WHERE database = 'lab' AND name LIKE 'gNN_report%'one MergeTree table and one view
the objects are of the groupSELECT name, engine FROM system.tables WHERE database = 'lab' AND name LIKE 'gNN_%'views, MVs and tables of the model
the questions are answereddocs/answers.mdfive answers, each with query and operation
For the artifact of the sprintThe specification and the cube enter the Data Ingestion Structure artifact as the analytical layer that the DataApp will read; the five questions become the first indicators of its dashboard.
Self-study
Self-study for this session

Readings and a video assigned on Adalove for this week. They extend the cube part of the session: the operations of OLAP, its storage models and the relation between warehouse and mart.

Self-study 1

What is OLAP?

IBM overview of OLAP cubes, their operations (roll-up, drill-down, slice, dice, pivot) and MOLAP, ROLAP and HOLAP.

ibm.com· 60 min
Reading material

Lesson 6 material

The theory of each step in depth, the five prompts in full, the reference numbers and the mistakes that agents usually make in this lab.

this module

About this session

Data Cubes and Data Marts · 10/11/2026 · Prof. Afonso

Learning objective

By the end of the session, students should be able to model a data cube with at least three dimensions over a landing table, write its gold layer and data mart as views, decide when a report must be materialized and frozen in time, and answer multidimensional questions over it, first with TCGplayer prices and then with the partner data in ClickHouse.

Session strategy

Demonstration followed by application. In the first hour the professor builds the model live with a coding agent in five steps (dimensions, fact, cube and mart, frozen and live reports, and five questions), pasting each CREATE prompt and running the SQL it writes in a lab page with DuckDB inside the browser, over a landing table kept in the localStorage; while the agent works, the slides explain the concept of the step, and each step closes with a review against the numbers of the rehearsal. In the second hour each group repeats the steps over the partner data in the ClickHouse of the class, starting with a specification that is reviewed before any SQL.

Session structure

  1. Daily — 15 min
  2. Case, landing table and lab in the browser — 5 min
  3. Step 01: grain and dimensions as views — 10 min
  4. Step 02: the fact as a view; additivity of measures — 6 min
  5. Step 03: cube and data mart, as views — 10 min
  6. Step 04: frozen and live reports — 7 min
  7. Step 05: five OLAP questions — 7 min
  8. Second hour: the partner data in ClickHouse, in groups — 60 min