Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Lab: Pruning, Clustering and Cost per Query

Store the same 1.8 million events in three layouts, dry-run a fixed query set to measure files and bytes scanned, log every run in a query history table, and cut cost with partitioning, clustering, column selection, a materialised summary and a right-sized engine.

Contentsand lesson path

What you will learn

  • Reduce query cost and latency with partitioning or clustering, pruning, materialized results and right-sized compute, verified with query history.

01. Goal and setup

On a warehouse that bills by bytes scanned, the layout of a table decides the bill. Tuning is only real if you can show it, so in this lab every change is measured the way a platform team would measure it: with a dry run that reports what a query will read, and a query history table that records each run.

A dry run asks the planner which files and columns a query needs without running it; BigQuery offers one, and here PyIceberg plays that role. The numbers it gives are the same on every machine, because they come from the table metadata. DuckDB then runs each query so you can check the answers. You need the tools from Lab: One Lakehouse Table, Two Query Engines: Python 3.10+, pyiceberg[sql-sqlite,pyarrow,pyiceberg-core]==0.12.0 and duckdb==1.5.6, plus pyarrow 26.0.1, which byte sizes depend on. Allow about 250 MB of disk.

Terminal
mkdir tuning-lab && cd tuning-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "pyiceberg[sql-sqlite,pyarrow,pyiceberg-core]==0.12.0" \
  "duckdb==1.5.6" "pyarrow==26.0.1"

02. Step 1: One dataset, three layouts

Save the small helper lab.py, then build_tables.py. The script generates 1.8 million web events over 90 days with arithmetic, so everyone gets the same rows, and writes them three times. web.flat has no partitioning and its rows are shuffled, as happens after years of late data and merges. web.by_day is partitioned by day: each day's rows are in their own files. web.clustered is also partitioned by day, and inside each day the rows are clustered, meaning sorted and split by customer_id, so each of the four files per day covers one quarter of the customers. Managed warehouses do this for you with clustering keys; here you sort the data yourself before writing, because PyIceberg writes rows in the order you give them.

Python · lab.py
"""Shared catalog settings for the lab scripts."""
from pathlib import Path

from pyiceberg.catalog.sql import SqlCatalog


def open_catalog():
    Path("warehouse").mkdir(exist_ok=True)
    return SqlCatalog("lab", uri="sqlite:///catalog.db",
                      warehouse=f"file://{Path('warehouse').resolve()}")
Python · build_tables.py
"""Write the same 1.8 million events into three Iceberg tables, three layouts."""
import duckdb
from pyiceberg.transforms import DayTransform

from lab import open_catalog

EVENTS = """
SELECT i AS event_id,
       TIMESTAMP '2026-08-01' + to_microseconds(i * 4320000) AS event_ts,
       CAST(TIMESTAMP '2026-08-01' + to_microseconds(i * 4320000) AS DATE)
         AS event_date,
       CAST(i * 7919 % 1000 + 1 AS INTEGER) AS customer_id,
       ['DE', 'FR', 'VN', 'BR', 'US'][i * 31 % 5 + 1] AS country,
       CAST(i * 37 % 10000 / 100 AS DECIMAL(10, 2)) AS amount,
       md5(CAST(i AS VARCHAR)) AS session_id
FROM range(1800000) AS t(i)
"""
catalog = open_catalog()
catalog.create_namespace_if_not_exists("web")
con = duckdb.connect()
events = con.sql(EVENTS).to_arrow_table()

# A: no partitioning, rows in random order, six files.
flat = catalog.create_table("web.flat", events.schema)
shuffled = con.sql(EVENTS + " ORDER BY md5(CAST(i * 3 AS VARCHAR))").to_arrow_table()
for part in range(6):
    flat.append(shuffled.slice(part * 300000, 300000))

# B: partitioned by day, customers in arrival order within each day.
def create_by_day(name):
    table = catalog.create_table(name, events.schema)
    with table.update_spec() as spec:
        spec.add_field("event_date", DayTransform(), "event_date_day")
    return table


