snowflake.snowpark.WhenNotMatchedClause.insert¶
- WhenNotMatchedClause.insert(assignments: Iterable[ColumnOrLiteral] | Dict[str, ColumnOrLiteral]) WhenNotMatchedClause [source]¶
Defines an insert action for the not-matched clause and returns an updated
WhenNotMatchedClause
with the new insert action added.- Parameters:
assignments – A list of values or a
dict
that associates the names of columns with the values that should be inserted. The value ofassignments
can either be a literal value or aColumn
object.
Examples:
>>> # Adds a not-matched clause where a row in source is not matched >>> # if its key does not equal the key of any row in target. >>> # For all such rows, insert a row into target whose ley and value >>> # are assigned to the key and value of the not matched row. >>> from snowflake.snowpark.functions import when_not_matched >>> target_df = session.create_dataframe([(10, "old"), (10, "too_old"), (11, "old")], schema=["key", "value"]) >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary") >>> target = session.table("my_table") >>> source = session.create_dataframe([(12, "new")], schema=["key", "value"]) >>> target.merge(source, target["key"] == source["key"], [when_not_matched().insert([source["key"], source["value"]])]) MergeResult(rows_inserted=1, rows_updated=0, rows_deleted=0) >>> target.sort("key", "value").collect() # the rows are inserted [Row(KEY=10, VALUE='old'), Row(KEY=10, VALUE='too_old'), Row(KEY=11, VALUE='old'), Row(KEY=12, VALUE='new')] >>> # For all such rows, insert a row into target whose key is >>> # assigned to the key of the not matched row. >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary") >>> target.merge(source, target["key"] == source["key"], [when_not_matched().insert({"key": source["key"]})]) MergeResult(rows_inserted=1, rows_updated=0, rows_deleted=0) >>> target.sort("key", "value").collect() # the rows are inserted [Row(KEY=10, VALUE='old'), Row(KEY=10, VALUE='too_old'), Row(KEY=11, VALUE='old'), Row(KEY=12, VALUE=None)]
Note
An exception will be raised if this method is called more than once on the same
WhenNotMatchedClause
object.