Another syntax for creating primary key


Hello


I have a question about the right way to create primary keys.
Earlier, we were on Oracle 9i and we have upgraded to Oracle 10 g. The question is when creating primary key is allowed to create the unique index and then to create the primary key constraint? or directly create the first key is better? or are there ways to both the same?


for example:
one way:


SQL & gt; CONN u2/u2@db1
Connected.
SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1);


Table created.


SQL & gt; create an index on a (a1) tablespace unique pk_a t1;


The index is created.



SQL & gt; ALTER table a Add (constraint primary key (a1) using index pk_a);


Modified table.
Another way:
SQL & gt; CONN u1/u1@db1
Connected.
SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1)
2.


Table created.


SQL & gt;
SQL & gt; ALTER table a Add (constraint primary key (a1) using index tablespace t1 pk_a)
2.


Modified table.
Which of the two approach is better? or are they the same?


Thank you
Cedric

Oracle will attempt to create the index to apply the constraint. Of course, it is certainly possible that the creation of the index will fail, but you would be just to move the point of failure of the CREATE INDEX statement to the ALTER TABLE statement, assuming that everything else is equal (that is, you create the index in the same tablespace, quotas and tablespace sizes are the same, permissions are not changed, etc.)

It may be preferable in some contexts to create a non-unique index before the creation of the constraint and instruct Oracle to use the non-unique index to apply the constraint. If you decide in the future to make the primary key constraint can be delayed, for example, have a non-unique index allows you to make this change without having to (implicitly), drop and re-create the index. A separate CREATE INDEX statement also influences when you go to remove a constraint / index. If the index was created before the constraint, you can remove the constraint without affecting the index. If the index was created after the constraint, deleting the constraint implicitly removes the index. Normally, particularly with OLTP applications, this doesn't buy you much. Sometimes, however, there are ETL process benefiting from such things.

Justin

Tags: Database

