Creating an unique index instaed of using primary key index

Hi ,
I heard in a debate sometimes it's better to create a unique index on a column and using it instaed of using primary key index in oracle.I couldn't understand what the reason propely.
Can anyone please help me in thsi topic if it is a valid one .
Thanks in advance

Hi,
They are exactly NOT identical.
1. Unique key can have NULL values where primary keys can't.
2. Primary key is fundamentally those keys which do not change. I mean updating a primary key is not a good idea.
SQL> drop table test;
Table dropped.
SQL> create table test ( a number(2));
Table created.
SQL> ed
Wrote file afiedt.buf
  1* create unique index test_idx on test(a)
SQL> /
Index created.
SQL> ed
Wrote file afiedt.buf
  1* insert into test values(NULL)
SQL> /
1 row created.
SQL> drop table test;
Table dropped.
SQL>
SQL> create table test ( a number(2) primary key);
Table created.
SQL> insert into test values(NULL);
insert into test values(NULL)
ERROR at line 1:
ORA-01400: cannot insert NULL into ("HR"."TEST"."A")
SQL>Cheers,
Edited by: Avinash Tripathi on Nov 24, 2009 11:17 AM

Similar Messages

  • Hi i have created a unique index on table on 3 columns.

    Hi i have created a unique index on table on 3 columns.I want to know when i have 2 records
    which contain same values in 2 fields and the 3rd field contains a null
    will unique index allow me to insert these records.

    Robert Angel wrote:
    This must be one time when null = null. ;)
    regards,
    Robert.Not really, it is more the case that the non-null columns need to be unique. Your second attempt failed because there was already an index entry with 'a', 'b', and the lack of a value for column c gave Oracle no way to differentiate between the two rows so they are not unique.
    A subtle, but conceptually important difference. :-)
    John

  • JDeveloper 10g Creating a new record with trigger sequence primary key

    Hi there, I'm sorry to post this incredibly simple question and I'm sure that someone must have answered this on this forum before but the searching of this site is incredible slow and painful and after 30 mins I can't find help.
    I am using a struts Data Action to create a new record in the database and then being forwarded to an edit page where I can enter the new details. Then when the details are entered I am clicking an update button and returning to a browse screen where I can either commit the change to the database or rollback. Sounds pretty simple but I am really struggling with trying to get the trigger of the number sequence to work properly.
    Ideally I would like to click the create new record button and then the primary key/triggered sequence number is already displayed on the empty form...
    ... but if this is too tricky or not possible then I would like the user to either not enter any value in the key field (which currently causes error - JBO-27014: Attribute PoNo in PO_SYS_MODULE.PoSystemView1 is required) OR the user enters a number and the trigger overwrites this number with the next in the sequence.
    I can enter a new record if I look in the manager console and see the next number in the sequence and then create the record using this number and then click commit twice, as the first time I get the error: JBO-25019: Entity row of key oracle.jbo.Key[154 ] not found in PoSystem. Or if I enter a value 5 times greater than the next in the sequence I have to click the commit button 5 extra times to get the sequence to match the input.
    I hope that this lengthy explanation fills you in on my problem, there must be a simple solution to this and I will be VERY grateful to anyone who can help me.
    Many thanks
    Ben Sayers (clearly a newbie)

    Hi,
    ADF Business Components handles this for you - unless yo prefer doing this manually. In the Entity Object, set the PK attribute's type to DBSequence. Then create a database sequence and use a database trigger to add the sequence value on insert
    Frank

  • How do I use Primary Key and RowID in Materialized View Logs and MVs

    How do I use Primary Key and RowID in Materialized View Logs and Materialized Views????
    I don’t understand in the Materalized View Logs the diference between Primary Key and RowID. Besides, I could choose both Primary Key and RowID.
    When I have to use RowID?? Why?? And Primary Key??? And both, Primary Key and RowID????
    Thank you very much!

    Yes, I have already read it...
    But for example I don’t Understand:
    This is the example 8-1
    CREATE MATERIALIZED VIEW LOG ON products
    WITH SEQUENCE, ROWID
    (prod_id, prod_name, prod_desc, prod_subcategory, prod_subcat_desc, prod_
    category, prod_cat_desc, prod_weight_class, prod_unit_of_measure, prod_pack_
    size, supplier_id, prod_status, prod_list_price, prod_min_price)
    INCLUDING NEW VALUES;
    But if I create a Materialized View with TOAD if I choose a KEY field I receive the error:
    ORA-12026: invalid filter column detected
    Then I have to take out the Key (in the above example prod_id)
    And then the script is
    CREATE MATERIALIZED VIEW LOG ON products
    WITH ROWID, SEQUENCE, PRIMARY KEY!!!!!!!!!!!!!!!!!!!!
    (prod_id, prod_name, prod_desc, prod_subcategory, prod_subcat_desc, prod_
    category, prod_cat_desc, prod_weight_class, prod_unit_of_measure, prod_pack_
    size, supplier_id, prod_status, prod_list_price, prod_min_price)
    INCLUDING NEW VALUES;
    I have PRIMARY KEY in the definition (I don’t choose it) and I don’t have the prod_id field
    Why is it????
    Note: If I execute the script to create the MV Log manually the PRIMARY KEY option NO IS in the script and the prod_id field either is in the script.
    And on the other hand,
    What is this:
    CREATE MATERIALIZED VIEW LOG ON sales
    WITH ROWID;
    CREATE MATERIALIZED VIEW LOG ON times
    WITH ROWID;
    CREATE MATERIALIZED VIEW LOG ON customers
    WITH ROWID;
    These MATERIALIZED VIEW LOG contain any fields????
    Or it contain the primary key fields of this tables (sales, times and customers)??? Then, Why is it ROWID instead of PRIMARY KEY????
    Thanks!

  • Error while creating the Unique Index of the Primary Key of an Item

    Hi all,
    I have deployed a new item (CO_CONTRACTUNIT_PRODUCT) in my publication. The deploy appears to be successfull as the item can be seen in the repository through the Mobile Manager.
    The problem occurs when i sync my local DB to get the item offline. While synchronizing, the following error appears, both in the sync window and the log file ol_sync.log.
    "ERROR",POL-5130,"11/09/2010 11:43:52","table or view %s.%s not found:CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID","DB_ROSHNI"
    However, the debug file gives this other error regarding this table.
    ALL_INDEX:CREATE UNIQUE INDEX "TPCO_CONTRACTUNIT_PRODUCT_PK" ON CO_CONTRACTUNIT_PRODUCT (CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID) -5130Error at C:\ADE\omeprod_ol103021\olite\db\build\win\ocapi\..\..\..\src\ocapi\allindexes.cpp line:329 rc:-5130
    Build date Mar 29 2010
    okErr=(table or view %s.%s not found)
    mess=(CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID)
    AddLog(-5130 "ERROR",POL-5130,"11/09/2010 11:43:52","table or view %s.%s not found:CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID","DB_ROSHNI")
    But the index that is being created and is giving the error is the index created automatically with the Primary Key of the table, and so nothing has been modified in that.
    The primary key of the table is created with the three columns that are part of the index that is returning the error.
    As I could not solve the error, I tried to drop and re-create the item in the repository, but no luck. As a last option, i tried to remove the item from the repository to be able to sync properly again (just like before creating the item), but the error still happens.
    Another weird point is that i have tried creating the item in another publication of another database (but with almost equal items), and the item could was downloaded to my local DB without any problem, which makes this problem still more bizarre.
    What can it be?
    Any help would be great!
    Roshni

    have you tried unistalling the client and reinstalling it?
    schema evolution changes are not always handled correctly please check thread:
    Modification of publication item into Mobile Server
    i quote from rekounas instructions:
    If you are just adding a field, you should only have to run the alter publication item API call.
    Here is an old note on schema evolution on different scenarios. The names for the APIs that they use are now deprecated. Use the ConsolidatorManager class and call the method alterPublicationItem("PUBLICATION_ITEM_NAME", "SELECT STMT") :
    A) Add column
    1. Upload all client data. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Change the Oracle8i/9i database schema (add column)
    4. Create a Java program to call the Consolidator Admin API AlterPublicationItem()
    5. Start Mobile Server
    6. Execute a sync from the client
    7. The new column should be seen on the client. Use MSQL to check snapshot definitions.
    B) Drop column
    1. Upload all client data. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Delete column of the base table in the Oracle database schema
    4. Create a Java program to call the Consolidator Admin API DropPublicationItem()
    5. Create a Java program to call the Consolidator Admin API CreatePublicationItem() and AddPublicationItem().
    6. Start Mobile Server
    7. Execute a sync from the client
    8. The new column should be seen on the cliet. Use MSQL to check snapshot definitions.
    C) Change column datatype
    Changing datatypes in a repliatated system is not an easy task. You have to follow certain procedures in order to make it to work. Use DropPublicationItem, CreatePublicationItem and AddPublicationItem methods from the Consolidator Admin API. You must stop/start Mobile Server listener to refresh the cache.
    1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Drop/create column (do not use conversion procudures) at the base table
    4. Call DropPublicationItem(). Check if the ErrorQueue and InQueue no longer exist.
    5. Call CreatePublicationItem() and AddPublicationItem(). Check if the ErrorQueue and InQueue reflect the new column datatype
    6. Start Mobile Server. This automatically resumes application
    7. Client executes sync. This should drop the old snapshot and recreate the new snapshot. Use MSQL to check
    snapshot definitions.
    D) Drop table
    1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Drop base table
    4. Call DropPublicationItem(). Check if the ErrorQueue and InQueue no longer exist.
    5. Start Mobile Server. This automatically resumes application
    6. Client executes sync. This should drop the old snapshot. Use MSQL to check snapshot definitions.
    E) Add table
    1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Add new base table
    4. Call CreatePublicationItem() and AddPublicationItem() method
    5. Start Mobile Server. This automatically resumes application
    6. Client executes sync. This should add the new snapshot. Use MSQL to check snapshot definitions.
    F) Changing Primary Keys
    Chaning PK is a severe operation which must be executed manually. A snapshot must be deleted and recreated to propagate the changes to the clients. This causes a full refresh on this snapshot.
    1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
    2. Stop Mobile Server listener
    3. Drop the snapshot using DropPublicationItem() method o
    4. Alter the base table
    5. Call CreatePublicationItem()and AddPublicationItem() methods for the altered table
    6. Start Mobile Server. This automatically resumes application
    7. Client executes sync. The old snapshot will be replaced by the new snapstot using a full refresh. Use MSQL to check snapshot definitions.
    G) To Change a Table Weight =>
    Follow the procedure below to change the Table Weight parameter. The table weight is used by the Mobile Server/Synchronization to determin the sequence in which client records are applied to the Oracle database.
    1. Run MGP to apply any changes in the InQueue to the Oracle databse
    2. Change table weight using SetTemplateItemMetadata() method
    3. Add/change constraint on the the base table which reflects the change in table weight
    4. Synchronize
    gl m8

  • Bad exec plan when joining tables using primary keys together w/ Contains

    Hello all...this is something that confuzzles me....
    When joining 2 tables, the exec plan shows that the domain index is first accessed, before checking if there is a record in the other table using a highly selective index.
    create table users
    (userid varchar2(20),
    name varchar2(100),
    resume clob
    create table seeker
    (seekerid varchar2(20),
    userid varchar2(20),
    jobid varchar2(20)
    create index user_idx on users(userid)
    create index job_resume_index on users(resume)
    indextype is ctxsys.context
    create unique index seeker_unik on seeker(seekerid)
    create index seeker_index on seeker(jobid,userid)
    then sample records where inserted, then the text index was sync'ed.
    Query and Execution Plan:
    select u.userid, u.name
    from users u, seeker s
    where s.jobid = 'HJOBP000000000218627'
    and u.userid = s.userid
    and contains(resume,'texas') > 1
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=3 Card=1 Bytes=72)
    1 0 NESTED LOOPS (Cost=3 Card=1 Bytes=72)
    2 1 TABLE ACCESS (BY INDEX ROWID) OF 'USERS' (Cost=2 Card=1
    Bytes=30)
    3 2 DOMAIN INDEX OF 'JOB_RESUME_INDEX' (Cost=0)
    4 1 INDEX (RANGE SCAN) OF 'SEEKER_INDEX' (NON-UNIQUE) (Cost=
    1 Card=1 Bytes=42)
    The problem with execution plan is if the domain index returns huge number of records i.e. 40k rows, then it has to check each userid with the SEEKER table, and returns only 10 rows. I can add a hint to specify the use of the user_idx instead of the domain index to improve performance.
    My question is how does the database determine when to use the domain index or to use other highly selective index with out the aid of a HINT. The trace file shows the use of "CTXSYS"."TEXTOPTSTATS".ODCIStatsIndexCost and "CTXSYS"."TEXTOPTSTATS".ODCIStatsFunctionCost. Are these used to compute and compare the cost of each index and decide on what index to used? If so, why does it return a lower cost for domain index when the btree index is more efficient? I have all statistics gathered for all tables and indexes (inc dr$ tables and its indexes)
    Thanks,
    jojo

    Hi,
    What I'm pasting here is actually from Ch9 of Expert PL/SQL. It shows what happens during a select with CONTAINS. It does not include a join with another table, or an additional column in the where clause. Hope it helps.
    ================================================
    By default, the Extensible Query Optimizer is enabled. When enabled, the Extensible Query Optimizer can determine the I/O and CPU cost associated with the CONTAINS predicate, find the cost of each call to the CONTAINS() function, and determine the selectivity of the CONTAINS predicate.
    To see this in action I ran the basic select earlier. Examining the SQL trace shows the steps.
    Step 1 - Determine the I/O and CPU cost of the CONTAINS() function:
    --Available online as part of contains_trace.doc
    "CTXSYS"."TEXTOPTSTATS".ODCIStatsFunctionCost(
    sys.ODCIFuncInfo('CTXSYS',
    'CTX_CONTAINS',
    'TEXTCONTAINS',
    2),
    cost,
    sys.ODCIARGDESCLIST(
    sys.ODCIARGDESC(
    2, 'DOCUMENT_REPOSITORY', 'PLSQL',
    '"DOCUMENT"', NULL, NULL, NULL),
    sys.ODCIARGDESC(3, NULL, NULL, NULL, NULL, NULL, NULL)),
    NULL,
    'constitution',
    sys.ODCIENV(0,0,0,1));
    Step 2 – Determine the selectivity of the CONTAINS predicate
    -- Available online as part of contains_trace.doc
    "CTXSYS"."TEXTOPTSTATS".ODCIStatsSelectivity(
    sys.ODCIPREDINFO('CTXSYS',
    'CTX_CONTAINS',
    'TEXTCONTAINS',
    32),
    sel,
    sys.ODCIARGDESCLIST(
    sys.ODCIARGDESC(3, NULL, NULL, NULL, NULL, NULL, NULL),
    sys.ODCIARGDESC(5, NULL, NULL, NULL, NULL, NULL, NULL),
    sys.ODCIARGDESC(2, 'DOCUMENT_REPOSITORY', 'PLSQL',
    "DOCUMENT"', NULL, NULL, NULL),
    sys.ODCIARGDESC(3, NULL, NULL, NULL, NULL, NULL, NULL)),
    0,
    NULL,
    NULL,
    'constitution',
    sys.ODCIENV(0,0,0,1));
    Step 3: Determine the I/O and CPU cost of the CONTAINS predicate
    -- Available online as part of contains_trace.doc
    "CTXSYS"."TEXTOPTSTATS".ODCIStatsIndexCost(
    sys.ODCIINDEXINFO('PLSQL',
    'EXPERT_IDX',
    sys.ODCICOLINFOLIST(
    sys.ODCICOLINFO('PLSQL', 'DOCUMENT_REPOSITORY',
    '"DOCUMENT"', 'BFILE', NULL, NULL)),
    NULL,
    0,
    0),
    50.00000000,
    cost,
    sys.ODCIQUERYINFO(
    2,
    sys.ODCIOBJECTLIST(sys.ODCIOBJECT('SCORE', 'CTXSYS'))),
    sys.ODCIPREDINFO('CTXSYS', 'CONTAINS', NULL, 0),
    sys.ODCIARGDESCLIST(
    sys.ODCIARGDESC(3, NULL, NULL, NULL, NULL, NULL, NULL),
    sys.ODCIARGDESC(5, NULL, NULL, NULL, NULL, NULL, NULL),
    sys.ODCIARGDESC(2, 'DOCUMENT_REPOSITORY', 'PLSQL',
    '"DOCUMENT"', NULL, NULL, NULL),
    sys.ODCIARGDESC(3, NULL, NULL, NULL, NULL, NULL, NULL)),
    1,
    NULL,
    'constitution',
    sys.ODCIENV(0,0,0,1));
    Note: The 50.00000000 in this last call is the selectivity retrieved from step 2.
    Only after these three steps complete does the query actually get executed:
    -- Available online as part of contains_trace.doc
    SELECT score(1), title
    FROM document_repository
    WHERE CONTAINS(document, 'constitution', 1) > 0
    ORDER BY 1 DESC;
    This is not the end of the processing though. To retrieve the records, the $I table (the index data table) is queried as follows:
    -- Available online as part of contains_trace.doc
    SELECT /*+ INDEX(i) */ TOKEN_FIRST,TOKEN_LAST,TOKEN_COUNT,ROWID
    FROM "PLSQL"."DR$EXPERT_IDX$I" i
    WHERE TOKEN_TEXT = 'CONSTITUTION'
    AND TOKEN_TYPE = 0
    ORDER BY TOKEN_TEXT, TOKEN_TYPE, TOKEN_FIRST;
    Note: The search term is UPPERCASE when querying against the DR$EXPERT_IDX$I table because all of the tokens are stored in uppercase by default. The original SELECT was in lowercase. This automatic conversion to uppercase allows the Text index to provide case-insensitive searching.
    This query returns the following result:
    TOKEN_FIRST TOKEN_LAST TOKEN_COUNT ROWID
    1 2 2 AAAN54AAEAAAOvEAAo
    Finally, the $R table (the rowid table) is queried.
    -- Available online as part of contains_trace.doc
    SELECT data
    FROM "PLSQL"."DR$EXPERT_IDX$R"
    WHERE row_no = 0;
    Only now do I see the results of my query:
    SCORE(1) TITLE
    55 United States Constitution
    8 Bill of Rights
    Keep in mind that modifications to the query, such as the addition of other columns in the where clause or the addition of operators, will result in a different trace.
    ===============================

  • Creating a row trigger to populate the primary key

    to populate the primary key of a table automatically, i created a sequence named rule_id
    using the following statement:
    create sequence rule_id;
    and then i created a trigger to populate the primary key using the statements below:
    CREATE OR REPLACE
    TRIGGER RULE_ID BEFORE INSERT ON DOC_CATS_RULE_BASED_CLASS
    FOR EACH ROW
    BEGIN
    SELECT SEQ_RULE_BASED_CLASS.NEXTVAL
    INTO :new.id FROM DUAL;
    END;
    i took this from a books example. but it gives and error called:
    Error(3,8): PLS-00049: bad bind variable 'NEW.ID'
    What is wrong and what is the current way to do it?
    Please help!

    Hi ,
    The new denotes the new data values for the table relative column.....
    As regards the dual is a small table in the data dictionary that Oracle and user-written programs can reference to guarantee a known result. This table has one column called DUMMY and one row containing the value X.
    Regards,
    Simon

  • Testing for unique records in a compound Primary Key table

    I have a table with 2 fields being primary keys. I want to write a sql script to check if there are duplicates.
    Here is what I have but not sure if this is working right. I have table with millions of records.
    SELECT COUNT(CASE WHEN A.AUNQ >1  THEN 1 ELSE NULL END)
    FROM
    SELECT (List_Cd + Account_Key) PK_ListAcc, COUNT(List_Cd) AUNQ
    FROM RAW_AML_LISTEDACCNTS_JUN GROUP BY List_Cd, Account_Key HAVING (COUNT(List_Cd) >1))
     A;
    Can someone help?
    thanks

    Yes, I agree. I am doing data profiling and testing all these tables. I am expecting that the results show me zero, however, if there were any problems with the settings, then I should get something. I think that the subquery is needed because if I used
    what you suggested above I will get the following:
    List_CD    Account_Key
    1                    a
    2                    b
    3                    c
    3                    C
    1                    a
    1                    a
    the results will be:
    List_CD    Account_Key    CountOFAccount_Key
    1                    a                       
    3
    3                    C                       
    2
    I now need to count that query results to get the total which should be 2
    do you agree? I am just trying to confirm that the sql script I listed will give me this result correctly.

  • How to use primary key in sql combined from 2 columns

    table1
    primary key = orderid+custname
    orderid custname address
    8889 Adrian london
    8867 Clara manchester
    2229 Peter warwick
    table2
    primary key = orderid+custname
    orderid custname qty price
    8889 Adrian 10 2500
    8865 Adrian 20 9483
    8867 Clara 30 3993
    5869 Clara 15 1828
    2290 Peter 10 2102
    2298 Peter 13 3839
    then how do i query ?
    SQL> select t1.orderid, t1.custname, t1.address, t2.qty, t2.price from
    table1 t1, table2 where ? = ?
    what's the "?" should be ????
    it doesn't work if i enter the primary constraint key for each table.
    thanks.

    thanks, it works ;)
    btw, do you know how about the date field ?
    what if one of the field in table1 is 12/12/2005 14:30
    and table2 is 15/12/2005
    table1
    orderid orderdate
    1234 12/12/2005 14:30
    2234 15/12/2005 13:45
    table2
    orderid orderdate
    1234 12/12/2005
    2234 15/12/2005
    so the query
    select t1.orderid as t1 t1.orderdate , t2.orderid as t2, t2.orderdate from
    table1 t1, table2 t2 where t1.orderid = t2.orderid
    and to_char(to_date(t1.orderdate, 'dd/mm/yyyy hh24:mi'), 'dd/mm/yyyy') = t2.orderdate
    thanks.

  • Access path difference between Primary Key and Unique Index

    Hi All,
    Is there any specific way the oracle optimizer treats Primary key and Unique index differently?
    Oracle Version
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for IBM/AIX RISC System/6000: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    SQL> Sample test data for Normal Index
    SQL> create table t_test_tab(col1 number, col2 number, col3 varchar2(12));
    Table created.
    SQL> create sequence seq_t_test_tab start with 1 increment by 1 ;
    Sequence created.
    SQL>  insert into t_test_tab select seq_t_test_tab.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL> exec dbms_stats.gather_table_stats(USER_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
            259  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> create index idx_t_test_tab on t_test_tab(col1);
    Index created.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> Sample test data when using Primary Key
    SQL> create table t_test_tab1(col1 number, col2 number, col3 varchar2(12));
    Table created.
    SQL> create sequence seq_t_test_tab1 start with 1 increment by 1 ;
    Sequence created.
    SQL> insert into t_test_tab1 select seq_t_test_tab1.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB1',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab1;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1727568366
    | Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |             | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB1 | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> alter table t_test_tab1 add constraint pk_t_test_tab1 primary key (col1);
    Table altered.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB1',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab1;
    99999 rows selected.
    Execution Plan
    Plan hash value: 2995826579
    | Id  | Operation            | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                | 99999 |   488K|    59   (2)| 00:00:01 |
    |   1 |  INDEX FAST FULL SCAN| PK_T_TEST_TAB1 | 99999 |   488K|    59   (2)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6867  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> If you see here the even though statistics were gathered,
         * In the 1st table T_TEST_TAB, the table is still using FULL table access after creation of index.
         * And in the 2nd table T_TEST_TAB1, table is using PRIMARY KEY as expected.
    Any comments ??
    Regards,
    BPat

    Thanks.
    Yes, ignored the NOT NULL part.Did a test and now it is working as expected
    SQL>  create table t_test_tab(col1 number not null, col2 number, col3 varchar2(12));
    Table created.
    SQL>
    create sequence seq_t_test_tab start with 1 increment by 1 ;SQL>
    Sequence created.
    SQL> insert into t_test_tab select seq_t_test_tab.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL>  exec dbms_stats.gather_table_stats('GREP_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL>  set autotrace traceonly
    SQL>  select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6912  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL>  create index idx_t_test_tab on t_test_tab(col1);
    Index created.
    SQL>  exec dbms_stats.gather_table_stats('GREP_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL>  select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 4115006285
    | Id  | Operation            | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                | 99999 |   488K|    63   (2)| 00:00:01 |
    |   1 |  INDEX FAST FULL SCAN| IDX_T_TEST_TAB | 99999 |   488K|    63   (2)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6881  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL>

  • "ORA-1715 : UNIQUE may not be used with a cluster index" but why?

    "ORA-1715 : UNIQUE may not be used with a cluster index" but why and what "may" means here? Any comments will be welcomed, thank you and best regards;
    show rel
    release 1002000300
    CREATE CLUSTER sc_srvr_id (
    srvr_id NUMBER(10)) SIZE 1024;
    SELECT cluster_name, tablespace_name, hashkeys,
    degree, single_table FROM user_clusters;
    CREATE UNIQUE INDEX idx_sc_srvr_id ON CLUSTER sc_srvr_id;
    ERROR at line 1:
    ORA-01715: UNIQUE may not be used with a cluster index
    CREATE INDEX idx_sc_srvr_id ON CLUSTER sc_srvr_id;
    SELECT index_name, index_type, tablespace_name
    FROM user_indexes where index_name like '%SRVR%' ;
    CREATE TABLE cservers (
    srvr_id    NUMBER(10),
    network_id NUMBER(10),
    status     VARCHAR2(1),
    latitude   FLOAT(20),
    longitude  FLOAT(20),
    netaddress VARCHAR2(15))
    CLUSTER sc_srvr_id (srvr_id);
    ALTER TABLE cservers add constraint pk_srvr_id primary key (srvr_id ) ;
    SELECT index_name, index_type, tablespace_name
    FROM user_indexes where index_name like '%SRVR%' ;
    INDEX_NAME                     INDEX_TYPE
    TABLESPACE_NAME
    IDX_SC_SRVR_ID                 CLUSTER
    USERS
    PK_SRVR_ID                     NORMAL
    USERSdo we really need another pkey index here?

    "May" has different meanings, one of which is:
    (used to express opportunity or permission)
    Metalink note 19067.1 says:
    This is not permitted.
    ... which agrees with the above meaning of it.
    Besides these, it does not make any sense to me to create a unique index on a cluster. You can have primary keys in the tables you include in the cluster, it depends on your business requirement. But why do you need a unique index on a cluster?

  • Can an unique index be created on read only cache group

    Hi
    Can an unique index be created on read only cache group
    Regards
    Siva Kumar

    No, I do not think so. Creating a unique index could cause autorefresh operations to fail if the data being refreshed contains duplicate values that would not be allowed by the index. You can create regular indexes on a table in a readonly cache group.
    Chris

  • Create unique index from duplicate rows

    Dear
    I created an index like
    create index tablename_idx on tablename (FIELD1,FIELD2);
    It should be
    create unique index tablename_idx on tablename (FIELD1,FIELD2,filed3);
    How can I delete those duplicate records and create the UNIQUE index ?
    Thanks and regards
    Fahmed

    > How can I delete those duplicate records
    [url http://forums.oracle.com/forums/search.jspa?threadID=&q=delete+duplicate+records&objID=f75&dateRange=all&userID=&numResults=15]http://forums.oracle.com/forums/search.jspa?threadID=&q=delete+duplicate+records&objID=f75&dateRange=all&userID=&numResults=15
    Regards,
    Rob.

  • Difference between Unique key and Unique index

    Hi All,
    I've got confused in the difference between unique index & unique key in a table.
    While we create a unique index on a table, its created as a unique index.
    On the other hand, if we create a unique key/constraint on the table, Oracle also creates an index entry for that. So I can find the same name object in all_constraints as well as in all_indexes.
    My question here is that if during creation of unique key/constraint, an index is automatically created than why is the need to create unique key and then two objects , while we can create only one object i.e. unique index.
    Thanks
    Deepak

    This is only my understanding and is not according to any documentation, that is as follows.
    The unique key (constraint) needs an unique index for achieving constraint of itself.
    Developers and users can make any constraint (unique-key, primary-key, foreign-key, not-null ...) to enable,disable and be deferable. Unique key is able to be enabled, disabled, deferable.
    On the other hand, the index is used for performance-up originally, unique index itself doesn't have the concept like constraints. The index (including non-unique, unique) can be rebuilded,enabled,disabled etc. But I think that index cannot be set "deferable-builded" automatic.

  • How to create a primary key by 2 columns in sql??

    as title
    thx a lot.

    Chris,
    Well you have two basic ways. One is to issue an alter table command and define a PRIMARY KEY (also called a PK). The other is to create a UNIQUE index. The PRIMARY KEY creates an index anyway, though I prefer to just use unique indexes as you can specify more options in this manner. A table can only have 1 PK where as you can have multiple UNIQUE indexes. I also do not combine the PK definition directly into the CREATE TABLE command, as normally one would keep a seperate PK script, even if they did contain only unique indexes commands and not PK alter table commands.
    Anyway, below are the two methods of making a PK/Unique object for your table. The table name used here is T1 ...
    Method #1 (Primary Key)
    ALTER TABLE T1 DROP PRIMARY KEY;
    ALTER TABLE T1 ADD PRIMARY KEY
    (Column_1,Column_2, ...)
    STORAGE
         NEXT 512K
         MINEXTENTS 1
         MAXEXTENTS UNLIMITED
         PCTINCREASE 0
    Method #2 (preferred) : Unique Index
    DROP INDEX PK_T1;
    CREATE UNIQUE INDEX PK_T1 ON T1
    (Column_1,Column_2, ...)
    TABLESPACE INDX
    PCTFREE 10
    STORAGE
         INITIAL 1M
         NEXT 512K
         MINEXTENTS 1
         MAXEXTENTS UNLIMITED
         PCTINCREASE 0
    It's always best to define the storage clause for both the create table and it's indexes.
    Hope this helps ya,
    Tyler

Maybe you are looking for

  • "On my Mac" Calendars, Help me delete!

    I am using leopard 10.5.7, iphone OS 3.0, and the latest itunes (that blocks the pre update.) i recently subscribed to some calendars from my iphone, and wanted to get rid of the same calendars from my mac that were synced to my phone. i have mobile

  • SQL query with PHP variable help

    Hi, Using Dreamweaver Developer Toolbox, I added a Horizontal recordset to get two columns across for the city. Next to this is a number value of how many records are in the particular city. But I have gone wrong somewhere, as I get the same value fo

  • Configuring with D-Link or Netgear Modem

    Hi, I'm facing unsolvable problem with installing a brand new Aiport Extreme router with my already working D-Link modem. The modem works fine when using it directly, and works fine with an old D-Link router. I gave up on the D-Link modem and bought

  • It is possible to turn your old ipad to the app's to your new iPad 2

    is it possible to get your app from ipad to ipad2

  • Pull Down Manu

    Hi Is it possible to create a pull down manu after clicking the sub-tab or tab in Apex? Thanks, Ethan