day = create_by_day("web.by_day")
day.append(events)

# C: partitioned by day and clustered: each day holds four files, one per
#    customer range, so a file's min/max customer_id covers only a quarter.
clustered = create_by_day("web.clustered")
for low in (1, 251, 501, 751):
    chunk = con.sql(EVENTS).filter(f"customer_id BETWEEN {low} AND {low + 249}")
    clustered.append(chunk.order("event_date, customer_id").to_arrow_table())

for name in ("flat", "by_day", "clustered"):
    t = catalog.load_table(f"web.{name}")
    files = list(t.scan().plan_files())
    mib = sum(f.file.file_size_in_bytes for f in files) / 2**20
    print(f"web.{name:<10} {len(files):>4} files {mib:7.1f} MiB")
Terminal
python build_tables.py
Expected output
web.flat          6 files    60.8 MiB
web.by_day       90 files    48.5 MiB
web.clustered   360 files    54.3 MiB

The shuffled table is the largest. Parquet compresses a column better when similar values sit next to each other, so the order of the rows changes the size of the files, and therefore the bytes you pay to read them.

03. Step 2: Dry run, run, record

history.py holds a fixed query set: the same questions, asked the same way, every time you test a layout. For each run it asks PyIceberg to plan the scan, then adds up column_sizes, the compressed bytes per column that Iceberg records for every data file, for only the columns the query uses. That is how warehouses that bill by bytes count: by the columns referenced in the partitions and blocks they cannot skip, not by the rows returned. It converts bytes to a cost with a made-up price of $5 per TiB, multiplies by 10,000 runs to make the numbers readable, runs the query in DuckDB, and appends one row to query_history in history.duckdb. report.sql prints the history.

Python · history.py
"""Dry-run a query on one layout, run it in DuckDB, record it in the history."""
import sys
import time

import duckdb

from lab import open_catalog

PRICE_PER_TIB = 5.00        # a made-up on-demand price, for comparing layouts only
QUERIES = {
    "last_7_days": ("event_date >= '2026-10-23'", ("event_date", "country", "amount"),
                    "SELECT event_date, country, sum(amount) FROM t"
                    " WHERE event_date >= DATE '2026-10-23' GROUP BY ALL"),
    "one_customer": ("customer_id == 77", ("event_ts", "customer_id", "amount"),
                     "SELECT event_ts, amount FROM t WHERE customer_id = 77"),
    "week_star": ("event_date >= '2026-10-23'", None,
                  "SELECT * FROM t WHERE event_date >= DATE '2026-10-23'"),
    "last_7_days_mv": ("event_date >= '2026-10-23'",
                       ("event_date", "country", "revenue"),
                       "SELECT event_date, country, sum(revenue) FROM t"
                       " WHERE event_date >= DATE '2026-10-23' GROUP BY ALL"),
}
catalog = open_catalog()
history = duckdb.connect("history.duckdb")
history.execute("""CREATE TABLE IF NOT EXISTS query_history (
    run_id INTEGER, query VARCHAR, layout VARCHAR, files INTEGER,
    mib_scanned DOUBLE, usd_per_10k_runs DOUBLE, result_rows BIGINT,
    seconds DOUBLE)""")


def dry_run(table, row_filter, columns):
    """Files and bytes the planner says this query must read (like a dry run)."""
    names = columns or tuple(f.name for f in table.schema().fields)
    ids = [table.schema().find_field(n).field_id for n in names]
    files = list(table.scan(row_filter=row_filter, selected_fields=names).plan_files())
    size = sum(task.file.column_sizes[i] for task in files for i in ids)
    return len(files), size


def run(query, layout):
    row_filter, columns, sql = QUERIES[query]
    table = catalog.load_table(f"web.{layout}")
    files, size = dry_run(table, row_filter, columns)
    con = duckdb.connect()
    con.execute("LOAD iceberg")
    con.execute("CREATE VIEW t AS SELECT * FROM iceberg_scan("
                f"'{table.metadata_location}')")
    start = time.perf_counter()
    rows = len(con.sql(sql).fetchall())
    seconds = time.perf_counter() - start
    run_id = history.execute("SELECT count(*) + 1 FROM query_history").fetchone()[0]
    history.execute("INSERT INTO query_history VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                    [run_id, query, layout, files, size / 2**20,
                     size / 2**40 * PRICE_PER_TIB * 10_000, rows, seconds])


