What you will be able to do
- Persist a DataFrame as a catalog table with saveAsTable and predict what each save mode does when the table already exists
- Tell a managed table from an external one by what happens to the files when the table is dropped
- Choose a partitionBy column that lets filtered reads skip whole directories, and recognise a column whose cardinality makes partitioning backfire
- Write a bucketed, sorted table with bucketBy and sortBy, and explain why that layout only works through saveAsTable
Key concept
Persistent table layout — saveAsTable writes the data and also registers it as a named table in the catalog, so it is still there after the session ends. Any layout you choose at write time, such as partition directories, hash buckets or sorted buckets, is stored with the table, and every later query against that table name can use it.
1.Saving a DataFrame as a persistent table
A persistent table is data plus a name in the catalog. df.write.save(path) leaves files at a path, and the next job has to know that path and the format. df.write.saveAsTable("sales") writes the same files and also registers sales, so any later session can query it with spark.read.table("sales") or SELECT * FROM sales. A temporary view disappears when its session ends (temp views are session-scoped). A table saved with saveAsTable stays.
The signature is saveAsTable(name, format=None, mode=None, partitionBy=None, **options). If the table already exists, mode decides what happens, and the default is to throw an exception. The modes are the same four that path writes use (save modes), but two details only apply to tables. With overwrite, the DataFrame's schema does not have to match the existing table's schema. With append, the existing table's format and options are used, whatever you pass now.
saveAsTable also matches columns differently from insertInto. saveAsTable lines up columns by name. insertInto lines them up by position. If your DataFrame has the right columns in a different order, saveAsTable in append mode puts each value in the right column. insertInto would put values into the wrong columns without any error.
# Save as managed table with options
df.write \
.mode("overwrite") \
.format("parquet") \
.partitionBy("year") \
.saveAsTable("partitioned_table")A table is either managed or external, depending on whether you give it a location. If you give no location, the table is managed and the platform picks a default location for the files. If you give a location (in SQL, CREATE TABLE ... LOCATION path), the table is external. The difference shows up when you drop the table. Dropping a managed table in the Hive metastore removes both the catalog entry and the files. Dropping an external table removes only the catalog entry, and the files stay at their location.
| Table type | How it is created | On DROP TABLE |
|---|---|---|
| Managed | No LOCATION given; a default table location is created | Removed from the metastore and the underlying data is deleted |
| External | LOCATION path given | Removed from the metastore but the underlying data remains |
Checkpoint 1 of 8· Fill the gap
This write should create a partitioned Parquet table called partitioned_table and register it in the catalog. Later sessions must be able to query it by name with spark.read.table, and columns must be matched by name. Which call completes the sample?
# Save as managed table with options
df.write \
.mode("overwrite") \
.format("parquet") \
.partitionBy("year") \
. ? ("partitioned_table")saveAsTable writes the files and also registers the name in the catalog, and it matches columns by name. save and parquet only write files to a path that the next job has to know. insertInto matches columns by position.
Source: docs.databricks.comCheckpoint 2 of 8· Check yourself
In the Hive metastore, table A was created with df.write.saveAsTable("a") and no location. Table B was created with CREATE TABLE b ... LOCATION '/data/b'. You then run DROP TABLE on both. What happens to their data files?
A has no location, so it is a managed table, and dropping it deletes its files. B has a LOCATION, so it is external, and dropping it removes only the catalog entry.
“When an external table is dropped the files at the LOCATION will not be dropped.”Source: docs.databricks.com
2.partitionBy: one directory per value
partitionBy decides how the files are arranged on disk, not how rows are ordered in memory. It splits the output by the given columns into a Hive-style layout: one subdirectory per distinct value, named column=value, with that value's rows inside. The partition column's value is stored in the directory name, so each file inside holds only the remaining columns.
import tempfile, os
with tempfile.TemporaryDirectory(prefix="partitionBy") as d:
spark.createDataFrame(
[{"age": 100, "name": "Alice"}, {"age": 120, "name": "Ruifeng Zheng"}]
).write.partitionBy("name").mode("overwrite").format("parquet").save(d)
spark.read.parquet(d).sort("age").show()
# +---+-------------+
# |age| name|
# +---+-------------+
# |100| Alice|
# |120|Ruifeng Zheng|
# +---+-------------+
# Read one partition as a DataFrame.
spark.read.parquet(f"{d}{os.path.sep}name=Alice").show()This layout is how partition pruning works on retrieval. When a query filters on the partition column, Spark knows which directories hold the matching values and skips the rest without opening their files. In the orders table above, a filter on one order_date touches one directory out of roughly eighteen hundred. On a persistent table you get the same layout by calling .partitionBy("transaction_date") before .saveAsTable("transactions"), or by passing partitionBy= to saveAsTable itself. Readers then only need the table name, and the pruning works for every query that filters on that column.
Several calls that look similar do not produce this layout. bucketBy hashes rows into a fixed number of files instead of one directory per value. sortBy orders rows inside those bucket files. orderBy is not a DataFrameWriter method at all: the writer's methods are mode, format, option(s), partitionBy, bucketBy, sortBy, clusterBy, and the save, insert and format-specific methods. df.repartition("transaction_date") changes how the data is split across tasks in memory before the write (repartitioning). It writes no directory per date, so a later filter has nothing to prune.
Checkpoint 3 of 8· Check yourself
Analysts will query a persistent transactions table mostly with WHERE transaction_date = '...'. Each query should skip the files for all other dates without opening them. Which write produces a table that allows this?
partitionBy writes one column=value directory for each date. Spark can then prune every directory that does not match the filter. repartition only splits the data across tasks in memory. bucketBy hashes rows into a fixed number of files. sortBy only orders rows within buckets. None of these three creates per-value directories.
“If specified, the output is laid out on the file system similar to Hive's partitioning scheme.”Source: docs.databricks.com
Checkpoint 4 of 8· Exam question
A data engineer needs to persist a large transactions_df DataFrame as a managed table so that later queries filtering on transaction_date can skip irrelevant files entirely, with no bucketing or sorting required. Which code correctly persists the table with this optimization?
Correct answer: A — transactions_df.write.mode("overwrite").partitionBy("transaction_date").saveAsTable("transactions")
- A.
partitionBywrites the table as Hive-style directories keyed bytransaction_date, so a later query filtering on that column only reads the matching directory. This is the standard way to get file-skipping without introducing bucketing or sort metadata. - B.
bucketByhashes rows into a fixed number of bucket files rather than creating per-value directories, so a reader cannot tell from the file layout which bucket holds a giventransaction_date. It optimizes joins and aggregations on the bucketing column, not date-based file skipping. - C.
sortBycan only be used together with a precedingbucketBycall on the same writer. Calling it alone raises an error before any data is written, so this call never reaches the metastore. - D.
DataFrameWriterhas noorderBymethod; ordering a DataFrame before a write is done withDataFrame.orderBy, not on the writer object. This call fails with an attribute error at runtime. - E.
repartitionchanges how many in-memory Spark partitions are used during the write, which can affect the number of output files, but it does not create the on-disk directory structure that lets a reader prune bytransaction_datevalue.
3.When partitioning backfires: high-cardinality columns
partitionBy creates one directory per distinct value, so the number of values in the column sets the number of directories. A date column over five years gives about eighteen hundred directories, each holding a full day of data. A timestamp column or a customer ID can give millions of directories, each holding a few rows. Partitioning works well for low or known cardinality fields such as dates or physical locations, but not for high-cardinality fields such as timestamps.
The cost comes from small partitions. Each directory holds at least one file, so a high-cardinality column produces a huge number of tiny files. Spark then spends more effort listing and opening those files than reading the data, and that loss outweighs whatever pruning saves. A common guideline is that each partition should hold at least 1 GB of data, because tables with fewer, larger partitions tend to outperform tables with many small ones.
| Candidate column | Distinct values | Effect of partitionBy |
|---|---|---|
| date, physical location | Low or known (days, locations) | Few large directories; filters prune whole directories |
| event timestamp, customer ID | High, and growing over time | Very many tiny partitions; listing and opening files costs more than pruning saves |
Checkpoint 5 of 8· Check yourself
You are choosing the partition column for a persistent clickstream table that grows by about 2 TB a year. Its columns include event_ts (a millisecond timestamp), event_date, and customer_id (tens of millions of distinct values). Most queries filter on a time range. Which write is most likely to give fast reads?
event_date has low, known cardinality, so you get a few large directories that time filters can prune. event_ts and customer_id have very high cardinality. Partitioning on them creates huge numbers of tiny partitions, and listing and opening those files costs more than pruning saves.
“Tables with fewer, larger partitions tend to outperform tables with many smaller partitions.”Source: docs.databricks.com
Sources6
4.bucketBy and sortBy: hashed, sorted files in a table
Bucketing groups rows by the hash of a column instead of by each distinct value. bucketBy(numBuckets, col, *cols) hashes each row's bucket columns and places the row in one of exactly numBuckets files. The file count stays the same however many distinct values the column has, which makes bucketing a good fit for high-cardinality keys such as customer_id, where partitionBy would fail. Spark's bucket hash function differs from Hive's, so a table bucketed by Spark is not compatible with Hive's bucketing.
sortBy works only together with bucketBy. It orders the rows inside each bucket file by the given columns. It does not sort the dataset as a whole, and it does not replace bucketBy. The sort column can differ from the bucket column, as in the example below, which buckets by name and sorts each bucket by age.
spark.sql("DROP TABLE IF EXISTS sorted_bucketed_table")
spark.createDataFrame([
(100, "Alice"), (120, "Alice"), (140, "Bob")],
schema=["age", "name"]
).write.bucketBy(1, "name").sortBy("age").mode(
"overwrite").saveAsTable("sorted_bucketed_table")Bucketing applies only to file-based sources written with saveAsTable. The bucket count and bucket columns have to be recorded somewhere for later queries to use them, and the catalog entry that saveAsTable creates is that place. A plain .save("/mnt/data/customers_parquet") writes files with no table around them. So df.write.bucketBy(20, "customer_id").sortBy("customer_id").save(path) is not a valid write. Spark does not quietly drop the bucketing and write plain Parquet, and it does not create a table named after the path.
The payoff from bucketing comes on later joins. When a join reads tables that are already bucketed on the join key, Spark can use that stored layout to skip the shuffle it would otherwise need to bring matching keys together. This is called a bucket join, and it only applies to bucketed tables. With partitionBy, the gain is skipping directories on a filter. With bucketBy, the gain is skipping a shuffle on a join.
The same layout can be written in SQL: CLUSTERED BY (cols) [SORTED BY (cols)] INTO n BUCKETS in a CREATE TABLE statement. SQL adds two rules. A partition column cannot also be a bucket or sort column, because buckets are created within each partition. And the clause is not supported for Delta or Iceberg tables, which use CLUSTER BY instead.
| Call | What it writes | Works with save(path)? | What later reads gain |
|---|---|---|---|
| partitionBy(*cols) | One Hive-style directory per column value | Yes, and with saveAsTable | Filters on the column skip whole directories |
| bucketBy(numBuckets, col, *cols) | A fixed number of hash-bucket files | No, saveAsTable only | Joins on the bucket key can avoid the shuffle |
| sortBy(col, *cols) | Rows ordered inside each bucket | No, requires bucketBy and saveAsTable | Each bucket file is already sorted |
bucketBy. customer_id has very high cardinality, so partitionBy would create one tiny directory per customer. bucketBy keeps a fixed number of files no matter how many customers there are, and because the table is already bucketed on the join key, later joins on customer_id can skip the shuffle.
Checkpoint 6 of 8· Match them up
Match each call in a write chain to the layout it produces and the constraint it carries.
Tap a term, then the definition that fits it.
partitionBy creates per-value directories for pruning. bucketBy creates a fixed number of hash files that must be recorded with a catalog table, so it needs saveAsTable. sortBy only orders rows within those buckets. repartition affects only the split across tasks in memory, not the layout on disk.
“Sorts the output in each bucket by the given columns on the file system.”Source: docs.databricks.com
Checkpoint 7 of 8· Exam question
Which statement correctly describes the relationship between sortBy and bucketBy on DataFrameWriter when persisting a table?
Correct answer: A — sortBy orders rows within each bucket file that bucketBy produces; a write that calls sortBy without bucketBy first raises an error.
- A. Bucketing groups rows into a fixed number of bucket files by hashing a column, and a chained sort orders the rows inside each of those files. Because there is nothing to sort within until buckets exist, the writer raises an error if a sort is requested without bucketing first.
- B. A sort requested this way is scoped to buckets, not the whole dataset, and it cannot be requested on its own; it must follow a bucketing call. There is no single fully sorted output file produced by this mechanism.
- C. Bucket count and column choice are set independently of any sort; the hash function that assigns rows to buckets does not consult sort order at all. The dependency runs the other way: sorting needs buckets to sort within, not the reverse.
- D. These are two distinct writer methods with different jobs: one groups rows into a fixed number of files by hash, the other orders rows inside files that already exist. They are not aliases and using only one of them does not reproduce the other's effect.
- E. Directory-level partitioning is a separate writer method entirely, unrelated to either of these two calls. Neither of these methods governs partition directories, and the in-memory-only claim understates what a bucket-and-sort write actually persists to storage.
Checkpoint 8 of 8· Exam question
A developer writes:
df.write.bucketBy(20, "customer_id").sortBy("customer_id").save("/mnt/data/customers_parquet")
What happens when this code runs?
Correct answer: A — The write fails immediately with an AnalysisException, since bucketBy and sortBy only work with saveAsTable or insertInto, not save.
- A. Bucketing and its associated sort are table-level metadata that only a catalog entry can store, so they are only accepted on
saveAsTableandinsertInto. The file-basedsavepath has no catalog entry to record that metadata in, and Spark raises an exception rather than writing partial results. - B. This describes what a bucketed
saveAsTablewrite would produce, butsavedoes not accept bucketing at all. The call fails before any files are written, so no such output is produced. - C. Spark does not silently drop an unsupported writer configuration and continue; a
bucketBy-plus-sortBycall onsaveraises an exception rather than falling back to a default file layout. - D.
savenever creates a metastore entry regardless of which writer options are chained onto it; it only writes files to the given path. No table registration happens here, and the call fails before reaching that point anyway. - E. The number of buckets is independent of the cluster's core count and is not capped by available parallelism. The failure here comes from combining bucketing with an unsupported writer method, not from a shuffle-stage parallelism limit.
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/saveAsTableOfficial docs
“If the table already exists, the behavior depends on the mode parameter (default is to throw an exception).”
↩︎ Saving a DataFrame as a persistent table“When mode is 'overwrite', the schema of the DataFrame does not need to match the existing table schema.”
↩︎ Saving a DataFrame as a persistent table“When mode is 'append', if a table already exists, its format and options are used.”
↩︎ Saving a DataFrame as a persistent table“Unlike DataFrameWriter.insertInto, DataFrameWriter.saveAsTable uses column names to find the correct column positions.”
↩︎ Saving a DataFrame as a persistent table“Saves the content of the DataFrame as the specified table.”
↩︎ Key concept - 2.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-table-usingOfficial docs
“If you specify no location the table is considered a managed table and Databricks creates a default table location.”
↩︎ Saving a DataFrame as a persistent table“Specifying a location makes the table an external table.”
↩︎ Saving a DataFrame as a persistent table“Since a clustering operates on the partition level you must not name a partition column also as a cluster column.”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“This clause isn't supported for Delta or Iceberg tables. Use CLUSTER BY instead.”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“When an external table is dropped the files at the LOCATION will not be dropped.”
↩︎ Checkpoint - 3.
“The table is removed from the metastore but the underlying data remains.”
↩︎ Saving a DataFrame as a persistent table“The table is removed from the metastore and the underlying data is deleted.”
↩︎ Exam trap 4 - 4.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/partitionByOfficial docs
“If specified, the output is laid out on the file system similar to Hive's partitioning scheme.”
↩︎ partitionBy: one directory per value - 5.
“Partitions the output by the given columns on the file system.”
↩︎ partitionBy: one directory per value - 6.https://docs.databricks.com/aws/en/tables/partitionsOfficial docs
“but not for fields with high cardinality such as timestamps”
↩︎ When partitioning backfires: high-cardinality columns“For partitions, verify that each partition contains at least 1 GB of data.”
↩︎ When partitioning backfires: high-cardinality columns“Tables with fewer, larger partitions tend to outperform tables with many smaller partitions.”
↩︎ When partitioning backfires: high-cardinality columns“but not for fields with high cardinality such as timestamps”
↩︎ Exam trap 3 - 7.
“but with a different bucket hash function and is not compatible with Hive's bucketing.”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“Applicable for file-based data sources in combination with DataFrameWriter.saveAsTable.”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“Applicable for file-based data sources in combination with DataFrameWriter.saveAsTable.”
↩︎ Exam trap 1 - 8.
“Sorts the output in each bucket by the given columns on the file system.”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“Sorts the output in each bucket by the given columns on the file system.”
↩︎ Exam trap 2 - 9.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“This is a generalization of the concept of Bucket Joins, which is only applicable for bucketed tables”
↩︎ bucketBy and sortBy: hashed, sorted files in a table“makes use the existing storage layout to avoid the shuffle phase”
↩︎ bucketBy and sortBy: hashed, sorted files in a table