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_Fatma
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.

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