if __name__ == "__main__":
    for layout in sys.argv[2:]:
        run(sys.argv[1], layout)
SQL · report.sql
SELECT run_id, query, layout, files, round(mib_scanned, 3) AS mib,
       round(usd_per_10k_runs, 3) AS usd_10k, result_rows AS rows
FROM query_history ORDER BY run_id;

Start with the dashboard question, revenue per country per day for the last 7 days, on the flat table and on the partitioned one. The report function is just a short way to print the history.

Terminal
report() { python -c "import duckdb; print(duckdb.connect('history.duckdb')\
  .sql(open('report.sql').read()))"; }
python history.py last_7_days flat by_day
report
Expected output
┌────────┬─────────────┬─────────┬───────┬────────┬─────────┬───────┐
│ run_id │    query    │ layout  │ files │  mib   │ usd_10k │ rows  │
│ int32  │   varchar   │ varchar │ int32 │ double │ double  │ int64 │
├────────┼─────────────┼─────────┼───────┼────────┼─────────┼───────┤
│      1 │ last_7_days │ flat    │     6 │  5.222 │   0.249 │    35 │
│      2 │ last_7_days │ by_day  │     7 │  0.204 │    0.01 │    35 │
└────────┴─────────────┴─────────┴───────┴────────┴─────────┴───────┘

Same 35 result rows, 25 times fewer bytes. On flat, every file holds some rows from every day, so the planner must read all six. On by_day, it keeps the 7 files whose partition value is on or after 23 October and skips the other 83 without opening them; this is partition pruning. It only works when the planner can compare your filter with the partition values. BigQuery, for example, prunes when the partition column stands alone on one side of the comparison or sits inside one of a short list of supported functions; other functions around the column make it scan every partition. Engines differ: in our tests DuckDB still pruned Hive folders when the date was wrapped in strftime. A dry run is how you find out for your engine.

04. Step 3: Clustering for a second access pattern

Support agents look up one customer across all 90 days. Partitioning by day cannot help, because the filter is on customer_id. Compare by_day and clustered.

Terminal
python history.py one_customer by_day clustered
report
Expected output
┌────────┬──────────────┬───────────┬───────┬────────┬─────────┬───────┐
│ run_id │    query     │  layout   │ files │  mib   │ usd_10k │ rows  │
│ int32  │   varchar    │  varchar  │ int32 │ double │ double  │ int64 │
├────────┼──────────────┼───────────┼───────┼────────┼─────────┼───────┤
│      1 │ last_7_days  │ flat      │     6 │  5.222 │   0.249 │    35 │
│      2 │ last_7_days  │ by_day    │     7 │  0.204 │    0.01 │    35 │
│      3 │ one_customer │ by_day    │    90 │ 10.304 │   0.491 │  1800 │
│      4 │ one_customer │ clustered │    90 │  3.845 │   0.183 │  1800 │
└────────┴──────────────┴───────────┴───────┴────────┴─────────┴───────┘

Both plans read 90 files, but they are not the same files. In by_day, every file contains customers 1 to 1,000, so its minimum and maximum customer_id always include 77. In clustered, only the file for customers 1 to 250 in each day can contain 77; the planner skips the other 270 files using the min and max values stored in the manifests. That is what clustering buys you: a second column that prunes well, without creating a partition per customer. Partitioning by day and customer instead would create 90,000 tiny partitions here, and many small files are slow to plan and to read.

05. Step 4: SELECT star costs more than you think

Run the 7-day question once more, but with SELECT *, as someone exploring the table might.

Terminal
python history.py week_star by_day
report
Expected output
┌────────┬──────────────┬───────────┬───────┬────────┬─────────┬────────┐
│ run_id │    query     │  layout   │ files │  mib   │ usd_10k │  rows  │
│ int32  │   varchar    │  varchar  │ int32 │ double │ double  │ int64  │
├────────┼──────────────┼───────────┼───────┼────────┼─────────┼────────┤
│      1 │ last_7_days  │ flat      │     6 │  5.222 │   0.249 │     35 │
│      2 │ last_7_days  │ by_day    │     7 │  0.204 │    0.01 │     35 │
│      3 │ one_customer │ by_day    │    90 │ 10.304 │   0.491 │   1800 │
│      4 │ one_customer │ clustered │    90 │  3.845 │   0.183 │   1800 │
│      5 │ week_star    │ by_day    │     7 │  3.748 │   0.179 │ 140000 │
└────────┴──────────────┴───────────┴───────┴────────┴─────────┴────────┘

The same 7 files, but 18 times the bytes of run 2, almost all of it the session_id column: 32 random hexadecimal characters per row that compress badly. Columnar storage only saves money when the query names the columns it needs. On a warehouse that bills by bytes scanned, adding LIMIT 10 would not change the bill either: the limit trims the rows returned, not the columns and partitions read.

06. Step 5: Materialise the dashboard query

The dashboard runs the 7-day query every few minutes, but the events change only once a day. Compute the answer once per load instead: materialize.py builds a 450-row summary of revenue per day and country, and replaces it on each refresh. A warehouse materialised view does the same, and some engines refresh it for you when the base table changes.

Python · materialize.py
"""Pre-compute daily revenue per country once, as a small summary table."""
import duckdb
from pyiceberg.exceptions import NoSuchTableError

from lab import open_catalog

catalog = open_catalog()
source = catalog.load_table("web.by_day")
con = duckdb.connect()
con.execute("LOAD iceberg")
summary = con.sql(f"""
    SELECT event_date, country, sum(amount) AS revenue, count(*) AS orders
    FROM iceberg_scan('{source.metadata_location}')
    GROUP BY ALL ORDER BY ALL""").to_arrow_table()
try:
    catalog.load_table("web.daily_revenue").overwrite(summary)   # a refresh
except NoSuchTableError:
    catalog.create_table("web.daily_revenue", summary.schema).append(summary)
print(f"web.daily_revenue: {summary.num_rows} rows,"
      " built from web.by_day")
Terminal
python materialize.py
python history.py last_7_days_mv daily_revenue
report
Expected output
web.daily_revenue: 450 rows, built from web.by_day
┌────────┬────────────────┬───────────────┬───────┬────────┬─────────┬────────┐
│ run_id │     query      │    layout     │ files │  mib   │ usd_10k │  rows  │
│ int32  │    varchar     │    varchar    │ int32 │ double │ double  │ int64  │
├────────┼────────────────┼───────────────┼───────┼────────┼─────────┼────────┤
│      1 │ last_7_days    │ flat          │     6 │  5.222 │   0.249 │     35 │
│      2 │ last_7_days    │ by_day        │     7 │  0.204 │    0.01 │     35 │
│      3 │ one_customer   │ by_day        │    90 │ 10.304 │   0.491 │   1800 │
│      4 │ one_customer   │ clustered     │    90 │  3.845 │   0.183 │   1800 │
│      5 │ week_star      │ by_day        │     7 │  3.748 │   0.179 │ 140000 │
│      6 │ last_7_days_mv │ daily_revenue │     1 │  0.001 │     0.0 │     35 │
└────────┴────────────────┴───────────────┴───────┴────────┴─────────┴────────┘

One small file and about 1 KB (1,033 bytes) for the same 35 rows. The price is freshness and upkeep: the summary is only as new as its last refresh, and someone must schedule that refresh and check that it ran.

07. Step 6: Right-size the compute

Bytes are one bill; compute time is the other. On warehouses that bill compute per second, a bigger size costs more per second and only pays off if the work finishes proportionally sooner. right_size.py runs one heavy query, a distinct count over all 1.8 million sessions, with 1, 2 and 4 DuckDB threads. Your times will differ; compare the shape.

Python · right_size.py
"""Run one heavy query with 1, 2 and 4 threads and compare time with thread-seconds."""
import time

import duckdb

from lab import open_catalog

table = open_catalog().load_table("web.by_day")
SQL = (f"SELECT country, count(DISTINCT session_id) FROM iceberg_scan("
       f"'{table.metadata_location}') GROUP BY country")
for threads in (1, 2, 4):
    con = duckdb.connect()
    con.execute("LOAD iceberg")
    con.execute(f"SET threads = {threads}")
    con.sql(SQL).fetchall()                     # warm-up: file cache, extension
    start = time.perf_counter()
    con.sql(SQL).fetchall()
    seconds = time.perf_counter() - start
    print(f"threads={threads}  {seconds:5.2f} s"
          f"  thread-seconds={threads * seconds:5.2f}")
Terminal
python right_size.py
Illustrative output (timings vary by machine)
threads=1   0.52 s  thread-seconds= 0.52
threads=2   0.39 s  thread-seconds= 0.77
threads=4   0.25 s  thread-seconds= 1.00

More threads made the query faster, but not twice as fast for twice the threads, so the thread-seconds, the quantity a per-second bill charges for, went up. Choose the size from a deadline: the smallest size that meets it is usually the cheapest. Use the query history to check after every change, rather than assuming.

08. Step 7: Report the change with evidence

A tuning change is finished when you can show its effect. compare.sql reads the history and puts the first layout tried next to the cheapest one for each question.

SQL · compare.sql
-- For each question: the first layout tried, and the cheapest one so far.
SELECT regexp_replace(query, '_mv$', '') AS question,
       arg_min(layout, run_id) AS first_layout,
       round(arg_min(mib_scanned, run_id), 3) AS first_mib,
       arg_min(layout, mib_scanned) AS best_layout,
       round(min(mib_scanned), 3) AS best_mib
FROM query_history
WHERE query <> 'week_star'
GROUP BY ALL ORDER BY first_mib DESC;
Terminal
python -c "import duckdb; print(duckdb.connect('history.duckdb')\
  .sql(open('compare.sql').read()))"
Expected output
┌──────────────┬──────────────┬───────────┬───────────────┬──────────┐
│   question   │ first_layout │ first_mib │  best_layout  │ best_mib │
│   varchar    │   varchar    │  double   │    varchar    │  double  │
├──────────────┼──────────────┼───────────┼───────────────┼──────────┤
│ one_customer │ by_day       │    10.304 │ clustered     │    3.845 │
│ last_7_days  │ flat         │     5.222 │ daily_revenue │    0.001 │
└──────────────┴──────────────┴───────────┴───────────────┴──────────┘

09. Check your understanding

Practice check · 3 questions

Layouts and their cost

Each question changes one detail of the lab. Pick the best answer.

Q1. You run `python history.py one_customer flat`. How many files does the dry run plan?
Q2. Most queries on a 5-year table filter by `account_id`, which has 2 million distinct values, and some also filter by month. Which layout fits best?
Q3. In step 6, going from 2 to 4 threads cut the time but raised the thread-seconds. The nightly job has a 2-hour deadline and finishes in 40 minutes on the smaller size. What should you do?
Practice only: not graded, not saved, not evidence.

10. Apply it

This is the measurement half of the skill practice. Load your fact table, write a fixed query set of three to five real questions, and record run time, bytes scanned and estimated cost for each in a query history table, using the warehouse's own history view if it has one. Then apply one partitioning or clustering change and one materialised result, re-run the same set, and report the before and after numbers with the query that produced them.

11. Review prompt

Without looking back, explain: how a dry run estimates the bytes a query will scan; why partitioning by day helped the 7-day query but not the customer query; what clustering changed in the files; why SELECT * and LIMIT affect the bill differently; when a materialised summary is worth its upkeep; and how to decide whether a bigger compute size is worth paying for.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check