In today’s article, we will learn how to add a primary key to a column in a table containing data in an Oracle database.
If we want to add a primary key to a column of a table with data and we get an error, the following process is followed.
1. We create a new table from the table to which the Primary Key will be added.
1 2 | CREATE TABLE HEMW.IPTV_TEST_ABONE_NEW TABLESPACE HE_USERS AS (SELECT * FROM HEMW.IPTV_TEST_ABONE); |
2. We Truncate the table to which the Primary Key will be added.
1 | TRUNCATE TABLE HEMW.IPTV_TEST_ABONE; |
3. Now we add a Primary Key to the table to which the Primary Key will be added.
1 2 | ALTER TABLE HEMW.IPTV_TEST_ABONE ADD CONSTRAINT ACCOUNTNAME__ITA_PK PRIMARY KEY (ACCOUNTNAME); |
4. We insert data from the newly created table into the original table.
1 2 | INSERT INTO HEMW.IPTV_TEST_ABONE SELECT * FROM HEMW.IPTV_TEST_ABONE_NEW; COMMIT; |