Similar Questions

  • Trigger - use one to create primary key values

    I'm stuck on a simple use to do a TRIGGER that fires when you add new rows to a table and want to Developer SQL to add the primary key value.

    I seem to be able to relax, but it is not inserted the primary key but giving a SQL error: ORA-00947: not enough values.

    Here's what I have.

    CREATE TABLE HF_fishers

    (

    contact_id INT NOT NULL

    , name VARCHAR (25)

    , last_name VARCHAR (35)

    PRIMARY KEY (contact_id)

    );

    CREATE SEQUENCES HF_fishers_seq.

    Then I ran the following trigger:

    CREATE

    HF_fishers_seq_trigger RELAXATION

    BEFORE INSERTING

    ON HF_fishers

    FOR EACH LINE

    BEGIN

    IF (: new.contact_id IS NULL)

    THEN

    : NEW.contact_id: = NVL (: NEW.contact_id)

    HF_fishers_seq. NEXTVAL

    );

    END IF;

    END HF_fishers_seq_trigger;

    =============

    Then I executed the following SQL statement that gives the error.

    INSERT INTO HF_fishers VALUES('Jacob','Muller');

    But if I do everything is good except that it defeats the purpose of relaxation.

    INSERT INTO HF_fishers VALUES(1,'Jacob','Muller');

    MySQL has a nice 'AUTO_INCREMENT' command, but from what I understand in Oracle, I need to set up a trigger to automatically increment a column/cell, which in this case I use for the PRIMARY KEY.

    3003916 wrote:

    OK Jaramillo, I tried as you wrote, but what would be an INSERT statement correct?

    -After the code trigger of Jaramillo

    INSERT INTO HF_fishers (first_name, last_name) values ("Jesse", "Owens"); -I have the trigger but he made the mistake of duplicate key.

    INSERT INTO HF_fishers values (hf_fishers_seq.nextval, 'Jesse', "Owens");  -No trigger but get key duplicated,.

    INSERT INTO HF_fishers VALUES(:NEW_contact_id,'Jesse','Ownes'); -works without the trigger but the "get links" dialog box appears. So not much 'automatic' on this issue,.

    My mistake.  Here is the modified version of the trigger. I removed the CONDITIONAL clause and comes to be a part of the body of the trigger.

    So, I created the table, the sequence, the relaxation and ran the first two insert statements and it worked fine.  The third one you have invites SQL + or any tool you use to enter a value if she sees the ":" colon as a variable binding.  Colon only works in a trigger without asking for confirmation.

    Here is the code and my exit I ran home

    DROP TABLE hf_fishers CASCADE CONSTRAINTS PURGE;
    DROP SEQUENCE hf_fishers_seq;
    
    CREATE TABLE hf_fishers
    (
    contact_id   INTEGER NOT NULL
    ,first_name   VARCHAR(25)
    ,last_name    VARCHAR(35)
    ,PRIMARY KEY (contact_id)
    );
    
    CREATE SEQUENCE hf_fishers_seq;
    
    CREATE OR REPLACE TRIGGER hf_fishers_seq_trigger
       BEFORE INSERT
       ON hf_fishers
       FOR EACH ROW
    BEGIN
    
       IF(:NEW.contact_id IS NULL) THEN
          :NEW.contact_id := hf_fishers_seq.NEXTVAL;
       END IF;
    
    END hf_fishers_seq_trigger;
    
    INSERT INTO hf_fishers(first_name, last_name)
         VALUES ('Jesse', 'Owens');  -- Works with the trigger
    
    INSERT INTO hf_fishers
         VALUES (hf_fishers_seq.nextval, 'Jesse', 'Owens');  --Works without using the trigger body code.
    
    SELECT *
      FROM hf_fishers;
    
    COMMIT;
    

    The output

    Deleted table.

    Elapsed time: 00:00:00.05

    Sequence has fallen.

    Elapsed time: 00:00:00.02

    Table created.

    Elapsed time: 00:00:00.03

    Order of creation.

    Elapsed time: 00:00:00.02

    Trigger created.

    Elapsed time: 00:00:01.05

    1 line of creation.

    Elapsed time: 00:00:00.04

    1 line of creation.

    Elapsed time: 00:00:00.01

    CONTACT_ID FIRST NAME LAST NAME

    ---------- ------------------------- -----------------------------------

    1 Jesse Owens

    2 Jesse Owens

    2 selected lines.

    Elapsed time: 00:00:00.04

    Validation complete.

    Elapsed time: 00:00:00.01

  • Bad generation of DDL for indexes primary key partitioned - lost partitions

    Hello

    In our design of the database, we want to divide some tables and their indexes. The partition type is hash indexes must be local, also divided No problem affecting storage of the table partitions. Also no aucun probleme problem with the index partitions, not included the primary key.

    Our problem appears in the generation of DDL: partitions of tables and indexes are generated fine except the primary partitions it shows key - phrase-'alter table' primary key as if it was not partitioned.

    Apparently indexes primary keys must be generated as the other indices, is it not?

    Thanks in advance,

    Bernat Fabregat

    Published by: Berni 11/29/2010 12:37

    Hello Bernat,

    for local partitioning, you need to create indexes separated on column PK (if you do not already). Set partitioning for this index, and then in the dialog box for the primary key in the physical model:
    (1) in the 'Général' tab, clause "with the help of the index' - select 'by the name of the index.
    (2) in tab 'using Index' - 'Existing Index' drop-down list box - select defined index.

    Global partitioning can be created directly on the primary key in the physical model.

    Philippe

  • How to change the type of source for a primary key on a form?

    Hello

    When creating a form, I put the source type for the primary key of an existing sequence.

    Now, I want to change the source of a trigger.

    Can anyone suggest how do?

    Thanks in advance,
    Annie

    Annie:

    Set the trigger and then delete the process of the page named «Get PK»

    CITY

  • DB sequence for the primary key

    Hello

    I have Table of key primary we use DB sequence in the database itself, for example if start a line (using sql client) DB without primary key sequence will do it for me, because of this trigger.

    (1) my doubt is if I generate A EO off this table I need to explicitly set db sequence for this attribute as this or no need to do this sequence bz DB does good for me!

    (new oracle.jbo.server.SequenceImpl("SEQ_NAME",adf.object.getDBTransaction())).getSequenceNumber()
    
    
    
    

    No, you use a db trigger all what you need to do is to define the type of the attribute DBSeqence. Then the framework will assign a negative value for the PK, which can and will be used as K until you commit the transaction. During this time the bed frame now generated correct sequence of relaxation and rights holders to PK all negative values of the line (and it's child row).

    Don't forget to check DBSequence attributes must have "Refresh on insert" together that it triggers the correct PK is read from the database after insertion.

    Do not use ' (new oracle.jbo.server.SequenceImpl ("SEQ_NAME", adf.object.getDBTransaction ()) .getSequenceNumber () ' attribute is the PK you use triggers to generate the sequence.

    Timo

  • Factor of clustering for the primary key Index

    Hi all

    I have cretead a new table with 1.7 million records with an index of primary key on ID (NUMBER)
    Number of blocks used is arnd 57 K.

    Factor value of clustering on the primary key index is 1.6 million.

    Could you please suggest what can be the reason for such a clustering factor high for the new table.


    Thank you
    Ash N.

    Google is your friend:
    http://www.dbasupport.com/forums/archive/index.php/t-38893.html
    http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:1032431852141
    http://hemantoracledba.blogspot.com.es/2008/01/impact-of-clustering-factor.html

  • Should I create primary keys or foreign first?

    I'm new to sql and a student please bear with me.

    I create a script so that when I run a sequence of tables are created. I created all of my fine tables but now I want to add the primary and foreign keys. I tried to do all this at once before but had problems, my idea was to use alter table instructions and add the constraints of key primary and foreign in this way.

    The thing I want to know is what to build first? Should I do any foreign keys and primary keys or visa versa? Or can I do them sequentially and connect relationships between the tables that I will. Thanks in advance!

    Hello

    One thing to remember as a student is to apply logic to the task at hand. In this case, to create a foreign key, it must refer to a primary key in its definition as well so the KP must exist first. What I tend to do is to break down as statements in separate files or sections separate scripts and execute it in a logical order. IE Tables first, and then of PK and UK followed by the FK etc.. I also prefer to create offline rather than constraints in create table statements.

    Hope this helps

    André

  • Creating primary key in online?

    My database is oracle11g. My environment is 24 * 7.

    I know that we can create indexes online. But here it is the primary key. I do below things... These tasks must not lock the table.

    1 remove the primary key
    2. recreate the primary key
    3 remove the normal index
    4 re-create the normal index.

    Task 4 can be done online. I'm afraid the rest of the task.

    1. no oracle locks the table while dropping the PK?
    2. how to recreate the PK online?
    3 oracle locks the table while removing the index?

    Please let me know.

    Dear Shrinika,

    If you read the ticket of Richard, you will find the answer to your question.

    There is an improvement over 11 g and concurrent transactions are not owned by a lock of index.

    Index lock will wait only active transaction that was created before the create index command.

    Ogan

  • Create primary key also Select

    In Oracle, how we specify a primary key in a creation like the select statement? I ran a simple statement, but received the error ORA-00933. What I have to do two steps with created first table and alter the table to add the key?

    Thank you



    CREATE TABLE Test as
    SELECT
    *
    SOURCE one
    WHERE a.sys = 100
    PK1 CONSTRAINT PRIMARY KEY (account ID)
    SQL>  create table t (a primary key) as select 1 from dual
    /
    Table created.
    
  • Online syntax to create Foreign key with Alter Table statement

    I am a pretty meticulous reader. That being said, from the 4 texts that I read to start to learn SQL, I do not remember and do more that probably not, find a syntax online for the creation of a CF with the statement alter table.

    Just something I thought while I was reading.

    Is there a such syntax?

    And if so someone can give me direction on my code?

    ALTER table emp4 change employee_id key foreign employees of references (employe_id);

    It gives me the option error invalid alter table.

    Any idea would be appreciated.

    Thank you.

    rp0428 wrote:

    A foreign key is a constraint, you must use ADD CONSTRAINT.

    Thare is more than one way to skin a cat:

    SQL > create table tbl (id number, name varchar2 (10))
    2.

    Table created.

    SQL > alter table tbl adds (foreign key references emp (empno))
    2.

    Modified table.

    SQL > select constraint_name,.
    2 constraint_type
    3 from user_constraints
    4 where table_name = 'TBL '.
    5.

    CONSTRAINT_NAME C
    ------------------------------ -
    SYS_C0021920 R

    SQL > drop table tbl purge
    2.

    Deleted table.

    SQL > create table tbl (id number, name varchar2 (10))
    2.

    Table created.

    SQL > alter table tbl change (foreign key references emp (empno))
    2.

    Modified table.

    SQL > select constraint_name,.
    2 constraint_type
    3 from user_constraints
    4 where table_name = 'TBL '.
    5.

    CONSTRAINT_NAME C
    ------------------------------ -
    SYS_C0021921 R

    SQL >

    SY.

  • Creating primary key based on the Date

    Hi all
    I am trying to create a unique ID for each record, based on the date that the record is created. Example, if the folder is created today, I want to the key is 20101130XX where XX is a sequential list of numbers e.g. 01, 02, 03 etc... in the case where more than one person creates a record today.

    If 3 people created record yesterday their unique ID would be

    2010112900
    2010112901
    2010112902

    and then comes the midnight and someone creates a new record, that it would be

    2010113000

    This is intended to give each record with a unique ID that will be used to reference the ticket.

    We are already using the date format, but currently users have to manually enter the id and who can create errors such as 2011112900 when it should have been 2010112900 then instead of 2010 they put 2011

    I'm not sure how to create a trigger to generate this type of unique identification number and would appreciate any help

    Thanks in advance

    Wally

    Never said it was perfect, but then again, it is a rather sticky issue... Reset sequence work would be scheduled to run @ some point... You entered in tables past 24/7? I would say that system could be locked for those 5 minutes sequence is updated, or the table is locked to allow no access while the process is...

    To be honest, that is the question in the design of a key value that is dependent on outside data, as apposed to a surrogate key, which is generated System... Again, you could have at ONCE and have the surrogate for a key key REAL primary and date + sequence as a secondary key for the use of basic unit of carbon...

    Thank you

    Tony Miller
    Webster, TX

    If vegetable oil is made from vegetables, then what is baby oil?

  • What is the syntax for creating a global temporary table using a select query

    HII
    I create a global temporary table using a select query... How to speak of "on commit preserve rows ' who?


    create a table temporary global t1 select * from trn_ordbase on the lines of commit preserve;

    but this is an invalid syntax, then how to talk on commit preserve rows in this? If I don't mention, by default its recital on the validation of deleted rows.

    Please help me on this problem.
    create global temporary table t1 on commit preserve rows
      2  as select * from dual;
    
    Table created.
    
    TUBBY_TUBBZ?
    
  • How to specify the tablespace for a India primary key in create table statement

    How to specify the storage space for a primary key index in a create table statement?
    Does the following statement is true?
    CREATE TABLE 'GPS'||TO_CHAR(SYSDATE+1,'YYYYMMDD')
                ("ID" NUMBER(10,0) NOT NULL ENABLE, 
                "IP_ADDRESS" VARCHAR2(32 BYTE), 
                "EQUIPMENT_ID" VARCHAR2(32 BYTE), 
                "PACKET_DT" DATE, 
                "PACKET" VARCHAR2(255 BYTE), 
                "PACKET_FORMAT" VARCHAR2(32 BYTE), 
                "SAVED_TIME" DATE DEFAULT CURRENT_TIMESTAMP, 
                 CONSTRAINT "UDP_LOG_PK" PRIMARY KEY ("ID") TABLESPACE "INDEX_DATA"
                 )            
                 TABLESPACE "SBM_DATA";   
    Thank you

    Published by: qkc November 9, 2009 13:42

    As orafad noted, you can use the documentation using ESCALATION clause, i.e.

    SQL> ed
    Wrote file afiedt.buf
    
      1  CREATE TABLE GPS
      2              ("ID" NUMBER(10,0) NOT NULL ENABLE,
      3              "IP_ADDRESS" VARCHAR2(32 BYTE),
      4              "EQUIPMENT_ID" VARCHAR2(32 BYTE),
      5              "PACKET_DT" DATE,
      6              "PACKET" VARCHAR2(255 BYTE),
      7              "PACKET_FORMAT" VARCHAR2(32 BYTE),
      8              "SAVED_TIME" DATE DEFAULT CURRENT_TIMESTAMP,
      9               CONSTRAINT "UDP_LOG_PK" PRIMARY KEY ("ID") USING INDEX TABLESP
    ACE "USERS"
     10               )
     11*              TABLESPACE "USERS"
    SQL> /
    
    Table created.
    

    Justin

  • How to refer to the primary key column of newly inserted rows of tabular form

    Hello

    I use APEX 4.2.0.00.27 with Oracle DB 11.2.0.3.0.

    I work with a tabular presentation wizard-created for insert and update a table using the integrated SRM process (sequence 10).  I'm trying to use a process of anonymous block of PL/SQL (sequence 30) to make another manipulation of table after the records were inserted or updated.  The manual process is associated with my tabular form and I use the variables of name of column binding in my program block.

    My (rsn_test) table has 3 columns: test_id (number), test_nbr (number), test_id2 (number).  Test_id column is identified as the primary key and the type of the source already exists a sequence rsn_test_seq.  Column test_id2 gets its default value 0 to a hidden page element.

    I would use my manual process for updating the value of the test_id2 column.  If it's 0 then I want to put the value of the column test_id.  If it is any other value, then it must remain at this value.  My logic works very well for an existing line, but I'm running into a problem with the newly added lines.  The new lines get inserted, but the test_id2 column remains the default value 0.  I can tell the debugger that the SRM process is triggered first and inserts the line, then my manual dealing with fires.  The problem seems to be that the connection variable: TEST_ID for the primary key column remains NULL after insertion.  I don't know how to get the value of the column test_id of my newly created line to use in my PL/SQL block to my update.

    Process of PL/SQL:

    DECLARE
    BEGIN
       :P7_SHOW := NULL;
       :P7_SHOW := NVL(:TEST_ID2,555) || ' and ' || NVL(:TEST_ID,787) || ' and ' || NVL(:TEST_NBR,9999);
       IF :TEST_ID2 = 0 AND :TEST_ID IS NOT NULL THEN
          UPDATE rsn_test
             SET test_id2 = :TEST_ID
           WHERE test_id = :TEST_ID;
       ELSE
          :TEST_ID2 := :TEST_ID2;
       END IF;
    END;
    
    

    Excerpt from the debugger:

    0.01625 0.00010 Processes - point: ON_SUBMIT_BEFORE_COMPUTATION
    0.01635 0.00008 Branch point: Before Computation
    0.01643 0.00003 Process point: AFTER_SUBMIT
    0.01646 0.00022 Tabs: Perform Branching for Tab Requests
    0.01668 0.00008 Branch point: Before Validation
    0.01676 0.00024 Validations:
    0.01700 0.00135 Perform basic and predefined validations:
    0.01835 0.00020 Perform custom validations:
    0.01855 0.00049 ...Validation "TEST_NBR must be numeric" - Type: ITEM_IS_NUMERIC
    0.01904 0.00007 ......Skip for row 1 because row hasn't changed
    0.01911 0.00016 ......Skip for row 2 because row hasn't changed
    0.01927 0.00012 ...Validation "TEST_ID2 must be numeric" - Type: ITEM_IS_NUMERIC
    0.01939 0.00007 ......Skip for row 1 because row hasn't changed
    0.01945 0.00018 ......Skip for row 2 because row hasn't changed
    0.01964 0.00005 Branch point: Before Processing
    0.01968 0.00004 Processes - point: AFTER_SUBMIT
    0.01972 0.00588 ...Process "ApplyMRU" - Type: MULTI_ROW_UPDATE
    0.02560 0.00154 ...Execute Statement: declare function x return varchar2 is begin begin for c1 in ( select "RSN_TEST_SEQ".nextval pk from sys.dual ) loop return c1.pk; end loop; end; return null; end; begin wwv_flow.g_value := x; end;
    0.02714 0.00140 ......Row 3: insert into "APPPCSRSN"."RSN_TEST" ( "TEST_ID", "TEST_NBR", "TEST_ID2") values ( :b1, :b2, :b3)
    0.02854 0.00011 ...Process "ApplyMRD" - Type: MULTI_ROW_DELETE
    0.02865 0.00004 ......Skip because condition or authorization evaluates to FALSE
    0.02869 0.00015 ...Process "Process Submit" - Type: PLSQL
    0.02884 0.00007 ......Skip for row 1 because row hasn't changed
    0.02891 0.00012 ......Skip for row 2 because row hasn't changed
    0.02903 0.00012 ......Process row 3
    0.02915 0.00429 ...Execute Statement: begin DECLARE BEGIN :P7_SHOW := NULL; :P7_SHOW := NVL(:TEST_ID2,555) || ' and ' || NVL(:TEST_ID,787) || ' and ' || NVL(:TEST_NBR,9999); IF :TEST_ID2 = 0 AND :TEST_ID IS NOT NULL THEN UPDATE rsn_test SET test_id2 = :TEST_NBR WHERE test_id = :TEST_ID; ELSE :TEST_ID2 := :TEST_ID2; END IF; END; end;
    0.03344 0.00013 ...Session State: Saved Item "P7_SHOW" New Value="0 and 787 and 1300"
    0.03356 0.00004 Branch point: After Processing
    0.03360 0.00048 ...Evaluating Branch: "AFTER_PROCESSING" Type: REDIRECT_URL Button: (No Button Pressed) Condition: (Unconditional)
    0.03407 0.00013 Redirecting to f?p=290:7:8717971109610:::::&success_msg=0%20row(s)%20updated%2C%201%20row(s)%20inserted.Success%2FEBD244168556408CBA714E3974918C09%2F
    0.03420 0.00012 Stop APEX Engine detected
    0.03432 0.00007 Stop APEX Engine detected
    0.03439 - Final commit
    
    

    Any suggestions?

    I have run tests on

    https://apex.Oracle.com/pls/apex/f?p=83488:1 demo/demo

    to see your problem.

    I have 2 solution for your problem.
    I add trial NOT tabular just usual block of PL/SQL

    BEGIN
    I'm IN (SELECT TEST_ID FROM RSN_TEST WHERE TEST_ID2 = 0)
    LOOP
          UPDATE RSN_TEST
             SET test_id2 = TEST_ID
           WHERE test_id = i.TEST_ID;
      END LOOP;
    END;

    and works very well, you can see in the sample.

    The other solution is to show new generated TEST_ID

    Adding a sequence as a default value for a column in a table field

    And to execute your procedure.

    I get how is with the good luck of time.

    By

  • How to fill out the table foreign key to the primary key form

    Hi all

    I'm stuck in this problem for 3 days, and I'm about to research and implement solutions on the internet.

    I have two tables

    create table prim (a number primary key, b varchar2 (100));

    create table CHILD (a number references (a) prim, varchar2 (100)) c;

    I created a page for PRIM table.

    = page name form on PRIM2

    I have manually two columns for the CHILD table to know

    P26_A_1 (for the primary key in the CHILD table)

    P26_C (for the column in the CHILD Table c)

    now when the user clicks on the button CREATE, a row must be inserted into the child table.

    I want to assign the P26_A to P26_A_1 during the validation process, so that a line must be inserted into the PRIM table as well as in the CHILD table.

    How to do this?

    I downloaded my application page in https://apex.oracle.com

    my workspace identifiers are inferior to

    name of the workspace = IMBERT

    username = demo

    password = demo

    kindly guide me.

    Thank you.

    Hello

    I created a new page (page 30) similar to your page and added the insertion of the child. It just check the page and code. It works now, when you insert the prim file is triggered a second trial which inserts the child record manually.

    On page 26 it was some sort of mistake, was easier to create a new as it was almost a standard form.

    Concerning

    Bottom

Maybe you are looking for