Altering Primary Key Constraint

hi this may sound silly .
but is it possible to alter a primary key constraint and add another column to it ?
eg. >desc t1
c1 number(3) not null
c2 number(3)
here I have created primary key on column c1.
Now I want to alter this constraint and add second column also as part of primary key constraint (so that it will be composite primary key )
How do i do that ? Do the column needs to be empty ?
Thanks

You should use ALTER TABLE DROP CONSTRAINT / ADD CONSTRAINT option.
Do the column needs to be empty ?Because primary key constraint supposes NOT NULL constraints for columns
included into primary key, all columns havn't to have nulls values (NOT NULL constraint will be added to c2 column):
SQL> create table t1 (c1 number(3) not null, c2 number(3));
Table created.
SQL> alter table t1 add constraint t1_pk primary key(c1);
Table altered.
SQL> insert into t1 values(1,1);
1 row created.
SQL> insert into t1 values(2,null);
1 row created.
SQL> commit;
Commit complete.
SQL> alter table t1 drop constraint t1_pk;
Table altered.
SQL> alter table t1 add constraint t1_pk primary key (c1,c2);
alter table t1 add constraint t1_pk primary key (c1,c2)
ERROR at line 1:
ORA-01449: column contains NULL values; cannot alter to NOT NULL
SQL> update t1 set c2 = 3;
2 rows updated.
SQL> alter table t1 add constraint t1_pk primary key (c1,c2);
Table altered.
SQL> desc t1
Name                                      Null?    Type
C1                                        NOT NULL NUMBER(3)
C2                                        NOT NULL NUMBER(3)Rgds.

Similar Messages

  • Altering Primary Key constraint on a table i Oracle 10G

    Hi All,
    Can anyone tell me how to alter a primary key constraint on any table. My concern is that, suppose i have a table called 'Employee' where only 'EmployeeName' is added as a primary ket constaint. Now i want to alter this P.K. constarint to add 'EmployeeName' and 'DateOfBirth' as a primary key. Can anyone suggest me how can i achieve that? Any help will be highly appreciated.

    hi,
    you need to drop the constraint and recreate it.
    SQL> conn scott/tiger@alpspso
    Connected.
    SQL> create table test (id number constraint id_pk primary key,name varchar(30));
    create table test (id number constraint id_pk primary key,name varchar(30))
    ERROR at line 1:
    ORA-00955: name is already used by an existing object
    SQL> create table test_table (id number constraint id_pk primary key,name varchar(30))
    Table created.
    SQL> alter table test_table modify constraint id_pk primary key(id,name);
    alter table test_table modify constraint id_pk primary key(id,name)
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    SQL> alter table test_table modify constraint id_pk(id,name);
    alter table test_table modify constraint id_pk(id,name)
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    SQL> alter table test_table modify primary key(id,name);
    alter table test_table modify primary key(id,name)
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    SQL> alter table drop constraint id_pk;
    alter table drop constraint id_pk
    ERROR at line 1:
    ORA-00903: invalid table name
    SQL> alter table test_table drop constraint id_pk;
    Table altered.
    SQL> alter table test_table add constraint id_pk primary_key(id,name);
    alter table test_table add constraint id_pk primary_key(id,name)
    ERROR at line 1:
    ORA-00902: invalid datatype
    SQL> alter table test_table add constraint id_pk primary key(id,name);
    Table altered.
    Regards.
    Navneet

  • Alter primary key constraint - efficient way

    Please let me know the efficient way to alter the primary key constraint in a table(it has millions of records).
    Thanks.

    Do you want to have a NCI on PK instead of CI? You have to drop a constraint.. You know , a  constraint is a logical component  but the index (unique) that SQL Server creates behind the scene is a physical implementation...
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Unable to enforce Primary Key constraint with my code

    Hi Guys
    I have a table that contains 2 columns: code and description (defined as not null). I am using oracle forms 10g, if I inset a new row both the columns: code and description should have data e.g. code: 001 and description: Main Store...
    So on forms I have an on-update trigger on block level that handles the error messages but if the user has to update the description this trigger blocks him because the value for the code i.e. 001 is already on the database but if I remove the piece of code (the first IF block on my code together with a cursor and the entire declaration section)then the primary key constraint is violated: the code is as follows:
    declare
    v_store_code store_types.code%type;
    cursor store_codes is
    select a.code
    from store_types a
    where a.code = :b1.code;
    begin
    open store_codes;
    fetch store_codes into v_store_code;
    if ( store_codes%found ) then
    Message('The Store Code you have entered already exists on the Store_Types table, please enter another code!');
    Message('The Store Code you have entered already exists on the Store_Types table, please enter another code!');
    close store_codes;
    raise form_trigger_failure;
    end if;
    close store_codes;
    if :b1.code is not null and :b1.description is null then
         message('If the Store Code has been captured, then the Store Description must be captured!');
         message('If the Store Code has been captured, then the Store Description must be captured!');
    raise form_trigger_failure;
    end if;
    if :b1.description is not null and :b1.code is null then
         message('If the Store Description has been captured, then the Store code must be captured!');
         message('If the Store Description has been captured, then the Store code must be captured!');
         raise form_trigger_failure;
    end if;
    exception
              when others then
                   message(sqlerrm);
                   raise form_trigger_failure;
    end;
    My main intention here is: the user should be able to update the description field and save the changes without violating primary key on the column: code ...... please help me guys...

    ICM
    Sir as far I could understand , your problem is that your wanna allow the end users to update the Store_description , and Store_code..
    So on forms I have an on-update trigger on block level that handles the error messages but if the user has to update the description this trigger blocks him because the value for the code i.e. 001 is already on the databaseif it's right then why don't you have unique key constraints Store_description?
    alter the tables and apply unique key constraint...
    and no need to write this code
    f :b1.code is not null and :b1.description is null then
    message('If the Store Code has been captured, then the Store Description must be captured!');
    message('If the Store Code has been captured, then the Store Description must be captured!');
    raise form_trigger_failure;
    end if;because as you mentioned
    code and description (defined as not null)if they are already under not null constraints then no need to handle this in coding..
    he/she must be able to change the description and save the changes without affecting the code i.e.:Sir I think updation in records can only be performed when the forms is in query mode e.g execute query, have all/desired records and then make changes
    (1)description is in unique key constraint it can't be duplicated ..
    (2)code is PK it can never be duplicated...
    for this I would suggest you to have a update button on forms , when-button-pressed trigger sets property of block (update_allowed, property_true);
    and check the code of unique key violation code from oracle form's help , when that error code raise up you can show those message
    Message('The Store Code you have entered already exists on the Store_Types table, please enter another code!');
    Message('The Store Code you have entered already exists on the Store_Types table, please enter another code!');I hope it could do something for you
    thanks
    regards:
    usman noshahi

  • Primary Key Constraint

    dear members,
    I have a tables named orders and part. Both of them contain common column named partnum. The column partnum in the table orders contains duplicates. I tried to add a primary key constraint to that column partnum but sql*plus gave me an error unique constraint voilation.
    The reason for the error was because of duplicates in the column partnum but if i want to assign a column as a primary key and suppose it contains duplicates then how can i do that ? I cannot alter my table orders data, in this case how should i proceed further!!!

    You cannot use a single column with duplicates or null values as a primary key. It's that simple.
    If a given single column has duplicates values its not a possible candidate for a primary key. It has to be an unique value.
    I'm not fully sure here but kinda feels like your table "orders" has information about all orders (purchase, sell, whatever) related with "parts". So, this way if its possible that orders has duplicates because you have several orders on the same "part". I think "part" has a primary key on "partnum". If there's a need for a pk in "orders" maybe you have an additional column, let's call it "ordernum".

  • Modifying column adding primary key constraint

    how can we alter a table and modify a column and add a primary key constraint to it??

    987018 wrote:
    can't we add a primary key constraint using the modify command?If the column already exists, and ther is no existing primary key, then
    SQL> create table t (id number, descr varchar2(10));
    Table created.
    SQL> alter table t modify (id not null primary key);
    Table altered.If the column does not yet exist and ther is no primary key then:
    SQL> create table t1 (descr varchar2(10));
    Table created.
    SQL> alter table t1 add (id number not null primary key);
    Table altered.John

  • Index of a primary key constraint

    Hi,
    I have to remove (temporarily) a primary key constraint (of a table) to can convert its columns to unicode ones.
    Found that after delete the PK (with "ALTER TABLE %s DROP CONSTRAINT %s" SQL command) sometimes remain its unique index, sometimes not.
    I guess the system does not remove it, if it was created by user command (and not with PK by system).
    Am I right?
    Can I get this information of the property of index of PK? (to be able to decide to need delete it as a second step)
    Please do not offer to check its existance after deletion of PK :-)
    I had used to get index properties with "user_indexes" view.
    Regards,
    Imre

    Found that after delete the PK (with "ALTER TABLE %s DROP CONSTRAINT %s" SQL command) sometimes remain its unique index, sometimes not.You may force to always delete the index by
    alter table my_table drop primary key drop index;or alternatively
    alter table my_table drop primary key keep index;

  • Modify a primary key constraint

    Hi,
    I'm starting with oracle, and I have two doubts that can't handle after searching on the internet.
    1º It's possible to make an ALTER TABLE of a CONSTRAINT DEFAULT?. Maybe you think that the question should be in another way like this: Does oracle database take the default condition as a constraint?. As long as I know, doesn't do that.
    2º It's possible, with an ALTER TABLE, to MODIFY a CONSTRAINT of a PRIMARY KEY, to add another more field?
    I've been searching on the internet, but I didn't find a clear answer. I'm using oracle 10g express edition.
    Thank you very much.
    P.D.:Sorry for my english it's not very good.

    #2 - You can not 'add a column to the primary-key constraint of a table' with a single ALTER, but you can drop and re-create the primary key constraint (including the additional column).
    13:25:26> create table t1 (a number primary key, b number, c number );
    Table created.
    Elapsed: 00:00:00.09
    13:25:46> alter table t1 drop primary key;
    Table altered.
    Elapsed: 00:00:00.06
    13:25:47> alter table t1 add primary key (a,b);
    Table altered.
    Elapsed: 00:00:00.09But you will not be able to drop the primary key of an index-organized table.
    13:25:47> create table t2 (a number primary key, b number, c number ) organization index;
    Table created.
    Elapsed: 00:00:00.03
    13:25:59> alter table t2 drop primary key;
    alter table t2 drop primary key
    ERROR at line 1:
    ORA-25188: cannot drop/disable/defer the primary key constraint for
    index-organized tables or sorted hash cluster
    Elapsed: 00:00:00.00
    13:25:59> #1 - I'm not sure I understand your question , but you can alter a table's column to have a default. This is not a 'constraint', but a default. It only has effect when you perform an insert which does not include that column.
    13:31:23> alter table t1 modify (c default 3.14);
    Table altered.
    Elapsed: 00:00:00.04
    13:31:24> insert into t1 (a,b,c) values (1,2,3);
    1 row created.
    Elapsed: 00:00:00.01
    13:31:24> insert into t1 (a,b,c) values (4,5,NULL);
    1 row created.
    Elapsed: 00:00:00.00
    13:31:24> insert into t1 (a,b) values(6,7);
    1 row created.
    Elapsed: 00:00:00.01
    13:31:24> select * from t1;
             A          B          C
             1          2          3
             4          5
             6          7       3.14
    3 rows selected.
    Elapsed: 00:00:00.18

  • Large table, primary key constraint

    I have migrated a table from 8i to 9i that is over 300 million rows. I migrated the the table to a 9i database without constraints or indexes.
    I have successfully created a composite index of two columns, t1 varchar2(512), t2 varchar2(32). This index took nearly 16 hours to create.
    I am now trying to create a primary key based on that index with the following sql:
    alter table table1
    add constraint table1_t1_t2_pk primary key(t1,t2)
    using index table1_t1_t2_idx
    nologging
    This process has taken over 24 hours and is well into the second day. Studio reports it will take an additional 15 hours to create.
    My questions are these?
    1. Is my syntax okay?
    2. I thought that by creating a primary key on an existing index, that another index is not being created. I thought it would be faster this way. Why is it taking a lot longer to create then the index it is based upon?
    3. Is there a more efficient method (other than parallel query) to create this index/constraint on such a large table? What happens when I go production and need to recreate this index if I have a failure. I have never had to do this before. I can't be down for 48 hours to create an index. What other alternatives do I have?
    The table is partit[i]Long postings are being truncated to ~1 kB at this time.

    Is INDEX table1_t1_t2_idx UNIQUE? If it's not that might explain why building the primary key constraint takes longer.
    I think the USING INDEX clause with an existing index is intended mainly for different UNIQUE constraints to share the same index. In your situation I think you would be better off just building the primary key constraint.
    Cheers, APC

  • How add primary key constraint to already existing table with data

    I want apply primary key constraint to already existing table with data
    is there any command or way to do

    Alternatively, assuming you want to ensure uniqueness in your primary key column you can do this:
    alter table <table name> add constraint <cons name> primary key (col1,col2) exceptions into <exception_table>
    If the altter table statement fails this will populate the EXCEPTIONS table with the rows that contain duplicate values for (col1,col2).
    You will need to run (or get a DBA to run) a script called UTLEXCPT.SQL (which will be in the $ORACLE_HOME/rdbms/admin directory) if you don't already have an EXCEPTIONS table.
    Cheers, APC

  • SQL Server - primary key constraint modify

    Hi,
    I have a table with many records. I wanted to modify the primary key constraint. The only way to alter the primary key constraint is to drop and create again. Please let me if it is right.
    Can we create primary key constraint with NoCheck. Since we have lots of records in our table, creating primary key constraint takes more time because it is checking the existing data. Please provide your comments.
    Thanks.

    >>I have a table with many records. I wanted to modify the primary key constraint. The only way to alter the primary key constraint is to drop and create again. Please let me if it is right.
    http://technet.microsoft.com/en-us/library/ms181043(v=sql.105).aspx
    Note
    To modify a PRIMARY KEY constraint, you must first delete the existing PRIMARY KEY constraint and then re-create it with the new definition.
    >>Can we create primary key constraint with NoCheck. Since we have lots of records in our table, creating primary key constraint takes more time because it is checking the existing data. Please provide your comments.
    http://msdn.microsoft.com/en-IN/library/ms188066.aspx
    When FOREIGN KEY or CHECK constraints are added, all existing data is verified for constraint violations unless the WITH
    NOCHECK option is specified. If any violations occur, ALTER TABLE fails and an error is returned. When a new PRIMARY KEY or UNIQUE constraint is added to an existing column, the data in the column or columns must be unique. If duplicate values are found, ALTER
    TABLE fails. The WITH NOCHECK option has no effect when PRIMARY KEY or UNIQUE constraints are added.
    Satheesh
    My Blog |
    How to ask questions in technical forum

  • Drop primary key constraint

    Hello everyone,
    I have a form with fields sno, sname. I added a new field 'class' which is a list box with values 1 to 10.All the information related to sno, sname and class are stored in the student table.The class field has primary key.Now i want to drop the primary key which exists on this class field. So I executed "alter table student drop primary key(class);
    It displayed an error message:ORA-01735:invalid alter table option. The reason why I want to drop this primary key is because when i try to open the legacy records on this form which do not have this new field does not allow me to save this form as this field has primary key constraint. If I can drop this constarint then I can update the student table with some default value in this class field for the legacy records as this field would be null for those records.Could any one let me know how to drop the primary key ?
    Thanks,
    Prathima

    instead to drop, disable the constraint and try.

  • DISABLE primary key constraint

    Hello,
    let me know whats meaning by this....
    Here, it creates a primary key and disable it... So whats the purpose of doing this...
    (defines and disables an integrity constraint)
    Constraint is DISABLED. is it in VALIDATE state / NO-VALIDATE state)
    CREATE TABLE emp (
    empno NUMBER(5) PRIMARY KEY DISABLE, . . . ;
    ALTER TABLE emp
    ADD PRIMARY KEY (empno) DISABLE;
    Thanks
    Edited by: Zerandib on Nov 12, 2008 6:47 AM

    Having just done this this morning, let me have a go at explaining one possible use for this feature:
    I am bulk-loading some data into a table. I know that some of the rows in that data duplicates other rows, and that I need to clean out those duplicates.
    The quickest way of detecting duplicates I know of is to attempt to switch on a primary or unique key constraint and have the duplicate records written out to an EXCEPTIONS table. Therefore, I create my loading table with a primary key constraint DISABLED, so that I can actually perform the data load which I know will violate the constraint. If I'd created it enabled, which is the default, the bulk load would never be able to insert anything into the table, after all. When the load is finished, I do this:
    alter table bulk_load enable constraint bulk_load_pk exceptions into exceptions;...and then I can use other techniques to use the new contents of the EXCEPTIONS table to work out which rows from the BULK_LOAD table to delete to clear out the duplicates.
    All constraints when first created are in the enabled validate state, unless you specify otherwise. If you miss out the validate/novalidate keyword, in other words, your constraint will be created as VALIDATE.
    Hope that helps a little.

  • Unusual Primary Key Constraint violation

    When using Apex collections from time to time this unique constraint error happens.
    ORA-00001: unique constraint (FLOWS_030000.WWV_FLOW_COLLECTIONS_UK) violated
    Now, I can't figure out why this constraint would be happening as we check for the existence of a collection before trying to create one, and the constraint relies on a number of values which we can't modify.
    All of our collection operations are done using the following APEX_COLLECTION calls
    COLLECTION_MEMBER_COUNT
    COLLECTION_EXISTS
    CREATE_OR_TRUNCATE_COLLECTION
    ADD_MEMBER
    DELETE_MEMBERS
    As I don't modify any data inside of the collections using any methods other than these above API calls I'm a bit confused.
    It's almost impossible for me to reproduce the error as it happens very rarely, in addition, most of the time performing the same action again after the constraint error has happened will succeed.
    Any ideas what I might be doing that could cause this?
    Thanks in advance,
    Joe

    I'm not sure if this will help but here's some more info:
    1. The constraint being violated is not a primary key constraint but a unique constraint as defined by:alter table wwv_flow_collections$
        add constraint wwv_flow_collections_uk
        unique(session_id, user_id, flow_id, collection_name, security_group_id)
    /2. The CREATE_OR_TRUNCATE_COLLECTION procedure first checks for the existence of a collection with those 5 keys. If found, it does:    delete wwv_flow_collections$ where id = <the id of the existing collection>;This delete cascades to rows in wwv_flow_collection_members$.
    Then, whether the "truncate" occurred or not it does this:    insert into wwv_flow_collections$( collection_name ) values( upper(p_collection_name));3. The TRUNCATE_COLLECTION procedure requires that the named collection exists, fetches its ID and then:delete wwv_flow_collection_members$ m where m.collection_id = <the id of the existing collection>;4.Of the two scenarios Joe showed us, the first one creates the failure condition (assuming two concurrent sessions) by allowing an insert to be performed, i.e., the "create collection" action. Even if the first inserter takes a while to commit, the second one will wait on a lock until the first inserter commits, then it will attempt an insert and raise the UK violation. In the second scenario, nobody ever inserts; only deletes from collections_members$ are issued (assuming the create_collection procedure is never called).
    Scott
    P.S. My head hasn't hurt this bad since Vikas's background job puzzler (Re: Background jobs

  • Creating primary key constraint

    hi,
    if i have a table created, and i inserted say around 10 records ( there are no primary key or any other constraints ) , after inserting those 10 records now can i create a primary key constraint with enable novalidate option ?
    thanks

    No, you can create a PK Constraint which is initially disabled:
    alter table t add constraint t_pk primary key(owner) disable;But when you try:
    alter table t enable novalidate constraint t_pk;You will get a ORA-02437 Error if there are duplicat values (Oracle 10g).
    Dim

Maybe you are looking for

  • Actions in PSE 8

    I read that PSE 8 now has a funtion for actions but can't find it anywhere in the programme (mac version). Can anybody help me?

  • How can I get Firefox to remember my open tabs the way it once did?

    In the past, each time I reopened Firefox, the tabs which I had had opened opened back up. But the other day I accidentally installed a "Radio.... something or other" toolbar while trying to listen to an ESPN press conference. After I added that tool

  • Installing oracle 10.1.0.5

    Hi, I am installing 10.1.0.5 on windows 2003 32 bit. I have installed the base version software only (10.1.0.2). I have downloaded 10.1.0.5 patch set. In the disk1 I have clicked setup.exe and installed the patchset on the same oracle home as 10.1.0.

  • Please Help...why does my screen keep going to black in fcp?

    I have just brought imac g5 (older version through private sale) and completed a beginners fcp course. When and got a lacie 250 , shot some stuff which I managed to capture! Then just tried to open project and now the screen keeps going to full black

  • Color Profiles visible in a pallete/panel, like in Photoshop?

    Is it possible to view your InDesign document's current color profile? I can see the profile in Photoshop (Info Panel) and in Illustrator (Document Info Panel) but not in InDesign. Is there an easy way to view the profiles of a placed document in any