Del via


saveAsTable

Saves the content of the DataFrame as the specified table. If the table already exists, the behavior depends on the mode parameter (default is to throw an exception). When mode is 'overwrite', the schema of the DataFrame does not need to match the existing table schema.

Syntax

saveAsTable(name, format=None, mode=None, partitionBy=None, **options)

Parameters

Parameter Type Description
name str The table name.
format str, optional The format used to save.
mode str, optional The behavior when data already exists. Accepted values are 'append', 'overwrite', 'error' or 'errorifexists' (default), and 'ignore'.
partitionBy str or list, optional Names of partitioning columns.
**options dict Additional string options.

Returns

None

Notes

When mode is 'append', if a table already exists, its format and options are used. Unlike DataFrameWriter.insertInto, DataFrameWriter.saveAsTable uses column names to find the correct column positions.

Examples

Create a table from a DataFrame, and read it back.

spark.sql("DROP TABLE IF EXISTS tblA")
spark.createDataFrame([
    (100, "Alice"), (120, "Bob"), (140, "Tom")],
    schema=["age", "name"]
).write.saveAsTable("tblA")

spark.read.table("tblA").sort("age").show()
# +---+------------+
# |age|        name|
# +---+------------+
# |100|Alice|
# |120|Bob|
# |140| Tom|
# +---+------------+

spark.sql("DROP TABLE tblA")