Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting an error when I try to add a Primary Key?

I am using SQL Server and SSMS.

I have a table called PersonsTable:

   PersonID  FirstName   Surname  Age
    1         Hansen      Ola      30
    2         Svendson    Tove     23
    3         Pettersen   Kari     20

I am trying to set a primary key like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ALTER TABLE PersonsTable
ADD PRIMARY KEY (PersonID);

But it gives me the following error:

Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'PersonsTable'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.

>Solution :

You can’t create a primary key because that column is set to allow null values. Modify the column to not allow nulls.

Via query, it should look something like:

alter table PersonsTable alter column PersonID INT not null
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading