I have an existing table called Persion
. In this table I have 5 columns:
Try using this code:
ALTER TABLE `table name`
CHANGE COLUMN `column name` `column name` datatype NOT NULL,
ADD PRIMARY KEY (`column name`) ;
There is already an primary key in your table. You can't just add primary key,otherwise will cause error. Because there is one primary key for sql table.
First, you have to drop your old primary key.
MySQL:
ALTER TABLE Persion
DROP PRIMARY KEY;
SQL Server / Oracle / MS Access:
ALTER TABLE Persion
DROP CONSTRAINT 'constraint name';
You have to find the constraint name in your table. If you had given constraint name when you created table,you can easily use the constraint name(ex:PK_Persion).
Second,Add primary key.
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persion ADD PRIMARY KEY (PersionId,Pname,PMID);
or the better one below
ALTER TABLE Persion ADD CONSTRAINT PK_Persion PRIMARY KEY (PersionId,Pname,PMID);
This can set constraint name by developer. It's more easily to maintain the table.
I got a little confuse when i have looked all answers. So I research some document to find every detail. Hope this answer can help other SQL beginner.
Reference:https://www.w3schools.com/sql/sql_primarykey.asp
If you add primary key constraint
ALTER TABLE <TABLE NAME> ADD CONSTRAINT <CONSTRAINT NAME> PRIMARY KEY <COLUMNNAME>
for example:
ALTER TABLE DEPT ADD CONSTRAINT PK_DEPT PRIMARY KEY (DEPTNO)
The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain UNIQUE values and column cannot contain NULL Values.
-- DROP current primary key
ALTER TABLE tblPersons DROP CONSTRAINT <constraint_name>
Example:
ALTER TABLE tblPersons
DROP CONSTRAINT P_Id;
-- ALTER TABLE tblpersion
ALTER TABLE tblpersion add primary key (P_Id,LastName)
-- create new primary key constraint
ALTER TABLE dbo.persion
ADD CONSTRAINT PK_persionId PRIMARY KEY NONCLUSTERED (pmid, persionId);
is a better solution because you have control over the naming of the primary_key.
It's better than just using
ALTER TABLE Persion ADD PRIMARY KEY(persionId,Pname,PMID)
which yeilds randomized names and can cause problems when scripting out or comparing databases
drop constraint and recreate it
alter table Persion drop CONSTRAINT <constraint_name>
alter table Persion add primary key (persionId,Pname,PMID)
edit:
you can find the constraint name by using the query below:
select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='Persion'
and type_desc LIKE '%CONSTRAINT'