Module 8 · Information Systems · Lesson 6 · Week 5

Data Cubes and Data Marts

Reference material for the session in which the professor builds, live and with a coding agent, a dimensional model over a landing table with what TCGplayer published about the Pokémon TCG sets of 2026: dimensions with hierarchies, a periodic snapshot of prices, a cube as a summarised fact table and a data mart, all as views in DuckDB inside the browser, reports frozen in September next to reports always current, and the cards that appreciated most during the year. In the second hour each group builds the same model over the partner data in the ClickHouse of the class.

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
Part IFoundations

1. How to read this material

This material accompanies Lesson 6, which has two hours. In the first, the professor builds a dimensional model live, in five steps, over a landing table with what TCGplayer published about the Pokémon TCG sets released in 2026; each step starts with a CREATE prompt sent to a coding agent, and the SQL that the agent writes runs in the lab page of the module, inside the browser. In the second hour, each group applies the same steps to the partner data in the ClickHouse of the class.

Parts I to III follow the theory blocks of the first hour: the case and the landing table, the grain, the dimensions and the kinds of fact and measure, and then the cube, the materialisation and the data mart. Part IV describes the lab step by step, with the prompts in full, the reference SQL and the results, and Part V describes the work of the groups in ClickHouse. A reader who missed the session can reproduce every result by opening the lab page and running the reference SQL of each step, without installing anything.

Every number was measured on 07/11/2026 with DuckDB 1.4.3 compiled to WebAssembly (DuckDB-WASM 1.32.0) and confirmed with the Python package of the same version. The landing table is a fixed file of the repository, so the counts and the prices are deterministic and must be reproduced exactly; a different count indicates a wrong filter or a wrong join, not a change of the data.

2. The case: the market of Pokémon cards on TCGplayer

TCGplayer is the largest marketplace of collectible cards in the United States. For each product it lists, a single card in a given printing or a sealed product such as a booster box, it publishes a market price computed from recent sales, together with the lowest, the middle and the highest listing. The public site tcgcsv.com mirrors the catalogue and the prices of TCGplayer once a day and keeps a daily archive of the prices, which makes it possible to know the price of a card on past dates without an account or a key of the official API, whose access is restricted to approved partners.

The case of the lesson takes the seven Pokémon TCG sets released in 2026, from ME: Ascended Heroes in January to ME06: Delta Reign in November, with their 1,490 products and the prices of those products on five dates. Collectors, stores and investors ask different questions of the same prices: a collector wants the current value of a card, a store wants to know which rarities and printings are worth keeping in stock, and an investor wants to know which cards gained value during the year. The last question is the question of the session.

SetCodeReleased onCardsProducts
ME: Ascended HeroesASC2026-01-30575620
ME03: Perfect OrderPOR2026-03-27124156
ME04: Chaos RisingCRI2026-05-22122150
ME05: Pitch BlackPBL2026-07-17120148
ME: 30th Celebration30C2026-09-16161224
ME: 30th Celebration Classic Collection30C2026-09-163030
ME06: Delta ReignDLR2026-11-06141162

The question needs care, because a set is not priced all at once. TCGplayer lists the sealed products of a set in pre-sale weeks before the release, and the single cards enter the price list after the release, many of them weeks later. A comparison between the total value of a set on two dates therefore mixes appreciation with coverage, and the only valid comparison of appreciation is the same card, in the same printing, on two dates.

3. The landing table db_ingestion

The data of the lesson arrives in one table with three columns, the same shape as the landing table of Lesson 4 and the enriched table of Lesson 5. timestamp records when the record was captured, in Unix time: the number of seconds since 00:00 UTC of 1 January 1970, stored as an integer (BIGINT). data_json keeps the record exactly as TCGplayer published it, with its field names, and data_tag says which kind of record it is. Keeping the record whole in a JSON column means that a new field published by the source does not break the load, and that the model can be rebuilt from the landing table at any time.

data_tagOne record isRowstimestamp (Unix)
tcgplayer.set.v1a set, with its code and release date71794081927 (07/11/2026 20:05 UTC)
tcgplayer.product.v1a product: 1,273 cards, which have a collector number, and 217 sealed products1,4901794081927
tcgplayer.price.v1the prices of one product in one printing (Normal, Holofoil or Reverse Holofoil)5,951noon UTC of 01/03, 01/05, 01/07, 01/09 and 07/11/2026, from 1772366400 to 1794052800

Every date of the model follows the same rule and is Unix time in seconds. An integer has no time zone, compares and sorts as a number and is the same in DuckDB, in ClickHouse and in any language that reads the data; the price paid is that a person needs a conversion to read it, which the model makes only where a label is needed. The day of a capture is timestamp // 86400 * 86400, the Unix time of 00:00 UTC of that day, and the labels of month, quarter and year come from epoch_ms(timestamp * 1000), which DuckDB returns in UTC. The conversion with to_timestamp is avoided, because it applies the time zone of the browser and moves the captures of the first hours of a day to the day before.

One record of each tag (the product and the price are the Pikachu ex 276/217)
tcgplayer.set.v1      {"groupId":24541,"name":"ME: Ascended Heroes","abbreviation":"ASC",
                       "isSupplemental":false,"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"},
                                       {"name":"Card Type","value":"Lightning"},
                                       {"name":"HP","value":"200"},{"name":"Stage","value":"Basic"}],...}
tcgplayer.price.v1    {"productId":676088,"lowPrice":504.9,"midPrice":699.41,"highPrice":5000.0,
                       "marketPrice":571.17,"directLowPrice":587.14,"subTypeName":"Holofoil"}

Two simplifications were made in the capture, both recorded in capture/capture_tcgplayer.py of the lab. The long text of each card, with its attacks and rules, and the address of its image were removed from the products, so that the file fits the storage of the browser. The prices of each date come from the daily archive of tcgcsv.com and receive the timestamp of noon of that date. The complete file has 2.2 MB of JSON and 131 KB once compressed, and it can be downloaded from the lab as data/db_ingestion.json by the groups who want to repeat the model elsewhere.

4. The lab in the browser

The lab page loads DuckDB compiled to WebAssembly, which runs the same SQL engine as the command line, inside the tab and without a server. On the first visit the page downloads the compressed landing table, keeps it in the localStorage of the browser and creates db_ingestion from it; on later visits the copy in the localStorage is used, and the page works without network once DuckDB itself is in the cache. Every statement that creates, changes or removes an object is also kept, and it runs again when the page reloads, so the model built during the session survives a reload or the closing of the tab.

The localStorage holds about 5 MB per site, counted in characters of two bytes, and is shared by every page of the same address. The compressed landing table occupies about 343 KB of it and the statements of the complete model less than 20 KB, which leaves room for the other pages of the portal. The data itself lives in the memory of the tab while it is open: what persists is the source and the recipe, and the model is rebuilt from them in less than a second. The panel at the side of the editor shows the objects of the model, the space used, and two buttons, one that drops the model and keeps the data, and one that forgets everything.

Below the editor, a drill-down explorer draws the materialized report of September, or the live report, as ranked bars grouped by the dimensions that the reader checks: set, rarity, card and variant. Checking a dimension drills down and unchecking it rolls up; clicking a bar descends into that member along the hierarchy set › rarity › card, and the path of filters above the chart rolls back up. For every view the explorer shows the SQL it ran and the level of gold.agg_price_cube that holds the same cells, identified by its grouping_id, and checks that the numbers are equal; at the level of the card, finer than the grain of the cube, the view comes from the report alone.

The choice of the browser has a teaching purpose and a limit. It removes every installation from the session, so that the time is spent on the model and not on the environment, and it makes the lab reproducible by any student at home. It does not replace a warehouse: the data of a real partner, with millions of rows, belongs to a server, which is why the second hour runs in ClickHouse.

Part IIDimensional modelling

5. Grain and dimensions

Kimball and Ross design a dimensional model in four decisions taken in order, because each one depends on the previous. The first selects the business process to be measured, which here is the pricing of a product by TCGplayer. The second declares the grain, the exact meaning of one row of the fact table: one product, in one printing, on one capture date. The third chooses the dimensions that describe the context of each row, and the fourth the numerical facts that are measured. The grain comes before the dimensions because it determines which questions the model can answer: a grain of one set per date would answer how much a set is worth on that date, but never which card appreciated, while the finer grain answers both, since the value of a set is the sum of its cards.

The dimensions of the case and their hierarchies

Each dimension has a hierarchy, an order of its attributes from the general to the specific, which is the path along which a question climbs or descends. The four dimensions of the case are written as views over the landing table, because they are small, read in every query and rarely changed; as views they keep no copy and always reflect the current landing table, at the cost of reading the JSON again at each use.

DimensionFromHierarchyRows
gold.dim_settcgplayer.set.v1release month › set7
gold.dim_producttcgplayer.product.v1kind (card or sealed) › rarity › product1,490
gold.dim_varianttcgplayer.price.v1Normal, Holofoil, Reverse Holofoil3
gold.dim_datetimestamp of the prices; key date_unix, the Unix time of 00:00 UTCyear › quarter › month › day5

The attributes of a product arrive as a list of pairs in extendedData, and a card is told apart from a sealed product by the presence of a collector number in that list. A macro gold.attr(json, name) filters the list and returns the value of one attribute, so each attribute is one line of the view and the rule that reads the list is written once.

A natural key that repeats

The code of a set looks like a key, but TCGplayer gave the code 30C to two sets released on the same day, ME: 30th Celebration and its Classic Collection. A model that identifies or groups sets by the code merges the two without any error message, and the merged set shows a value that belongs to neither. The fact therefore refers to a set by set_id, the identifier that TCGplayer guarantees as unique, the cube groups by set_name, and the code remains in the dimension as an attribute for display. This is the role that a natural key has in a star schema: it describes the member, while the identity comes from a key that the model can trust.

6. The fact and its kind

Kimball distinguishes three kinds of fact table by what one row records. A transaction fact has one row per event, inserted once and never updated, as the item of an order in the star of Lesson 5. A periodic snapshot has one row per entity per period, even when nothing happened in the period, and records the state of the entity at that moment, as the price of a card on each capture date. An accumulating snapshot has one row per process and is updated as the process advances through its milestones, as an order with the dates of approval, shipping and delivery. The fact of this lesson is a periodic snapshot, because TCGplayer does not publish each sale but the price of the day, and the state on each capture date is the finest measurement available.

gold.fact_price is a view, like every object of the gold layer. It keeps no copy of the data: at every query it reads the price records of the landing table, types the JSON and joins the product and the set, so it always reflects the last capture that arrived. With 5,951 prices the cost of recomputing it is a few milliseconds; with the volume of a real partner the same view would be materialized, a decision that section 10 discusses. The fact carries the four prices of the record and the number of days since the release of the set, together with the keys of the product, the set, the variant and the date.

The test of the grain

The grain declared in the specification is verified with a query: the number of rows of the fact must be equal to the number of distinct combinations of its key. A larger number of rows means that the same product, variant and date appear twice, and that every sum over the fact counts some prices twice. In the case the test returns 5,951 rows and 5,951 combinations, and 49 rows without market price, which are kept because the other prices of the record are valid.

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

7. Additive, semi-additive and non-additive measures

A measure is classified by the dimensions across which its sum still has meaning, and the classification decides how every aggregate of the model may treat it. An additive measure can be summed across every dimension, as the number of price records. A semi-additive measure can be summed across some dimensions but not across time: the market prices of all the cards of a set on one date add up to the cost of buying one copy of each, but the price of one card summed over five dates is a number without meaning. A non-additive measure cannot be summed across any dimension, as an average or a percentage, and must be recomputed from the fact at each level.

KindAdds up acrossIn this lessonIn Lesson 5
additiveevery dimensionnumber of price recordsprice and freight of the items
semi-additiveevery dimension except timemarket priceopen orders on a day
non-additiveno dimensionaverage price of a rarity; percentage of appreciationdistinct count of orders

