7

Can I add a new column to an existing spark table using the ALTER TABLE command ?

var query = "ALTER TABLE " + "global_temp." + tableName(0) + " ADD COLUMN " + newColumnName + " " + newColumnDatatype
var drt = spark.sql(query)

The above code raises the following error.

 no viable alternative at input 'ALTER TABLE global_temp.people_ty ADD COLUMN' new_age integer

EDIT

The correct syntax is as follows

ALTER TABLE tablename ADD COLUMNS (newColumn newDataType)

But, it also throws the following error.

ALTER ADD COLUMNS does not support views.
You must drop and re-create the views for adding the new columns. Views: `global_temp`.`people_ty`
7
  • Is people_ty registered using createOrReplaceTempView? Commented Apr 25, 2018 at 7:03
  • 1
    Data frames are immutable, you cannot alter them. Commented Apr 25, 2018 at 7:05
  • @philantrovert , people_ty is registered using createGlobalTempView Commented Apr 25, 2018 at 7:07
  • Why not do a withColumn before you create a view out of it? Commented Apr 25, 2018 at 7:08
  • 1
    Spark 2.3.0 . The syntax is ALTER TABLE tablename ADD COLUMNS (newColumn newDataType) Commented Apr 25, 2018 at 8:51

1 Answer 1

5

In Spark SQL the syntax is as mentioned by Soumyadip Ghosh in the comments

ALTER TABLE table_identifier ADD COLUMNS ( col_spec [ , ... ] )

Works for me.

Sign up to request clarification or add additional context in comments.

1 Comment

When trying to use that synthax i get an error. Code: spark.read.format('jdbc').options(**spark_sql_options).option('query', F'SELECT * FROM {table_name}').load().createGlobalTempView('db_second_view') Error: AnalysisException: test_table is a temp view. 'ALTER TABLE ... ADD COLUMN' expects a table..; Am I missing something? Is it because my view is backed by an actual sql database?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.