Can we make existing column as primary key?


Can we make existing column as primary key?



I Have one column name Token and I'm generating random numbers and saving it as token but sometimes it saves duplicate tokens so I want to make it unique.



I just want to know will it affect existing records





Did you use php to interact with sql?
– Vito Ferrulli
Jun 29 at 9:19





@VitoFerrulli Yes
– Jordan
Jun 29 at 9:41




3 Answers
3



If you try to add a unique constraint (or primary key constraint) to a column that contains non-unique values, the alter statement will just fail. You need to first update the column so all values are unique (or remove duplicates), and then alter the table.


alter





Thank You. I think it will help me
– Jordan
Jun 29 at 10:09



Try doing this


ALTER table_namePersons ADD UNIQUE (Token);



After doing this if you'll try to insert a duplicate key you will have an error and catching it you can generate another token





He'd be getting errors with this, since he has duplicates already on that column
– Caldazar
Jun 29 at 9:08





Oh right I did not think he had already duplicates records
– Vito Ferrulli
Jun 29 at 9:38


ALTER table Student add primary key (studentID)



Use the Alter command to edit table's DDL and then add a primary key to it by specifying the column.
If the primary key already exist, then first you will have to drop it before defining another PK by -


ALTER table STUDENT drop CONSTRAINT <constraint_name>





For setting a Primary Key on a column that has duplicates, you will have to get rid of them first.
– devutkarsh
Jun 29 at 9:10






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV