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: 

Unable to add primary key constraint to nullable identity column

Malthe
New Contributor III

While we can in fact define a primary key during table creation for an identity column that's nullable (i.e., not constrained using NOT NULL), it's not possible to add such a primary key constraint after the table has been created.

We get an error message:
> Cannot create the primary key `my_table_pk` because its child column(s) `id` is nullable. Please change the column nullability and retry.

But it's not possible to change the nullability of an identity column:
> ALTER TABLE ALTER COLUMN is not supported for IDENTITY columns.

I'm not sure if logically speaking this is a bug, but it's a bit of an unfortunate situation if you want to move to a table setup with constraints and haven't created the identity columns initially with a nullability constraint.

1 ACCEPTED SOLUTION

Accepted Solutions

amuchoudhary
New Contributor III

Creating a table with a nullable IDENTITY column and defining the primary key at creation time works.
The database quietly interprets the column as NOT NULL for the purposes of the primary key, even though it's technically defined as nullable (i.e., not constrained using NOT NULL).

The database engine enforces the nullability at the schema level due to which this contradictory error shows up. 
As of today there is no direct fix, maybe we can add this as enhancement but not sure its going to fix anytime soon as this will get tricky and dirty. 
The best approach is dropping the table and recreating it with required constraints during creation ( if possible ).

View solution in original post

1 REPLY 1

amuchoudhary
New Contributor III

Creating a table with a nullable IDENTITY column and defining the primary key at creation time works.
The database quietly interprets the column as NOT NULL for the purposes of the primary key, even though it's technically defined as nullable (i.e., not constrained using NOT NULL).

The database engine enforces the nullability at the schema level due to which this contradictory error shows up. 
As of today there is no direct fix, maybe we can add this as enhancement but not sure its going to fix anytime soon as this will get tricky and dirty. 
The best approach is dropping the table and recreating it with required constraints during creation ( if possible ).

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