cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Get Started Discussions
Start your journey with Databricks by joining discussions on getting started guides, tutorials, and introductory topics. Connect with beginners and experts alike to kickstart your Databricks experience.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Unable to change/cast column datatype using Delta IO

Srikanthn
New Contributor II

I have created a delta table using Delta IO library, with following details

Table Name: Employee

Columns {Id Integer, name String, gender String, Salary decimal(5,2)}

Now I want to upcast the salary from decimal(5,2) to decimal(10,4). If I use delta IO library I am endup with "Detected incompatible schema change" error. Is there way to change upcast columns, change datatype using Delta IO.

1 REPLY 1

Kaniz
Community Manager
Community Manager

Hi @Srikanthn , Yes, you can change the datatype of a column in a Delta table without losing the delta log. The delta log provides transaction history which is essential for time travel in delta tables.

Here is the method to change the datatype of a column in a Delta table:

python
import org.apache.spark.sql.functions.col

spark.read.table("Employee")
   .withColumn("Salary", col("Salary").cast("decimal(10,4)"))
   .write.format("delta").mode("overwrite").option("overwriteSchema",true).saveAsTable("Employee")

This method reads the Delta table (managed or external), changes the datatype of the column "Salary" from decimal(5,2) to decimal(10,4), and overwrites the schema of the table. 

To check the datatype after changing the column datatype, you can use the following code:

python
spark.read.table("Employee").printSchema()
spark.read.table("Employee").show(truncate = false)

This method also preserves the delta log, so you can time travel and check in what version what changes have been made.

Join 100K+ Data Experts: Register Now & Grow with Us!

Excited to expand your horizons with us? Click here to Register and begin your journey to success!

Already a member? Login and join your local regional user group! If there isn’t one near you, fill out this form and we’ll create one for you to join!