Dynamic PricingClickHouse Workshops

01 Understand the retail chain

Load retail history and query chain-wide sales in ClickHouse.

Your computer
macOS terminal: Run workshop commands in Terminal using zsh or bash.

Outcome

Load 100 million synthetic sales lines for 5,000 stores and 20 perishable SKUs. Find which districts sell the most units and record your first query measurement.

Starting point

Complete Module 00. Keep SQL console and your workshop terminal open.

Rows, baskets, and money

A row is a transaction line. A basket can contain several lines, so row count is not transaction count. uniqExact(transaction_id) counts baskets. Returns have negative quantities and amounts. Monetary columns store SGD cents: 800 means SGD 8.00. These 20 products represent the perishable category, not the retailer's full catalog.

The branch column labels a simulated sales path. This history uses branch = 'applied', the path included in chain totals. Later price experiments add comparison rows for a hypothetical unchanged price. Module 02 explains both labels with a diagram.

Your data schema across the workshop

Use this map as a reference while you progress. Module 01 loads sales and reference data; Module 02 adds live ingestion and aggregates. Modules 03–05 query the pricing views. Setup and initialization prepare several of these objects for you; follow each module's actions rather than creating everything in this diagram now.

Workshop schema: sales staging activates into retail_sales; two materialized views populate minute aggregate tables. Five reference and model tables and six Postgres CDC destinations support current-state, context, opportunity, price-comparison, and receipt-scoped outcome views.

How to read the map:

  • Stored tables hold transaction lines, reference data, model parameters, replicated operational records, or aggregate states. retail_sales_console is the manual import staging table; registration activates its loaded data as retail_sales without inserting it again. Live sales also go directly into retail_sales.
  • Incremental materialized views run when new blocks enter retail_sales. retail_sales_minute_mv writes store/SKU/minute states to retail_sales_minute; retail_district_minute_mv writes district/SKU/minute states to retail_district_minute. Module 02 backfills the existing history separately, then uses sumMerge and uniqExactMerge to query the states.
  • Query-time views compute results when queried. The current-state views expose the latest non-deleted CDC values. retail_analysis_context identifies a complete sales cutoff. retail_opportunities combines sales, reference data, and versioned operational evidence at that cutoff; retail_price_comparison expands ready opportunities into permitted-price forecasts. After approval, retail_outcome_series calculates running totals from receipt-linked sales and CDC evidence.

The workbench and pricing agent use the same analytical views that you query in SQL console. These views do not apply a price; the workbench commits your approved change in Managed Postgres.

IdentifierWhat it connects
store_id / district_idSales and operational records to the store catalog and district grouping.
sku / store_groupA product and store group to the prepared price-response parameters.
run_idLive sales, operational evidence, and receipts for one synthetic workshop run.
batch_id / sequenceSales delivery to batch acknowledgements and the operational versions valid at a cutoff.
receipt_idAn approved price change to its subsequent applied-price and unchanged-price sales.
Application tables in Managed Postgres

The six replicated source tables appear in the diagram. The backend also uses retail_state for current stock and prices, retail_proposals for prices awaiting approval, retail_comparisons for the two simulated stock balances, retail_return_claims to track returns, and retail_history_state to track import and aggregate registration. The application manages these tables; the analytical exercises use their relevant evidence in ClickHouse.

Actions

1. Select the workshop dataset

Set this line in your private app/.env.workshop:

PRICING_RETAIL_DATASET_MANIFEST=https://s3.ap-southeast-1.amazonaws.com/partner-workshop/dynamic-pricing/retail-chain-v2/2026-10-16/showcase/manifest.json

The metadata file lists files, checksums, and expected totals. Both loading methods below use this same dataset. No AWS login is needed to read the public files.

2. Open SQL console

Open your ClickHouse Cloud service, select SQL console, and select pricing as the database. Paste one statement at a time and select Run.

SQL console showing the database selector, SQL editor, Run button, and result panel

The screenshot shows the controls; use the retail SQL below for this workshop.

3. Create and load the sales table

3.1. Create the table

Run the following schema. Setup may already have created the empty staging table; IF NOT EXISTS makes this step repeatable.

