cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Drop/Create tables in Redshift with PySpark

BradSheridan
Valued Contributor

Happy Friday afternoon fellow Bricksters! Got another question for you... I have a pyspark notebook that reads from redshift into a DF, does some 'stuff', then writes back to redshift. All good here. What I'm trying to do with no luck yet is first DROP TABLE IF EXISTS, then follow that with CREATE TABLE IF NOT EXISTS but can't seem to figure out how. Any suggestions are welcomed! thanks

1 ACCEPTED SOLUTION

Accepted Solutions

BradSheridan
Valued Contributor

Answered my own question!! check this out:

dropSQL = ("DROP TABLE IF EXISTS <tablename>;"). --note the semicolon at the end!

createSQL = ("CREATE TABLE IF NOT EXISTS <tablename> (field1 int, field2 date, etc...);")

preActionsSQL = dropSQL + createSQL

then when writing your dataframe to a Redshift table, include this:

.option("preactions", preActionsSQL)

Side note: if you use the .mode("overwrite") option, I *think it actually either drops or truncates the target table first anyway, but I haven't confirmed this...was too excited to share my findings with y'all !!!!

View solution in original post

1 REPLY 1

BradSheridan
Valued Contributor

Answered my own question!! check this out:

dropSQL = ("DROP TABLE IF EXISTS <tablename>;"). --note the semicolon at the end!

createSQL = ("CREATE TABLE IF NOT EXISTS <tablename> (field1 int, field2 date, etc...);")

preActionsSQL = dropSQL + createSQL

then when writing your dataframe to a Redshift table, include this:

.option("preactions", preActionsSQL)

Side note: if you use the .mode("overwrite") option, I *think it actually either drops or truncates the target table first anyway, but I haven't confirmed this...was too excited to share my findings with y'all !!!!

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group