Sub topic 5
Partitioning and when it helps or hurts
This chapter assumes you know basic SQL, have used Databricks notebooks or a SQL warehouse, and know that a Delta table is Parquet data files plus a transaction log. It also assumes you know that OPTIMIZE compacts small files. Partitioning is the oldest layout tool for Delta tables. It still has good uses, but it is often applied to the wrong tables.
What partitioning does
Partitioning, also called Hive-style partitioning, splits a table's files into groups by the values of one or more columns. Each distinct combination of values gets its own directory. Every data file lives in exactly one directory, so it holds rows for exactly one partition value.
CREATE TABLE events_partitioned (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
PARTITIONED BY (event_date);On storage, the table looks like this:
events_partitioned/
_delta_log/
event_date=2024-01-01/part-00000-....snappy.parquet
event_date=2024-01-02/part-00000-....snappy.parquet
event_date=2024-01-02/part-00001-....snappy.parquetDelta also records each file's partition values in the transaction log. This matters for performance. The engine does not have to list directories to find the right files. It reads the log, compares the query's filter with each file's recorded partition value, and drops the files that cannot match. This is called partition pruning, and it is the simplest form of data skipping.
When partitioning helps
Partitioning pays off when all of these hold:
- The table is large. Databricks guidance is to avoid partitioning tables smaller than about 1 TB.
- Most queries filter on the partition column with equality or range predicates.
- The column has low cardinality, meaning few distinct values. Dates, regions, and tenant types are typical.
- Each partition holds at least roughly 1 GB of data, so files stay large.
Partitioning also gives operational benefits beyond reads.
Targeted maintenance. You can run OPTIMIZE on recent partitions only, which avoids rewriting old data that is already compacted:
OPTIMIZE events_partitioned
WHERE event_date >= '2024-01-01';The WHERE clause of OPTIMIZE can only reference partition columns. Filtering on a non-partition column fails.
Partition-scoped overwrites. You can replace one day of data atomically without touching other days:
INSERT INTO events_partitioned
REPLACE WHERE event_date = DATE'2024-01-01'
SELECT 1, 42, DATE'2024-01-01', 'reloaded row';Cheap deletion by retention window. A delete such as DELETE FROM events_partitioned WHERE event_date < '2023-01-01' matches whole partitions. Delta can then drop those files without rewriting any file.
Inspecting partitions
Confirm which columns a table uses and how its partitions look:
DESCRIBE DETAIL events_partitioned;
SHOW PARTITIONS events_partitioned;DESCRIBE DETAIL returns partitionColumns, numFiles, and sizeInBytes. Divide the last two to get average file size. SHOW PARTITIONS lists the partition values, so you can count them and see whether any look unexpectedly numerous.
When partitioning hurts
Most partitioning problems come from the same cause. The layout splits data into pieces that are too small, and Delta cannot fix that afterward.
High-cardinality columns
Suppose a 10 GB table is partitioned by user_id and has one million users. The average partition is about 10 KB. A query then has to open up to a million tiny files. The transaction log also grows large, because it has an entry for each file. Even a query that filters on user_id spends most of its time on metadata and file-open overhead instead of reading data.
A date column can fail the same way. Partitioning a 5 GB table by event_date over three years creates about 1,100 partitions of roughly 5 MB each. That is far below the file sizes OPTIMIZE aims for.
OPTIMIZE cannot merge across partitions
Compaction works inside one partition at a time. A file in event_date=2024-01-01 is never combined with a file in event_date=2024-01-02. If each partition holds only a few megabytes, OPTIMIZE leaves one tiny file per partition. Over-partitioning therefore creates a small-files problem that maintenance cannot remove.
Partitioning on the wrong column
Partition pruning only helps queries that filter on the partition column. If you partition by event_date and most queries filter on user_id, every query scans every partition. You pay the cost of the layout and get none of the benefit.
Skew
Partition sizes are rarely equal. If one country value holds 70% of the rows, that partition becomes a hotspot. Reads and OPTIMIZE for that value take far longer than for the others.
Write overhead
A single write that touches many partitions creates at least one file per partition per writing task. A batch that spans 500 partitions can produce thousands of small files. Optimized writes, covered later in this tutorial, reduce this but do not remove the need to pick sensible partitions.
A fixed choice
Changing the partition columns means rewriting the whole table. You cannot run an ALTER TABLE to change them. Query patterns change over time, and a layout that fit last year's queries may not fit this year's. Liquid clustering, in a later chapter, addresses this limitation.
Table: good and bad partition candidates
| Column | Typical cardinality | Verdict | Reason |
|---|---|---|---|
| `event_date` on a 2 TB table | Hundreds to thousands | Good | Common filter, about 1 GB or more per day |
| `event_date` on a 3 GB table | Hundreds to thousands | Bad | Partitions of a few MB each |
| `region` with 5 values | Very low | Good, if queried | Large partitions, but watch for skew |
| `user_id` | Millions | Bad | Tiny files, huge log |
| `event_timestamp` | Nearly unique | Bad | Close to one partition per row |
| `event_id` | Unique | Bad | One partition per row |
Measuring before you decide
Do not guess at partition sizes. Compute them from the data you already have:
SELECT event_date,
COUNT(*) AS row_count
FROM events_partitioned
GROUP BY event_date
ORDER BY row_count DESC
LIMIT 20;For a real size estimate, use DESCRIBE DETAIL for the table total and divide by the number of distinct values. If the result is below roughly 1 GB per partition, a different layout is probably better.
For a table that is not yet partitioned, count distinct values before you choose a column:
SELECT COUNT(DISTINCT event_date) AS distinct_dates
FROM events;Then divide sizeInBytes from DESCRIBE DETAIL events by that number.
Common errors
- Partitioning by default. Many older tutorials partition every table by date. On a table under 1 TB this often produces more small files than it prevents.
- Partitioning by a timestamp. If you need to filter by time but the column has second-level precision, derive a date column or hour column. Partitioning by the raw timestamp creates a huge number of partitions.
- Querying through a function. A filter such as
WHERE year(event_date) = 2024may not prune partitions as well as a direct range,WHERE event_date >= '2024-01-01' AND event_date < '2025-01-01'. Write filters directly against the partition column when you can. - Expecting OPTIMIZE to fix over-partitioning. It only compacts inside each partition.
- Using several partition columns. Partitioning by
(country, event_date)multiplies partition counts. Two columns of 50 and 365 values give 18,250 partitions. Check the product before you add a second column.
Exercises
Exercise
A 40 GB table is partitioned by user_id. It has 2 million distinct users. Queries filter on user_id. Estimate the average partition size and say whether partitioning is a good fit. What does running OPTIMIZE do for it?
Show answer
The average partition is about 40 GB / 2,000,000 = 20 KB. This is far too small, so partitioning is a poor fit even though queries filter on user_id. The table has about 2 million tiny files and a very large transaction log. OPTIMIZE cannot merge files across partitions, so it leaves roughly one tiny file per partition and does not fix the problem. A better choice is an unpartitioned table with Z-ordering or liquid clustering on user_id.
Exercise
You partition a 3 TB table by event_date. Most queries filter on a date range, and each day holds about 8 GB. Name two operational benefits of this layout besides faster reads.
Show answer
Any two of these: OPTIMIZE can be limited to recent partitions with a WHERE clause on event_date; one day can be replaced atomically with REPLACE WHERE or replaceWhere without touching other days; and deleting data older than a retention cutoff matches whole partitions, so files are dropped without rewrites. Here each partition is about 8 GB, which is above the 1 GB guidance, so the layout is sound.