CREATE TABLE IF NOT EXISTS pricing.retail_sales_console (
    event_id UUID, transaction_id UUID, line_number UInt16 DEFAULT 1,
    store_id UInt16, district_id UInt16, sku UInt32,
    quantity Int32, price_minor Int64, receipts_minor Int64, sold_cost_minor Int64,
    event_time DateTime64(3, 'UTC'), original_event_id UUID DEFAULT toUUID('00000000-0000-0000-0000-000000000000'),
    receipt_id UUID DEFAULT toUUID('00000000-0000-0000-0000-000000000000'),
    run_id UUID DEFAULT toUUID('00000000-0000-0000-0000-000000000000'), batch_id UUID DEFAULT toUUID('00000000-0000-0000-0000-000000000000'), sequence UInt64 DEFAULT 0,
    branch LowCardinality(String) DEFAULT 'applied', source LowCardinality(String) DEFAULT 'history',
    price_version UInt64 DEFAULT 1, emitted_at DateTime64(3, 'UTC') DEFAULT now64(3)
) ENGINE = MergeTree
PARTITION BY toYYYYMM(event_time)
ORDER BY (district_id, toDate(event_time), store_id, sku, event_time, event_id);

Choose a sort key for your questions

MergeTree stores columnar data. The sort key starts with district and date, matching the first chain-level filters. Store and SKU support further drilldown. Monthly partitions group data for storage management. ORDER BY is not a uniqueness constraint.

3.2. Load Parquet from S3

Run this once into the empty staging table. The ClickHouse server reads the files directly; your browser does not download 100 million rows. s3_throw_on_zero_files_match requires at least one matching file and reports an error if the S3 path is empty.

INSERT INTO pricing.retail_sales_console
(event_id, transaction_id, line_number, store_id, district_id, sku, quantity,
 price_minor, receipts_minor, sold_cost_minor, event_time, original_event_id)
SELECT event_id, transaction_id, line_number, store_id, district_id, sku, quantity,
 price_minor, receipts_minor, sold_cost_minor, event_time, original_event_id
FROM s3('https://s3.ap-southeast-1.amazonaws.com/partner-workshop/dynamic-pricing/retail-chain-v2/2026-10-16/showcase/sales-*.parquet', NOSIGN, 'Parquet')
SETTINGS s3_throw_on_zero_files_match = 1;

3.3. Check the loaded rows

SELECT count() AS sales_lines, uniqExact(transaction_id) AS transactions,
 sum(quantity) AS net_units, sum(receipts_minor) / 100 AS receipts_sgd
FROM pricing.retail_sales_console;

Expect these totals:

Sales linesTransactionsNet unitsReceipts (SGD)
100,000,00051,000,00098,000,000985,422,100

A sales line is one product entry in a transaction. sum(quantity) includes negative return quantities, so net units differ from the line count.

3.4. Register the completed import

In your terminal, run:

.venv/bin/workshop retail-register-history

This verifies the loaded totals and catalog/time bounds, activates the table as pricing.retail_sales, and loads store, product, and availability reference data. It does not insert the sales rows again.

4. Query the chain

Run this in SQL console:

SELECT district_id, sum(quantity) AS net_units,
 sum(receipts_minor) / 100 AS receipts_sgd,
 uniqExact(transaction_id) AS transactions
FROM pricing.retail_sales
WHERE branch = 'applied'
GROUP BY district_id
ORDER BY receipts_sgd DESC;

Record the highest-revenue district, elapsed time, and rows read from the query details. Change the query to filter district_id = 1 before GROUP BY, then compare rows read.

What the query demonstrates

ClickHouse reads the selected columns and aggregates across the chain. District filtering can skip ranges in the sorted data. Module 02 adds pre-aggregation and measures the same facts through a smaller table.

5. Initialize and view the chain

.venv/bin/workshop retail-initialize
docker compose --env-file app/.env.workshop -f app/docker-compose.workshop.yml -f app/docker-compose.cloud.yml up --build --detach --wait

Initialization installs the prepared model and creates opening inventory and price policies in managed Postgres. Repeating this command reuses the current run. For a later workshop session, the fresh-scenario instructions in Module 02 create new opening stock while preserving your loaded history. Open http://localhost:8080 and select Start learner session. Overview shows historical chain totals and district activity. This is your reference before live sales and price changes. A zero live ingestion rate is expected until Module 02 starts the writer.

Verify

Your historical table contains 100 million lines. You can distinguish lines from baskets, identify a high-revenue district, and explain why a district filter affects the scan.

Next: Ingest sales and accelerate queries.

このページの内容

Track your progress?

Optional. We email a link to confirm your address; progress records once you open it.

Please use your work email address, not a personal one.

By continuing you accept the Terms.

JA