Skip to content
Silver 6 min read · All formats 3 practice problems ↓

Partitioning done right

Partitioning splits a table into folders by a column, such as one folder per day, so queries that filter on it can skip the rest. Done well it is a big speed-up; done badly it creates thousands of tiny files. This lesson shows when to partition, how to choose the column, and how it backfires.

Step 3 · Data lake & lakehouse · Silver · Keeping tables fast, lesson 1 of 3

Read first: Parquet and columnar storage · The small file problem (skip if you know them)

In plain words first

Filing receipts into one folder per month means "March receipts" is one folder to open. Filing them into one folder per customer per hour means millions of folders, each with one receipt, and finding anything takes longer than before.

Partitioning is choosing the folders. The right column is one you filter on often, with not too many distinct values.

What partitioning does

events/
├── event_date=2025-03-01/
│   ├── part-00000.parquet
│   └── part-00001.parquet
├── event_date=2025-03-02/
│   └── ...
└── event_date=2025-03-03/

A filter on the partition column, WHERE event_date = '2025-03-02', reads only that folder: partition pruning, decided before any file is opened. The partition column's values live in folder names (or metadata), not in the data files.

PySparkSpark SQL
df.write.format("delta").partitionBy("event_date").saveAsTable("events")
CREATE TABLE events (event_id BIGINT, user_id BIGINT, event_date DATE, payload STRING)
USING delta
PARTITIONED BY (event_date);

Choosing a partition column

  • Used in filters by most queries: otherwise pruning rarely helps and every query pays for more files.
  • Low cardinality: hundreds to a few thousand values over the table's life, not millions.
  • Enough data per partition: a common guideline is at least about 1 GB per partition. Delta's guidance suggests not partitioning tables under about 1 TB at all and relying on clustering instead.
  • Stable: changing the partition scheme later means rewriting the table (except with Iceberg partition evolution).
ColumnGood partition?Why
event_date on a 20 TB tableYesUsed in nearly every query, ~55 GB per day
event_date on a 50 GB tableProbably notAbout 140 MB per day: many small partitions
country (60 values)Maybe, as a second level only if queries filter on it and partitions stay largeMultiplies the partition count
user_idNoMillions of partitions with tiny files
event_timestampNoPractically unique values

How over-partitioning backfires

Plan · the idea

A 200 GB table is partitioned by event_date and country "to make country filters fast". 3 years × 60 countries = 65,700 partitions.

Reality · the files

Average partition: 3 MB. Each daily load writes up to one file per tasktask: The work for one partition in one stage, run on one CPU core. Learn more → per partition, so after a year the table has hundreds of thousands of small files.

Effect · every query

Queries that do not filter on country now open 60 times more files than needed. Planning takes minutes, and the metastore or transaction logtransaction log: The ordered list of commits that defines which files make up a Delta table at each version. Learn more → is bloated.

Better · the fix

Partition by month (or not at all), and cluster by country and date with Z-orderZ-order: Sorting data by several columns at once, so queries filtering on any of them can skip more files. Learn more → or liquid clustering. File-level statistics then provide most of the skipping, with large healthy files.

Alternatives and complements

Clustering

Z-order or sorting within files: skipping via min/max statistics without extra folders. Works on high-cardinality columns.

Hidden partitioning (Iceberg)

Partition by a transform like day(ts) or bucket(16, id); queries filter on the raw column and still prune. The layout can evolve later.

Liquid clustering (Delta)

Replaces partitioning and Z-order with incremental clustering on chosen keys that can change over time.
Why this matters: partitioning is coarse and permanent; clustering is fine-grained and adjustable. Partition only by the one or two columns that define how data arrives and is deleted (typically a date), and cluster for everything else.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session with Delta Lake, with spark already created: each builds its own data.

Goal: Partition by a date computed from the timestamp, so queries that filter on the timestamp still skip partitions.

Production patternPySpark · Partition by a generated date column, filter on the timestamp
import contextlib, io, os
from pyspark.sql import functions as F

path = os.path.abspath("lab/partitioning/events")
spark.sql(f"""CREATE OR REPLACE TABLE delta.`{path}` (
    id BIGINT, event_ts TIMESTAMP,
    event_date DATE GENERATED ALWAYS AS (CAST(event_ts AS DATE))
) USING delta PARTITIONED BY (event_date)""")
(spark.range(0, 100_000)
     .withColumn("event_ts", F.expr("TIMESTAMP'2025-03-01 00:00:00' "
                                    "+ make_dt_interval(CAST(id % 10 AS INT))"))
     .write.format("delta").mode("append").save(path))


def partition_filters(df):
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        df.explain()
    return buf.getvalue().split("PartitionFilters: ")[1].split("], ")[0] + "]"


events = spark.read.format("delta").load(path)
# no event_date in the query
recent = events.where("event_ts >= '2025-03-08 00:00:00'")
print("partition filter derived from event_ts:", partition_filters(recent))
print("rows:", recent.count())

Output from a real run

partition filter derived from event_ts: [((event_date#67783 >= 2025-03-08) OR isnull((event_date#67783 >= 2025-03-08)))]
rows: 30000

What to notice:

  • The query filters on event_ts only, yet the plan has a partition filter on event_date >= 2025-03-08: Delta worked it out from the generated column.
  • 30,000 rows: the last 3 of the 10 days.
  • With a plain event_date column, the same query would read every partition.

Common mistakes

  • Partitioning small tables — Creates small files with no benefit.
  • Partitioning by high-cardinality columns — Millions of folders and tiny files.
  • Filtering on a function of the partition column — WHERE year(event_date) = 2025 may not prune; filter on the raw column range, or use generated columns or hidden partitioning.

Key takeaways

  • Partitioning writes folders per value and lets filters skip whole folders.
  • Choose low-cardinality columns used in most filters, with about 1 GB or more per partition.
  • Over-partitioning creates huge numbers of small files.
  • Use clustering for high-cardinality filters; partition only by a date-like column.

Interview prep

THE QUESTION

"How would you partition a 30 TB events table queried mostly by date range and sometimes by user_id?"

Partition by event date (or month if daily partitions would be small), never by user_id. For user_id filters, cluster within partitions (Z-order or liquid clustering) so file statistics skip most files. Mention the 1 GB-per-partition guideline, small-file risk, and that Iceberg hidden partitioning or Delta liquid clustering can make layout changes cheaper later.

Avoid: "partition by user_id because we filter on it". High-cardinality partitions create millions of tiny files.

Follow-ups · answer out loud, then open

Follow-up"How big should a partition be?"
Large: around a gigabyte or more of data per partition, so each holds several well-sized files. Many guides suggest not partitioning tables under about 1 TB at all and relying on clustering instead.
Scenario"Queries filter on event_ts, but the table is partitioned by event_date and nothing is pruned. Why?"
In Hive-style partitioning, a filter on event_ts does not imply a filter on event_date. Add the date filter explicitly, use a Delta generated column for event_date (Delta then derives the partition filter), or use Iceberg hidden partitioning, which prunes from the source column.
Trap"More partitions means more parallelism."
Read parallelism comes from file splits, not folders. Over-partitioning gives many small files, slow listing and planning, and worse performance.

Check yourself

3 questions

Which is the worst partition column?

Show the answer

user_id. Millions of distinct values create millions of tiny partitions.

A 40 GB table is partitioned by day over 3 years. Roughly how large is each partition?

Show the answer

About 36 MB. 40 GB / ~1,100 days ≈ 36 MB: too small to be worth partitioning daily.

How do you make user_id filters fast without partitioning by it?

Show the answer

Cluster files by user_id (Z-order or liquid clustering). Clustering narrows per-file ranges so statistics skip files.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Keeping tables fast · lesson 2 of 3 · 5 min read
Compaction, OPTIMIZE and Z-order
Rewrite small files into large ones and cluster data so queries skip more of it.

Related lessons

Previous: Change Data Feed

Primary sources: Delta: best practices (choose the right partition column) · Iceberg: partitioning