The classification has two practical consequences. Every aggregation of a semi-additive measure keeps the time dimension, or takes one point of it, such as the first or the last date, and never sums over it; this is why the cube of the lesson groups by the date in every one of its levels. A non-additive measure is recomputed from the fact for each cell, and an average of averages or a sum of distinct counts gives a wrong number that looks plausible, which makes the error hard to notice.

Part IIICubes and marts

8. Data cubes and OLAP

A data cube organises a measure by several dimensions at once. Each cell holds the measure for one combination of members, one set, one rarity and one variant in the case, and the totals along each dimension are cells too: the cell of a set with every rarity and every variant is the total of the set. With three dimensions there are 2³ = 8 combinations of grouped and aggregated dimensions, from the finest level, where the three are present, to the grand total, where none is.

Online analytical processing, OLAP, is the kind of workload that a cube serves: few users, wide questions over large volumes, read much more often than written. A cube can be kept in a dedicated multidimensional engine (MOLAP), as summary tables of a relational warehouse (ROLAP), or in a mix of both (HOLAP). This lesson builds the relational kind, in which the cube is a summarised fact table: a fact table with a coarser grain, computed from the base fact, that gives the frequent questions a ready level to read. In the lab the cube is a view, computed at each read from the fact, so it never lags behind the landing table.

9. CUBE, ROLLUP and GROUPING SETS

The three extensions of GROUP BY compute several groupings in one statement and return them in one result. CUBE (a, b, c) generates every combination of the listed columns; ROLLUP (a, b, c) generates only the hierarchy from left to right, that is (a, b, c), (a, b), (a) and the total; GROUPING SETS generates only the combinations listed. In a row of a level where a column was aggregated the column is NULL, and the function grouping() tells this NULL apart from a real one: with several arguments it returns a number in which each bit says whether the corresponding column was aggregated, so 0 is the finest level and 7 the total of three columns.

ClauseGeneratesFor three columns
CUBE (a, b, c)every combination8 groupings
ROLLUP (a, b, c)the hierarchy from left to right4 groupings
GROUPING SETS (...)only the listed onesas many as listed
grouping(a, b, c)a bit per aggregated column0 = finest, 7 = total

ROLLUP fits a hierarchy, such as year, quarter and month, because it generates only the meaningful levels; CUBE over the same columns would also produce the month without the year, which merges the same month of different years. The cube of the case uses CUBE, because set, rarity and variant are independent dimensions, and keeps the date outside it, in the plain GROUP BY, because the price is semi-additive. The result has 524 cells in eight levels, against 5,951 rows of the fact.

grouping_idLevelCells
0set × rarity × variant182
1set × rarity137
2set × variant48
3set18
4rarity × variant68
5rarity51
6variant15
7all cards5

The last cell shows why the date stays in every grouping. One copy of every card was worth US$ 18,989.68 on 07/11/2026, while the same value summed over the five dates gives US$ 51,967.84, which adds the same cards up to five times and corresponds to nothing that can be bought.

10. Views, materialized views and the time of a report

A view keeps only its query and computes it at every read, so it always follows its sources and pays the full cost each time. A materialized result keeps the rows of the moment in which it was built and stays as it was until it is built again, so it is cheap to read and does not follow the sources. In the lab the whole gold layer, the cube included, and the mart are views, because the data is small and the model must always show the last capture. The difference matters for reports, which sometimes must follow the data and sometimes must not.

ObjectKeeps dataWhen it is computedIn this lesson
view (DuckDB and ClickHouse)no, only the queryat every readdimensions, fact, cube, mart and report.v_*_latest
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 block onlysecond hour, for loads in batches
refreshable materialized view (ClickHouse)yes, replaced at onceon a schedule, over the whole sourcesecond hour, for heavy reports

Reports frozen in time

A report of a closed period, such as the prices of September sent to the partner on the first day of the month or the sales of a month already closed in the books, must keep the values that were published, even if the source is corrected or completed afterwards, because decisions were taken on them. Such a report is materialized once and never refreshed. DuckDB has no materialized view, and the materialized report is a table built with CREATE TABLE ... AS SELECT; in ClickHouse it is a MergeTree table built the same way, or a materialized view whose refresh is not scheduled.

Reports always current

A report of the current state, such as the prices of the last capture, must follow every new capture, and it is a normal view that filters the last date with max(date) instead of a fixed date. Step 04 of the lab puts the two side by side and inserts a simulated capture to show that only the view moves; section 15 gives the numbers. An incremental materialized view of ClickHouse sits between the two kinds: it follows new inserts but sees only the rows inserted after it was created, so the rows already in the source must be loaded once, separately, with the same query.

11. Data marts and conformed dimensions

A data mart is the part of the warehouse that serves one area of the business, with the names, the granularity and the questions of that area. In the approach of Kimball the warehouse is the union of its marts, built one at a time, and what keeps them consistent is that they share their dimensions: a dimension is conformed when it has the same keys, the same attributes and the same meaning in every fact that uses it. A question that crosses two marts, such as the price of a card against the sales of a store, then compares the same sets, the same cards and the same dates.

The mart of the case, mart_collectors, has two views over gold. card_price joins the fact to its four dimensions and exposes the price of each card on each date with readable names; set_value exposes the level "set" of the cube. A dashboard reads the mart and never the landing table, so a change in the JSON of the source is absorbed by the dimensions and does not reach the users. The bus matrix records which dimension each mart uses and is the plan of the warehouse.

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

12. The five operations of OLAP

Every multidimensional question can be described as a movement over the cube. Roll-up climbs a hierarchy, from the card to its rarity or from the day to the month, and returns fewer cells at a higher level; drill-down descends it, from the rarity to its cards. Slice fixes one member of one dimension, such as one set, and leaves a cube with one dimension less; dice fixes several members of several dimensions, such as four rarities, three variants and one date, and leaves a smaller cube. Pivot turns the axes and shows the same cells in another layout, with the dates as columns and the sets as rows.

OperationIn SQL over the cubeQuestion of the lesson
roll-up / drill-downchoose the level by grouping_idQ1: average price of each rarity
sliceWHERE on one memberQ2: the most expensive cards of one set
pivotPIVOT in DuckDB; conditional aggregation in ClickHouseQ3: value of each set on each date
diceWHERE on several members, often with a pivotQ4: price of each printing of four rarities
comparison over timethe same member on two points of the time dimensionQ5: the cards that appreciated most
Part IVLab

13. Step 00 · Opening the lab

The lab is the page lab/lesson-6/ of the module, linked from the slides, from this material and from the home of the module. It needs only a recent browser; on the first visit it downloads DuckDB from a public CDN and the landing table from the repository, which takes a few seconds, and the status line shows the version of DuckDB, the number of rows of db_ingestion (7,448) and how many statements of the model were replayed.

Each step has two buttons. "Prompt" opens the CREATE prompt of the step, with a button to copy it to the coding agent; "Reference SQL" loads into the editor the SQL that the professor wrote and measured, for when the agent takes longer than the slot of the step or writes something that does not run. The editor runs every statement of the script with Ctrl+Enter, shows one result per statement and stops at the first error. Clicking an object in the side panel writes a query that shows its first rows.

The coding agent works in a folder of the professor, writes the SQL file of the step and does not run it: the SQL is pasted into the lab and runs there. The prompts state the facts measured in the rehearsal, so that both the agent and the class can compare the result of each step with the expected numbers.

14. The lab in five steps

The five steps below are the ones shown on the slides, in the same order. Each one has the prompt in full, the review that closes it and the reference SQL, which is the same file that the lab loads.

Step 01 · Dimensions

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.

Review before moving on:

  • 7 sets, 1,490 products, 1,273 cards, 3 variants and 5 dates
  • the four dimensions and the macro are views or macros, none is a table
  • a sealed product has the rarity n/a
Reference SQL of step 01
lab/lesson-6/sql/01_dimensions.sql
-- Lesson 6 · Step 01 · Dimensions over the landing table
--
-- Reference of the professor for prompt 01. In class the coding agent writes
-- its own version and the professor runs it in the lab page.
-- Everything reads db_ingestion, where each record is a JSON object with
-- the field names of TCGplayer.
--
-- Dimensions are views: they store no copy and always show the current
-- state of db_ingestion. Every date is Unix time, in seconds since
-- 1970-01-01 UTC, as the column timestamp of db_ingestion.

CREATE SCHEMA IF NOT EXISTS gold;

-- The extended attributes of a product arrive as a list of {name, value}.
CREATE OR REPLACE MACRO gold.attr(j, attr_name) AS
    list_filter(from_json(json_extract(j, '$.extendedData'), '[{"name":"VARCHAR","value":"VARCHAR"}]'),
                lambda e: e.name = attr_name)[1].value;

-- Set (collection): one row per set released in 2026.
CREATE OR REPLACE VIEW gold.dim_set AS
SELECT
    CAST(data_json->>'groupId' AS INTEGER)              AS set_id,
    data_json->>'name'                                  AS set_name,
    data_json->>'abbreviation'                          AS set_code,
    CAST(epoch(CAST(data_json->>'publishedOn' AS TIMESTAMP)) AS BIGINT) AS released_at,
    strftime(CAST(data_json->>'publishedOn' AS TIMESTAMP), '%Y-%m')     AS release_month
FROM db_ingestion
WHERE data_tag = 'tcgplayer.set.v1';

-- Product: a single card (it has a collector number) or a sealed product.
-- Hierarchy of the card: set > rarity > card.
CREATE OR REPLACE VIEW gold.dim_product AS
SELECT
    CAST(data_json->>'productId' AS INTEGER)            AS product_id,
    CAST(data_json->>'groupId' AS INTEGER)              AS set_id,
    data_json->>'name'                                  AS product_name,
    CASE WHEN gold.attr(data_json, 'Number') IS NULL THEN 'sealed' ELSE 'card' END AS kind,
    gold.attr(data_json, 'Number')                      AS number,
    coalesce(gold.attr(data_json, 'Rarity'), 'n/a')     AS rarity,
    gold.attr(data_json, 'Card Type')                   AS card_type,
    TRY_CAST(gold.attr(data_json, 'HP') AS INTEGER)     AS hp,
    gold.attr(data_json, 'Stage')                       AS stage
FROM db_ingestion
WHERE data_tag = 'tcgplayer.product.v1';

-- Variant: the printing of a card, which TCGplayer prices separately.
CREATE OR REPLACE VIEW gold.dim_variant AS
SELECT DISTINCT data_json->>'subTypeName' AS variant
FROM db_ingestion
WHERE data_tag = 'tcgplayer.price.v1';

-- Date of capture, with the hierarchy year > quarter > month > day. The key
-- date_unix is the Unix time of 00:00 UTC of the day of the capture.
CREATE OR REPLACE VIEW gold.dim_date AS
SELECT DISTINCT
    timestamp // 86400 * 86400                            AS date_unix,
    strftime(epoch_ms(timestamp * 1000), '%Y-%m')         AS month,
    year(epoch_ms(timestamp * 1000)) || '-Q' || quarter(epoch_ms(timestamp * 1000)) AS quarter,
    year(epoch_ms(timestamp * 1000))                      AS year
FROM db_ingestion
WHERE data_tag = 'tcgplayer.price.v1';

-- Check: 7 sets, 1,490 products (1,273 cards), 3 variants, 5 dates.
SELECT 'dim_set' AS dimension, count(*) AS rows FROM gold.dim_set
UNION ALL SELECT 'dim_product', count(*) FROM gold.dim_product
UNION ALL SELECT 'dim_product (cards)', count(*) FROM gold.dim_product WHERE kind = 'card'
UNION ALL SELECT 'dim_variant', count(*) FROM gold.dim_variant
UNION ALL SELECT 'dim_date', count(*) FROM gold.dim_date;

Step 02 · Fact

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.

Review before moving on:

  • the fact is a view; 5,951 rows and 5,951 distinct keys of the grain
  • 49 rows without market price
  • the number of prices per date and set grows as in section 6
Reference SQL of step 02
lab/lesson-6/sql/02_fact.sql
-- Lesson 6 · Step 02 · The fact, as a view, and the test of the grain
--
-- Reference of the professor for prompt 02.
--
-- gold.fact_price is a periodic snapshot: one product, in one variant, on
-- one date of capture. Like every object of gold it is a view: it keeps no
-- copy, reads db_ingestion at every query and always shows the last
-- capture that arrived. Its prices are semi-additive: the market price of
-- all the cards of a set on one date adds up to the cost of the set, but
-- adding the same card over several dates means nothing.

CREATE OR REPLACE VIEW gold.fact_price AS
SELECT
    i.timestamp // 86400 * 86400                        AS date_unix,
    CAST(i.data_json->>'productId' AS INTEGER)          AS product_id,
    p.set_id,
    i.data_json->>'subTypeName'                         AS variant,
    CAST(i.data_json->>'marketPrice' AS DECIMAL(10, 2)) AS market_price,
    CAST(i.data_json->>'lowPrice' AS DECIMAL(10, 2))    AS low_price,
    CAST(i.data_json->>'midPrice' AS DECIMAL(10, 2))    AS mid_price,
    CAST(i.data_json->>'highPrice' AS DECIMAL(10, 2))   AS high_price,
    (i.timestamp // 86400 * 86400 - s.released_at) // 86400 AS days_since_release
FROM db_ingestion AS i
JOIN gold.dim_product AS p ON p.product_id = CAST(i.data_json->>'productId' AS INTEGER)
JOIN gold.dim_set     AS s ON s.set_id = p.set_id
WHERE i.data_tag = 'tcgplayer.price.v1';

-- The test of the grain: rows = distinct (date_unix, product, variant).
SELECT count(*) AS rows,
       count(DISTINCT (date_unix, product_id, variant)) AS grain_keys,
       count(*) FILTER (WHERE market_price IS NULL)    AS without_market_price
FROM gold.fact_price;

-- Prices per date and set: the sets released later appear later.
SELECT f.date_unix, d.month, s.set_code, count(*) AS prices
FROM gold.fact_price AS f
JOIN gold.dim_date AS d USING (date_unix)
JOIN gold.dim_set  AS s ON s.set_id = f.set_id
GROUP BY ALL ORDER BY f.date_unix, s.set_code;

Step 03 · Cube and mart

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.

Review before moving on:

  • 524 cells in the eight levels of section 9
  • US$ 18,989.68 on 07/11/2026 and 51,967.84 summed over the dates
  • the cube and the mart are views and read only gold
Reference SQL of step 03
lab/lesson-6/sql/03_cube_and_mart.sql
-- Lesson 6 · Step 03 · The cube and a data mart for collectors, all views
--
-- Reference of the professor for prompt 03.
--
-- The cube is a view too: the whole gold layer is computed at query time
-- from db_ingestion, so it is always current. The cube crosses set, rarity
-- and variant on every date. It groups by
-- set_name and not by set_code, because the code 30C belongs to two sets
-- (ME: 30th Celebration and its Classic Collection): a natural key that
-- repeats would merge them.
--
-- The cube crosses set, rarity and variant on every date (date_unix). Because the price
-- is semi-additive, the date stays in every grouping: GROUP BY date_unix and
-- CUBE of the other three. A cell answers "on this date, how much did the
-- cards of this set, of this rarity, in this variant cost?".

CREATE OR REPLACE VIEW gold.agg_price_cube AS
SELECT
    f.date_unix,
    grouping(s.set_name, p.rarity, f.variant) AS grouping_id,
    coalesce(s.set_name, 'all')               AS set_name,
    coalesce(p.rarity, 'all')                 AS rarity,
    coalesce(f.variant, 'all')                AS variant,
    count(*)                                  AS prices,
    sum(f.market_price)                       AS market_value,
    round(avg(f.market_price), 2)             AS avg_market_price,
    max(f.market_price)                       AS max_market_price
FROM gold.fact_price AS f
JOIN gold.dim_product AS p USING (product_id)
JOIN gold.dim_set     AS s ON s.set_id = f.set_id
WHERE p.kind = 'card' AND f.market_price IS NOT NULL
GROUP BY f.date_unix, CUBE (s.set_name, p.rarity, f.variant);

-- A data mart for the collectors area: friendly names, one view per question.
CREATE SCHEMA IF NOT EXISTS mart_collectors;

CREATE OR REPLACE VIEW mart_collectors.card_price AS
SELECT f.date_unix AS captured_at, d.month, s.set_code, s.set_name, s.released_at,
       p.product_name AS card, p.number, p.rarity, f.variant, f.market_price, f.days_since_release
FROM gold.fact_price AS f
JOIN gold.dim_date    AS d USING (date_unix)
JOIN gold.dim_product AS p USING (product_id)
JOIN gold.dim_set     AS s ON s.set_id = f.set_id
WHERE p.kind = 'card';

CREATE OR REPLACE VIEW mart_collectors.set_value AS
SELECT c.date_unix AS captured_at, d.month, c.set_name, c.prices, c.market_value
FROM gold.agg_price_cube AS c
JOIN gold.dim_date AS d USING (date_unix)
WHERE c.grouping_id = 3;

-- Size of the cube by level.
SELECT grouping_id,
       CASE grouping_id
           WHEN 0 THEN 'set x rarity x variant' WHEN 1 THEN 'set x rarity'
           WHEN 2 THEN 'set x variant'          WHEN 3 THEN 'set'
           WHEN 4 THEN 'rarity x variant'       WHEN 5 THEN 'rarity'
           WHEN 6 THEN 'variant'                WHEN 7 THEN 'all cards' END AS level,
       count(*) AS cells
FROM gold.agg_price_cube
GROUP BY ALL ORDER BY grouping_id;

-- Why the date stays in the grouping: the value of all cards on the last
-- date is meaningful; the sum of that value over the five dates is not.
-- 1794009600 is 2026-11-07 00:00 UTC.
SELECT
    (SELECT market_value FROM gold.agg_price_cube WHERE grouping_id = 7 AND date_unix = 1794009600) AS value_on_2026_11_07,
    (SELECT sum(market_value) FROM gold.agg_price_cube WHERE grouping_id = 7)                    AS sum_over_dates_meaningless;

Step 04 · Frozen and live reports

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.

Review before moving on:

  • two tables frozen in September (1,226 card prices, 5 sets) and two live views
  • Pikachu ex 276/217: 1,049.08 frozen and 571.17 live before the simulated capture
  • 1,049.08 frozen and 600.00 live after it, and the simulated record deleted
Reference SQL of step 04
lab/lesson-6/sql/04_reports.sql
-- Lesson 6 · Step 04 · Reports frozen in time and reports always current
--
-- Reference of the professor for prompt 04.
--
-- The gold layer and the mart are views, so they always show the last
-- capture. A report sometimes has to stay as it was published: the prices
-- of September go to the partner on 01/09 and must not change afterwards.
-- DuckDB has no materialized view; a materialized report is a table built
-- with CREATE TABLE ... AS, which stores the result of that moment and keeps
-- it until someone builds it again. A live report is a normal view.

CREATE SCHEMA IF NOT EXISTS report;

-- Materialized, frozen: what the market looked like in September 2026.
CREATE OR REPLACE TABLE report.mv_card_price_2026_09 AS
SELECT set_name, card, rarity, variant, market_price
FROM mart_collectors.card_price
WHERE month = '2026-09';

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';

-- Normal views, live: always the last capture that arrived.
CREATE OR REPLACE VIEW report.v_card_price_latest AS
SELECT captured_at, set_name, card, rarity, variant, market_price
FROM mart_collectors.card_price
WHERE captured_at = (SELECT max(captured_at) FROM mart_collectors.card_price);

CREATE OR REPLACE VIEW report.v_set_value_latest AS
SELECT captured_at, set_name, prices, market_value
FROM mart_collectors.set_value
WHERE captured_at = (SELECT max(captured_at) FROM mart_collectors.set_value);

-- Before: the Pikachu ex 276/217 in the frozen report and in the live one.
SELECT 'before' AS moment,
       (SELECT market_price FROM report.mv_card_price_2026_09 WHERE card = 'Pikachu ex - 276/217') AS frozen_september,
       (SELECT market_price FROM report.v_card_price_latest  WHERE card = 'Pikachu ex - 276/217') AS live_latest,
       (SELECT max(captured_at) FROM report.v_card_price_latest)                                   AS live_captured_at;

-- A new capture arrives in the landing table. This record is SIMULATED for
-- the demonstration: a price of US$ 600.00 on 2026-11-10 12:00 UTC.
INSERT INTO db_ingestion VALUES (
    1794312000,
    '{"productId":676088,"lowPrice":560.0,"midPrice":690.0,"highPrice":5000.0,"marketPrice":600.0,"directLowPrice":null,"subTypeName":"Holofoil"}',
    'tcgplayer.price.v1');

-- After: the view followed the new capture; the materialized report did not.
SELECT 'after' AS moment,
       (SELECT market_price FROM report.mv_card_price_2026_09 WHERE card = 'Pikachu ex - 276/217') AS frozen_september,
       (SELECT market_price FROM report.v_card_price_latest  WHERE card = 'Pikachu ex - 276/217') AS live_latest,
       (SELECT max(captured_at) FROM report.v_card_price_latest)                                   AS live_captured_at;

-- Remove the simulated capture, so that the next steps use only real data.
DELETE FROM db_ingestion WHERE timestamp = 1794312000;

-- What each object of the model keeps.
SELECT schema_name, table_name AS object, 'table (materialized)' AS kind, estimated_size AS rows
FROM duckdb_tables() WHERE schema_name IN ('gold', 'mart_collectors', 'report')
UNION ALL
SELECT schema_name, view_name, 'view (computed at every read)', NULL
FROM duckdb_views() WHERE schema_name IN ('gold', 'mart_collectors', 'report') AND NOT internal
ORDER BY schema_name, kind, object;

Step 05 · Five questions

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.

Review before moving on:

  • the five answers of section 15
  • no query reads db_ingestion
  • Q5 compares the same card and variant on two dates
Reference SQL of step 05
lab/lesson-6/sql/05_questions.sql
-- Lesson 6 · Step 05 · Five questions, one OLAP operation each
--
-- Reference of the professor for prompt 05. Every question reads the cube or
-- the mart, never db_ingestion.

-- Q1 · Roll-up: from the card to the rarity. On 07/11/2026, how much is
--      the average card of each rarity worth?
SELECT rarity, prices, avg_market_price, max_market_price
FROM gold.agg_price_cube
WHERE date_unix = 1794009600 AND grouping_id = 5   -- 2026-11-07
ORDER BY avg_market_price DESC;

-- Q2 · Slice: one set. Which are the five most expensive cards of
--      Ascended Heroes on 07/11/2026?
SELECT card, rarity, variant, market_price
FROM mart_collectors.card_price
WHERE set_code = 'ASC' AND captured_at = 1794009600   -- 2026-11-07
ORDER BY market_price DESC LIMIT 5;

-- Q3 · Pivot: sets as rows, dates as columns. How did the market value of
--      one copy of every card of each set change? (semi-additive: it adds
--      cards inside a date, never dates)
PIVOT (SELECT set_name, month, market_value FROM mart_collectors.set_value)
ON month USING sum(market_value)
GROUP BY set_name
ORDER BY set_name;

-- Q4 · Dice and pivot: the four lowest rarities, the three variants, the
--      last date. How much does each printing of the same rarity cost?
PIVOT (SELECT rarity, variant, avg_market_price
       FROM gold.agg_price_cube
       WHERE date_unix = 1794009600 AND grouping_id = 4   -- 2026-11-07
         AND rarity IN ('Common', 'Uncommon', 'Rare', 'Double Rare'))
ON variant IN ('Normal', 'Reverse Holofoil', 'Holofoil') USING max(avg_market_price)
GROUP BY rarity
ORDER BY rarity;

-- Q5 · The question of the session. Which cards appreciated most between
--      their first capture and 07/11/2026? Cards that cost at least US$ 5 at
--      the first capture, so that a few cents do not become 100 %.
WITH first_and_last AS (
    SELECT set_code, card, rarity, variant,
           arg_min(market_price, captured_at) AS first_price,
           min(captured_at)                   AS first_captured_at,
           arg_max(market_price, captured_at) AS last_price
    FROM mart_collectors.card_price
    WHERE market_price IS NOT NULL
    GROUP BY ALL
    HAVING count(*) >= 2
)
SELECT set_code, card, rarity, variant, first_captured_at, first_price, last_price,
       last_price - first_price                         AS gain_usd,
       round(100 * (last_price / first_price - 1), 1)  AS gain_pct
FROM first_and_last
WHERE first_price >= 5
ORDER BY gain_pct DESC
LIMIT 10;

15. The results of steps 04 and 05

Step 04 · The frozen and the live report

The reports of September keep 1,226 card prices and the value of 5 sets. Before the simulated capture, the Pikachu ex 276/217 is worth US$ 1,049.08 in the frozen report and US$ 571.17 in the live one, captured at 1794009600 (07/11/2026). After a simulated record with timestamp 1794312000 (10/11/2026 at noon UTC) and US$ 600.00 enters the landing table, the live report shows US$ 600.00 captured at 1794268800 and the frozen report still US$ 1,049.08; the simulated record is then deleted. The frozen report also shows that the card peaked in September, at more than twice its price of March, a value that no live view of November displays.

The five questions of step 05 were chosen so that each one exercises a different operation over the cube, and each one reads the cube or the mart, never the landing table. The prices are market prices of TCGplayer in US dollars.

Q1 · Roll-up: the value of a rarity

On 07/11/2026 the average card of each rarity is worth, from the most to the least valuable:

RarityPricesAverage US$Maximum US$
RGB Rare33,973.484,492.45
Mega Hyper Rare6160.91284.88
Special Illustration Rare5676.32614.27
Futuristic Rare230.3634.70
Classic Collection3020.71132.76
Mega Attack Rare710.1531.13
Illustration Rare984.6040.65
Ultra Rare852.9413.76
Double Rare900.987.66
Pikachu Rare300.732.96
Rare1810.261.95
Uncommon3910.221.36
Common6480.200.81

Q2 · Slice: the top of Ascended Heroes

CardRarityVariantUS$ on 07/11/2026
Mega Gengar ex - 284/217Special Illustration RareHolofoil614.27
Pikachu ex - 276/217Special Illustration RareHolofoil571.17
Mega Dragonite ex - 290/217Special Illustration RareHolofoil402.35
Pikachu ex - 277/217Special Illustration RareHolofoil243.04
Mega Charizard Y ex - 294/217Mega Hyper RareHolofoil223.84

Q3 · Pivot: the value of each set on each date

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

Every set loses value after its release; Ascended Heroes peaks in May and ends at 59 % of its value in March. The apparent ninefold rise of the 30th Celebration is coverage and not appreciation: on 01/09 most of its cards had no market price yet, and its three RGB Rare cards, worth about US$ 4,000 each, entered the sum later.

Q4 · Dice and pivot: the printings of four rarities

Rarity · 07/11/2026NormalReverse HolofoilHolofoil
Common0.150.250.18
Uncommon0.160.28
Rare0.320.20
Double Rare0.98

A Reverse Holofoil costs about 1.7 times the Normal print of a Common or an Uncommon. An empty cell means that the rarity is not printed in that variant.

Q5 · The question of the session

SetCardFirst capture (Unix)First US$07/11 US$Gain US$Gain %
ASCPikachu ex - 276/217 (Holofoil)1772323200480.58571.17+90.59+18.9
PBLCrushing Hammer (Holofoil)17882208005.204.37−0.83−16.0
PBLMega Zeraora ex - 098/084 (Holofoil)17882208006.695.61−1.08−16.1
ASCPikachu ex - 277/217 (Holofoil)1772323200327.88243.04−84.84−25.9
ASCMega Dragonite ex - 290/217 (Holofoil)1772323200574.74402.35−172.39−30.0

Among the 137 cards that cost at least US$ 5 on their first capture and have at least two captures, only the Pikachu ex 276/217 of Ascended Heroes appreciated, by 18.9 % and US$ 90.59; every other card lost value, which is the usual path of a set in the months after its release. The threshold of US$ 5 keeps out the cards of a few cents, whose percentages are large and meaningless. The same query, with a longer window or a lower threshold, answers the question again as new captures are added to the landing table.

16. Recurring mistakes of agents

The traps below were found while the lab was rehearsed on 07/11/2026, and the prompts already carry the corresponding adjustments. Most of them do not raise an error and are caught only by a count or by one specific number, which is why each prompt states the facts measured in the rehearsal.

Reading the JSON

Inside a macro or a lambda of DuckDB the operator -> is read as the arrow of a lambda, and a macro written as j->'extendedData' fails with an error about a column that does not exist. The attribute must be read with json_extract(j, '$.extendedData') and the lambda written with the syntax lambda e: .... An agent that treats extendedData as an object, and not as a list of pairs, returns NULL for every rarity without any error.

Keys and joins

The fact and dim_product both carry set_id, and a chain of joins with USING (set_id) after USING (product_id) is ambiguous; the set must be joined with ON s.set_id = f.set_id. An agent that groups the cube by set_code merges the two sets with the code 30C silently, which is visible only in the value of the set.

Measures

An agent used to warehouses tends to write the fact and the cube as tables; the prompts ask for views, and only the reports of step 04 store data. The most frequent error of the cube is to leave the date out of the grouping, or to sum the level "all cards" over the dates, which returns US$ 51,967.84 instead of a value on one date. In Q5, comparing the value of a set between two dates confuses appreciation with coverage; the comparison must be the same card and variant, with arg_min and arg_max of the price by date. An average of rarity computed by averaging the averages of the sets gives a different and wrong number, because the sets have different numbers of cards.

The lab

The lab runs DuckDB 1.4, not the 2.0 of the command line of Lesson 5, and an agent that writes for 2.0, or that uses read_json, COPY or files, writes SQL that does not run in the browser. A statement that fails stops the script, and the statements before it are already kept in the localStorage, so the script can be corrected and run again from the failed statement.

Part VSecond hour

17. Your data in ClickHouse

In the second hour each group repeats the four steps over the partner data, in the ClickHouse of the class (shrek2, console at http://10.8.8.10:8123/play, user aluno), where the user reads silver and gold and creates objects only in the database lab. As in Lesson 5, every object of the group starts with its prefix, lab.g01_ for group 1, and no object of another group may be dropped.

The group first creates lab.gNN_db_ingestion with the three columns of the landing table and loads into it the enriched partner data of Lesson 5. The console of ClickHouse runs one statement at a time and does not upload files, so the load is done from the computer of the group, with clickhouse-connect in Python or with an INSERT ... FORMAT JSONEachRow sent over HTTP, in which data_json goes as a string with the record inside it.

Landing table and load of the group (replace g01)
CREATE TABLE IF NOT EXISTS lab.g01_db_ingestion (
    timestamp Int64,                -- Unix time, seconds, UTC
    data_json String,
    data_tag  LowCardinality(String)
) ENGINE = MergeTree ORDER BY (data_tag, timestamp);

-- one JSON object per line: {"timestamp":1794312000,"data_json":"{...}","data_tag":"partner.order.v1"}
curl -u aluno:aluno 'http://10.8.8.10:8123/?query=INSERT%20INTO%20lab.g01_db_ingestion%20FORMAT%20JSONEachRow' \
     --data-binary @db_ingestion.jsonl

The model follows the same decisions of the first hour, with the syntax of ClickHouse: the whole gold layer of the group is views, and only a report of a closed month is materialized. The table below lists the equivalences that the agent of the group needs; the prompt 06 already carries them.

In the lab (DuckDB)In ClickHouse
data_json->>'field'JSONExtractString(data_json, 'field'), JSONExtractFloat, JSONExtractInt
viewview
view for dimensions, fact and cubeview for dimensions, fact and cube
frozen report with CREATE TABLE ASCREATE TABLE ... ENGINE = MergeTree ORDER BY ... AS SELECT
dates in Unix time: timestamp // 86400 * 86400; label with epoch_ms(timestamp * 1000)intDiv(timestamp, 86400) * 86400; label with formatDateTime(toDateTime(timestamp, 'UTC'), '%Y-%m')
GROUP BY date_unix, CUBE (a, b, c)the same, or GROUP BY ... WITH CUBE; check that grouping() returns 0 at the finest level
PIVOTsumIf or maxIf per column
arg_min / arg_maxargMin / argMax
count(DISTINCT x)uniqExact(x)

18. Prompt 06 and the delivery

The prompt of the second hour asks the agent of the group for the specification first and stops there, so that the group reviews the grain, the measures and the five questions of the partner before any SQL reaches the shared server. Only after that review does the group ask for the SQL files.

Prompt 06 · CREATE · your data in ClickHouse
[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.
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>) 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 belong to the groupSELECT name, engine FROM system.tables WHERE database = 'lab' AND name LIKE 'gNN_%'views, materialized views and tables of the model
the questions are answereddocs/answers.mdfive answers, each with its query and operation

The specification and the cube enter the Data Ingestion Structure artifact of the sprint as the analytical layer that the DataApp will read, and the five questions of the partner become the first indicators of its dashboard.

19. Glossary

TermMeaning in this lesson
landing tabledb_ingestion: every record as it arrived, with the moment and the kind
grainthe exact meaning of one row of a fact table
periodic snapshota fact with one row per entity per period, recording a state
semi-additivea measure that adds up across every dimension except time
data cubea measure organised by several dimensions, with the totals of each one
summarised fact tablea fact table with a coarser grain, computed from the base fact
materialized reporta stored result of one moment, kept as published; in DuckDB a table from CREATE TABLE AS
CUBE / ROLLUP / GROUPING SETSextensions of GROUP BY that compute several groupings at once
grouping()function that says which columns of a row were aggregated
data martthe part of the warehouse that serves one area of the business
conformed dimensiona dimension with the same keys and meaning in every fact that uses it
natural keyan identifier that comes from the source, such as the code of a set
localStoragethe key-value storage of the browser, about 5 MB per site

20. Checklist

  • The grain is declared in one sentence before any SQL.
  • The whole gold layer (dimensions, fact and cube) and the mart are views over the landing table.
  • The hierarchies of the dimensions are written in the specification.
  • A report of a closed period is materialized once; a report of the current state is a view.
  • No natural key that repeats is used as an identity.
  • The grain test returns the same number of rows and of distinct keys.
  • Every measure is classified as additive, semi-additive or non-additive.
  • The cube keeps the time dimension in every grouping when a measure is semi-additive.
  • Distinct counts and averages are computed by the cube, never by summing finer cells.
  • The mart reads the gold layer and never the landing table.
  • Each of the five questions names its OLAP operation and its query.

21. References and self-study

  • KIMBALL, R.; ROSS, M. The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling. 3. ed. Indianapolis: Wiley, 2013. Chapters 1 to 4: the four decisions, kinds of fact, additivity and conformed dimensions.
  • GRAY, J. et al. Data cube: a relational aggregation operator generalizing group-by, cross-tab, and sub-totals. Data Mining and Knowledge Discovery, v. 1, p. 29–53, 1997. The origin of the CUBE operator.
  • DuckDB. GROUPING SETS, CUBE and ROLLUP; PIVOT; JSON functions. Documentation at duckdb.org.
  • ClickHouse. GROUP BY modifiers (WITH CUBE, WITH ROLLUP, GROUPING SETS); refreshable materialized views. Documentation at clickhouse.com/docs.
  • tcgcsv.com. Daily mirror of the catalogue and the prices of TCGplayer, with archive of past prices.
  • Self-study 1: What is OLAP? (IBM, 60 min).
  • Self-study 2: OLAP Cubes: Unleashing Multi-Dimensional Data Insights (video, 30 min).
  • Self-study 3: What is a Data Mart? (AltexSoft, 60 min).