How to add Primary key to an existing column of an already populated table

Asked

Viewed 557 times

0

I have a table already populated, in this table I have the column Deviceimei which I want to turn into Primary key. Is there any way to do this without having to empty the table ?

I’m trying this way:

alter table TableName add constraind PK_DeviceIMEI primary key (DeviceIMEI)
  • Are you making a mistake? If so, what mistake?

  • would not be add constraint ??? is wrong there

1 answer

3


Yes you do, the command is a ALTER TABLE:

ALTER TABLE nome-da-tablea ADD PRIMARY KEY (nome-do-campo)

Now, the contents of the field must respect the rules of a Primary key (quoted from the link above):

Limitations and Restrictions A table can contain only one PRIMARY KEY Constraint.

  • All Columns defined Within a PRIMARY KEY Constraint must be defined as NOT NULL.
  • If nullability is not specified, all Columns Participating in a PRIMARY KEY Constraint have their nullability set to NOT NULL.

That is to say:

  • The table can only have a primary key
  • If not specified, fields that are part of the Primary key must be non-null

If you have duplicated values in the key will give error, so just validate/correct/delete the data that do not respect the rules of Primary key that will work

  • I edited the question by adding an example of how I am trying to make the change. If you can point out where the error is thanks.

  • I commented there, if this command is the same as the question constraint is wrong, but can use only add primary key

Browser other questions tagged

You are not signed in. Login or sign up in order to post.