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 !!!!

Join Us as a Local Community Builder!

Passionate about hosting events and connecting people? Help us grow a vibrant local community—sign up today to get started!

Sign Up Now