CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 2 · Lesson 10/32

    Persistent tables in Spark: saveAsTable, partitionBy, bucketBy and sortBy

    Save data to persistent tables while applying sorting and partitioning to optimize data retrieval.

    16 min read
    5% of exam
    9 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    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.

    A managed, partitioned Parquet table written in one chain: mode, format and partition column, then saveAsTablepython
    # 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.

    What happens to the files when each kind of table is dropped (Hive metastore)
    Table typeHow it is createdOn DROP TABLE
    ManagedNo LOCATION given; a default table location is createdRemoved from the metastore and the underlying data is deleted
    ExternalLOCATION path givenRemoved 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")

    Checkpoint 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?

    Sources123

    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.

    partitionBy("name") creates a name=Alice directory, and reading that directory returns only its rows, without the name columnpython
    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?

    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?

    Sources45

    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.

    Choosing a partition column by cardinality
    Candidate columnDistinct valuesEffect of partitionBy
    date, physical locationLow or known (days, locations)Few large directories; filters prune whole directories
    event timestamp, customer IDHigh, and growing over timeVery 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?

    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.

    A sorted, bucketed table: bucketBy chooses the files, sortBy orders rows inside each one, and saveAsTable records the layoutpython
    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.

    The three DataFrameWriter layout calls compared
    CallWhat it writesWorks with save(path)?What later reads gain
    partitionBy(*cols)One Hive-style directory per column valueYes, and with saveAsTableFilters on the column skip whole directories
    bucketBy(numBuckets, col, *cols)A fixed number of hash-bucket filesNo, saveAsTable onlyJoins on the bucket key can avoid the shuffle
    sortBy(col, *cols)Rows ordered inside each bucketNo, requires bucketBy and saveAsTableEach bucket file is already sorted

    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.

    Checkpoint 7 of 8· Exam question

    Which statement correctly describes the relationship between sortBy and bucketBy on DataFrameWriter when persisting a table?

    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?

    Sources7892

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 2.
      “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. 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. 4.
      “If specified, the output is laid out on the file system similar to Hive's partitioning scheme.”
      ↩︎ partitionBy: one directory per value
    5. 5.
      “Partitions the output by the given columns on the file system.”
      ↩︎ partitionBy: one directory per value
    6. 6.
      “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. 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. 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. 9.
      “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

    Spotted a mistake, or was something unclear? Tell us.