Recently, I was working on one critical requirement where I was trying to alter 2 primary keys for a table in SQL server. But after executing the SQL script, I got this error. In this article, I will walk you through the complete steps I followed to fix this issue.
I was executing the below scripts.
First, I executed the below SQL script to create a new table.
CREATE TABLE TicketBookings (
TicketNumber VARCHAR(10),
BookingDate DATE,
PassengerID INT,
PSeatNumber VARCHAR(5)
);
Then, I tried executing the script below to create the composite primary key, and after executing this script, I got this error. Check out the screenshot below for your reference.
ALTER TABLE TicketBookings
ADD CONSTRAINT PK_TicketBookings
PRIMARY KEY (TicketNumber, BookingDate);
Solution
To solve this error, I followed the below steps.
I executed the scripts below to alter the TicketNumber and BookingDate to make it NOT NULL.
ALTER TABLE TicketBookings
ALTER COLUMN TicketNumber VARCHAR(10) NOT NULL;
ALTER TABLE TicketBookings
ALTER COLUMN BookingDate DATE NOT NULL;
The query was executed successfully, as shown in the screenshot below.
Now, I executed the below script again to alter the composite key. This time, the query was executed successfully, and the composite primary keys were also created successfully, as shown in the screenshot below.
ALTER TABLE TicketBookings
ADD CONSTRAINT PK_TicketBookings
PRIMARY KEY (TicketNumber, BookingDate);
To cross-check, Just expanded the TicketBookings table node and saw the two primary keys created successfully, as highlighted in the screenshot below.
Conclusion
So, to make any column primary key, you need to ensure the column is already set to no null; otherwise, you will get this error. Check out the information mentioned in this article to fix the error that cannot define the primary key constraint on the nullable column in the table.
You may also like following the articles below.
- How To Get The Primary Key Of A Table In SQL Server
- Cannot set SYSTEM_VERSIONING to ON when SYSTEM_TIME period is not defined.
- Incorrect Syntax Near The Keyword ‘Order’
- How to Alter Table Column to Allow NULL in SQL Server
Grey is a highly experienced and certified database expert with over 15 years of hands-on experience in designing, implementing, and managing complex database systems. Currently employed at WEX, USA, Grey has established a reputation as a go-to resource for all things related to database management, particularly in Microsoft SQL Server and Oracle environments. He is a Certified Microsoft SQL Server Professional (MCSE: Data Management and Analytics) and Oracle Certified Professional (OCP), with Extensive database performance tuning and optimization knowledge and a proven track record in designing and implementing high-availability database solutions.