Unique Index vs. Unique Constraint

Hi All,
I'm studying for the Oracle SQL Expert Certification. At one point in the book, while talking about indices, the author says that a unique index is not the same a unique constraint. However, he doesn't explain why they're two different things.
Could anyone clarify the difference between the two, please?
Thanks a lot,
Valerio

A constraint has different meaning to an index. It gives the optimiser more information and allows you to have foreign keys on the column, whereas a unique index doesn't.
eg:
SQL> create table t1 (col1 number, col2 varchar2(20), constraint t1_uq unique (col1));
Table created.
SQL> create table t2 (col1 number, col2 varchar2(20));
Table created.
SQL> create unique index t2_idx on t2 (col1);
Index created.
SQL> create table t3 (col1 number, col2 number, col3 varchar2(20), constraint t3_fk
  2                   foreign key (col2) references t1 (col1));
Table created.
SQL> create table t4 (col1 number, col2 number, col3 varchar2(20), constraint t4_fk
  2                   foreign key (col2) references t2 (col1));
                 foreign key (col2) references t2 (col1))
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-listIt's like saying "What's the difference between a car seat and an armchair? They both allow you to sit down!"

Similar Messages

  • Difference Between Unique Index vs Unique Constraint

    Can you tell me
    what is the Difference Between Unique Index vs Unique Constraint.
    and
    Difference Between Unique Index and bitmap index.
    Edited by: Nilesh Hole,Pune, India on Aug 22, 2009 10:33 AM

    Nilesh Hole,Pune, India wrote:
    Can you tell me
    what is the Difference Between Unique Index vs Unique Constraint.http://www.jlcomp.demon.co.uk/faq/uk_idx_con.html
    and
    Difference Between Unique Index and bitmap index.The documentation is your friend:
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/schema.htm#CNCPT1157
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/schema.htm#sthref1008
    Regards,
    Rob.

  • Difference between unique constraint and unique index

    1. What is the difference between unique constraint and unique index when unique constraint is always indexed ? Which one is better in this case for better performance ?
    2. Is Composite index of 3 columns x,y,z better
    or having independent/ seperate indexes on 3 columns x,y,z is better for better performance ?
    3. It has been very confusing for me to decide which columns to index, I have indexed most foreignkey columns, is it a good idea ? We do lot of selects and DMLS on most of our tables. Is there any query that I can run and find out if indexes are really being used and if they are improving any performance. I have analyzed and computed my indexes using ANALYZE index index_name validate structure and COMPUTE STATISTICS;
    null

    1. Unique index is part of unique constraint. Of course you can create standalone unique index. But is is no point to skip the logical view of business if you spend same effort to achive.
    You create unique const. Oracle create the unique index for you. You may specify index characteristic in unique constraint.
    2. Depends. You can't utilize the composite index if the searching condition is not whole or front part of the indexing key. You can't utilize your index if you query the table for y=2. That is.
    3. As old words in database arena, Index may be good or bad for a table depending on the size of table, number of columns in the table... etc. It is very environmental dependent. In fact, It is part of database nomalization. Statistic is a way oracle use to determine the execution plan.
    Steve
    null

  • 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.

  • UNIQUE INDEX and PRIMARY KEYS

    Hi Friends,
    I am confused about primary keys.
    What is the purpose of this key again? I know it is used for unique constraints.
    Supposing I have a table with two (2) columns which are each indexed as unique.
    Then they can me both candidate at primary key right?
    So why do I need a primary key again? when I have 2 columns which are uniquely index?
    Thanks a lot

    A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL
    The differences between the two are:
    1. Column(s) that make the Primary Key of a table cannot be NULL since by definition; the Primary Key cannot be NULL since it helps uniquely identify the record in the table. The column(s) that make up the unique index can be nullable. A note worth mentioning over here is that different RDBMS treat this differently –> while SQL Server and DB2 do not allow more than one NULL value in a unique index column, Oracle allows multiple NULL values. That is one of the things to look out for when designing/developing/porting applications across RDBMS.
    2. There can be only one Primary Key defined on the table where as you can have many unique indexes defined on the table (if needed).
    3. Also, in the case of SQL Server, if you go with the default options then a Primary Key is created as a clustered index while the unique index (constraint) is created as a non-clustered index. This is just the default behavior though and can be changed at creation time, if needed.
    So, if the unique index is defined on not null column(s), then it is essentially the same as the Primary Key and can be treated as an alternate key meaning it can also serve the purpose of identifying a record uniquely in the table.

  • Using UNUSABLE on Unique Index gives "initially in unusable state" error

    I am doing the following:
    1. Truncate table
    2 Alter PK Index Disable
    2. Alter Unique Index Unusable
    3. Insert /*+ APPEND NOLOGGING*/ into my table
    My problem is, I get an "ORA-26026: unique index ... initially in unusable state" error when I try to do the Insert. If I make the Unique index non-unique it isn't a problem. If I drop the index and recreate it its not a problem - so uniqueness doesn't appear to be the issue. Can you not use UNUSABLE with a Unique index, I couldn't find any reference to this in the 10g docs.
    I am using 10.1.0.4.
    Thanks
    Richard

    26026, 0000, "unique index %s.%s initially in unusable state"
    //* Cause: A unique index is in IU state (a unique index cannot have
    //* index maintenance skipped via SKIP_UNUSABLE_INDEXES).
    //* Action: Either rebuild the index or index partition, or use
    //* SKIP_INDEX_MAINTENANCE if the client is SQL*Loader.

  • Getting constraint errorr for INSERT? Cannot insert duplicate key row in object 'etag.Tag_Processed' with unique index 'IX_Tag_Processed'

    I have an index constraint "IX_Tag_Processed" on the field "Tag_Name" for the table "Tag_Processed". I keep getting this constraint error:
    Msg 2601, Level 14, State 1, Line 15
    Cannot insert duplicate key row in object 'etag.Tag_Processed' with unique index 'IX_Tag_Processed'. The duplicate key value is (AZPS_TEMUWS0110BL4_CISO).
    The statement has been terminated.
    For this INSERT: I have tried using tagstg.Tag_Name NOT IN with same result:
    INSERT into [Forecast_Data_Repository].[etag].[Tag_Processed] (Tag_Name, Tag_Type,Start_Datetime, End_Datetime, Source_SC, Sink_SC, Source_CA, Sink_CA, Source, Sink, Load_dt, Energy_product_code_id)
    SELECT DISTINCT (Tag_Name), Tag_Type,Start_Datetime, End_Datetime, Source_SC, Sink_SC, Source_CA, Sink_CA, Source, Sink, GETUTCDATE(),  [Forecast_Data_Repository].rscalc.GetStubbedEngProductCodeFromStaging(tagstg.Tag_Name)
    FROM [Forecast_Data_Repository].[etag].[Tag_Stg] tagstg
    WHERE tagstg.Id BETWEEN @minTId AND @maxTId --AND
    --tagstg.Tag_Name NOT IN (
    -- SELECT DISTINCT tproc.Tag_Name from [Forecast_Data_Repository].[etag].[Tag_Processed] tproc
    thank you  in advance, 
    Greg Hanson

    I have even tried a merge with the same constraint error,
    DECLARE @minTId bigint, @minTRId bigint, @minEId bigint
    DECLARE @maxTId bigint, @maxTRId bigint, @maxEId bigint
    DECLARE @errorCode int
    DECLARE @ReturnCodeTypeIdName nvarchar(50)
    SELECT @minTRId = Min(Id) FROM [etag].[Transmission_Stg]
    SELECT @maxTRId = Max(Id) FROM [etag].[Transmission_Stg]
    SELECT @minTId = Min(Id) FROM [etag].[Tag_Stg]
    SELECT @maxTId = Max(Id) FROM [etag].[Tag_Stg]
    DECLARE @MergeOutputTag TABLE
    ActionType NVARCHAR(10),
    InsertTagName NVARCHAR(50)
    --UpdateTagName NVARCHAR(50)
    --DeleteTagName NVARCHAR(50)
    DECLARE @MergeOutputEnergy TABLE
    ActionType NVARCHAR(10),
    InsertTagId BIGINT
    --UpdateTagName NVARCHAR(50)
    --DeleteTagName NVARCHAR(50)
    DECLARE @MergeOutputTransmission TABLE
    ActionType NVARCHAR(10),
    InsertTagId BIGINT
    --UpdateTagName NVARCHAR(50)
    --DeleteTagName NVARCHAR(50)
    MERGE [Forecast_Data_Repository].[etag].[Tag_Processed] tagProc
    USING [Forecast_Data_Repository].[etag].[Tag_Stg] tagStg
    ON 
    tagProc.Tag_Name = tagStg.Tag_Name AND
    tagProc.Tag_Type = tagStg.Tag_Type AND
    tagProc.Start_Datetime = tagStg.Start_Datetime AND
    tagProc.End_Datetime = tagStg.End_Datetime AND
    tagProc.Source_SC = tagStg.Source_SC AND
    tagProc.Source_CA = tagStg.Source_CA AND
    tagProc.Sink_CA = tagStg.Sink_CA AND
    tagProc.Source = tagStg.Source AND
    tagProc.Sink = tagStg.Sink 
    WHEN MATCHED THEN
    UPDATE
    SET Tag_Name = tagStg.Tag_Name,
    Tag_Type = tagStg.Tag_Type,
    Start_DateTime = tagStg.Start_Datetime,
    End_Datetime = tagStg.End_Datetime,
    Source_SC = tagStg.Source_SC,
    Sink_SC = tagStg.Sink_SC,
    Source_CA = tagStg.Source_CA,
    Sink_CA = tagStg.Sink_CA,
    Source = tagStg.Source,
    Sink = tagStg.Sink,
    Load_dt = GETUTCDATE()
    WHEN NOT MATCHED BY TARGET THEN
    INSERT (Tag_Name, Tag_Type, Start_Datetime, End_Datetime, Source_SC, Sink_SC, Source_CA, Sink_CA, Source, Sink, Load_dt)
    VALUES (tagStg.Tag_Name, tagStg.Tag_Type, tagStg.Start_Datetime, tagStg.End_Datetime, tagStg.Source_SC, tagStg.Sink_SC, tagStg.Source_CA, tagStg.Sink_CA, tagStg.Source, tagStg.Sink, GETUTCDATE())
    OUTPUT
    $action,
    INSERTED.Tag_Name
    --UPDATED.Tag_Name
    INTO @MergeOutputTag;
    SELECT * FROM @MergeOutputTag;
    Greg Hanson

  • 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>

  • How to create index not unique at the time of the CREATE TABLE

    Hi,
    I am trying to find out how in Oracle create secondary indexes that can accept duplicated into the CREATE TABLE statement, without have to execute a CREATE INDEX separately.
    As far I can see the only syntax accepted by Oracle 9i to create more than one index at the time of the table creation is:
    CREATE TABLE test_tab (x INTEGER, y INTEGER, z INTEGER PRIMARY KEY(x,y), UNIQUE(z))
    But, in my case I need to have the unicity only for the primary key, but not for the second index, that I would like to have not unique.
    How to do that inside of the CREATE TABLE statement?
    Any help?
    Thanks a lot in advance.

    To create an index automatically (not constraint related) , you will need to have an 'event' trigger on the schema that will (IE: detecting a table create/drop matching ARCHIVE_%) , generate the appropriate SQL required (create index sql) and pass THAT to a DBMS_JOB.
    Make sure you have job queue's enabled.
    This was the ONLY way that I could re-create a view automatically as new tables were created that matched a criteria IE ARCHIVE_JAN06, ARCHIVE_FEB06 etc.
    The application's "archiving" method created and was thus aware of these tables and permitted searching within 'archived' data, but 3rd party reporting applications needed to see a view encompassing all data, regardless of the tables involved. The view automatically created was a 'union_all' of all tables concerned.

  • 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

  • Unique Index Created Automatically on FK Columns

    Referencing the following document under Forward Engineering, http://www.oracle.com/technetwork/developer-tools/datamodeler/newfeatures30-224506.html
    Unique index is created for One-to-one relationships defined in the Logical model if there is no PK/UK constraint or unique index defined over foreign key columns.
    Why are unique indexes created automatically for foreign key columns? Should "lookups" not be defined in the logical model? I don't understand why it's designed to behave that way.

    Why are unique indexes created automatically for foreign key columns? They are created automatically only for 1:1 relationships in order to support that business rule.
    Should "lookups" not be defined in the logical model? Can you elaborate on that?
    Philip

  • The record has duplicate key values - "Include in Unique Index" checkbox missing

    I have a Silverlight client app that I'm developing in Lightswitch in VS2013 Ultimate Update 1, and have run into a problem when adding records.
    I am working against an external SQL Server 2008 database, and the table in question only has the primary key constraint, meaning that the ID field is an identity field, set as the primary key.
    When I try and add records to the table from the app, I get an error "The Shiur record has duplicate key values." This seems to happen when I add a row that has the same Speaker as an existing one. If I add one with a new Speaker then
    it inserts OK.
    Whilst searching for information on this error, I saw many comments around about there being a problem in earlier releases with the "Include in Unique Index" not working properly. This looked like my problem, except for two points...
    1) This table doesn't have anything in a unique index (as far as I know), as I never set it up to have any. You can see the details here...
    This looks to me like there is only the one index, which is the primary key one.
    2) The "Include in Unique Index" checkbox doesn't appear on my Properties panel at all. If I open the table in the designer, then click in the Speaker row, I don't see "Include in Unique Index" at all...
    Actually, I don't see "Include in Unique Index" at all, irrespective of what I click. It's just not there.
    So, I don't seem to have a unqiue constraint to violate, and VS doesn't show me the "Include in Unique Index" to allow me to check this, but I still get the error on insert. Anyone any ideas what's going on here?
    Thanks
    FREE custom controls for Lightswitch! A collection of useful controls for Lightswitch developers.
    Download from the Visual Studio Gallery.
    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at
    http://dotnetwhatnot.pixata.co.uk/

    Hi Alan,
    'Include in Unique Index' is for intrinsic database entity properties.
    Ah, that explains why I can't see it then :)
    Is LightSwitch or SQL throwing the error?
    Ah, you're a genius! Well, not quite, but your question led me to the answer.
    For some odd reason, the primary key fields on my tables seem to have lost their identity setting, so when it tried to insert a new record, the ID wasn't automatically increased, so was going in as zero. This worked fine for the first insert, as there wasn't
    a record with zero ID, but failed for the second.
    Changed the ID fields to be identity, and all works fine now :)
    Thanks very much.
    FREE custom controls for Lightswitch! A collection of useful controls for Lightswitch developers.
    Download from the Visual Studio Gallery.
    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at
    http://dotnetwhatnot.pixata.co.uk/

  • ORA-1779?? (I have unique index defined)

    I execute the query:
    UPDATE
    (select rec.cod_instalacion_marca cod_instal_marca_RECLAMAC, ins.cod_instalacion_marca cod_instal_marca_DIM_INST_MAR
    from ods.RECLAMAC rec
    INNER JOIN master_dwh.DIM_MODELOS mod ON (rec.cod_modelo = mod.cod_modelo)
    INNER JOIN master_dwh.DIM_INSTAL_MARCAS ins ON (rec.taller_implicado = ins.cod_instalacion and mod.cod_marca = ins.cod_marca))
    SET cod_instal_marca_RECLAMAC = cod_instal_marca_DIM_INST_MAR
    And I received the error:
    ORA-01779: cannot modify a column that maps to a non-key preserved column
    But I have:
    *) Primary key in the field: ins.cod_instalacion_marca (table: master_dwh.DIM_INSTAL_MARCAS)
    *) Unique Key in the fields: ins.cod_instalacion + ins.cod_marca (table: master_dwh.DIM_INSTAL_MARCAS).
    How can I solve it???
    Thanks very much!

    I’m sorry,
    But the table RECLAMAC is the table I want to modify!!! I can’t define unique key in this field (rec.cod_instalacion_marca ) because is the field that I want to modify and the values could repeat and that is correct.
    I read for example the AskTom Followup:
    You NEED a primary key/unique constraint on object_id in T1 to ensure that each row in T joins to AT MOST 1 row in T1.
    Consider, if T had:
    OBJECT_NAME OBJECT_ID
    ABC xxxx
    and T1 had:
    OBJECT_NAME OBJECT_ID
    ABC 123
    ABC 456
    what should be the outcome of:
    ADHOC@VOYAGER> update
    2 (select t.object_id toid,t1.object_id t1oid
    3 from t,t1
    4 where t.object_name=t1.object_name
    5 and upper(t.object_name)='PRIMARY_SALESFORCE')
    6 set toid=t1oid;
    should T have 123 or 456 and under what circumstances? Since the outcome of
    that update is 100% AMBIGOUS, we do not permit it. We need to ensure key
    preserved-ness and do that with a primary key/unique constraint.
    You need that index anyway typically for performance.
    But my T1 table in the AskTom example is DIM_INSTAL_MARCAS and I have defined the unique key: ins.cod_instalacion + ins.cod_marca
    Look at this:
    If I create the field cod_marca in the table RECLAMAC and execute this query, it is executed OK!!!!!!
    UPDATE
    (select rec.cod_instalacion_marca cod_instal_marca_RECLAMAC, ins.cod_instalacion_marca cod_instal_marca_DIM_INST_MAR
    from ods_clientes.EXP_RECLAMACIONES_EXPEDIENTES rec
    INNER JOIN maestros_dwh.DIM_INSTALACIONES_MARCAS ins ON (rec.taller_implicado = ins.cod_instalacion and rec.cod_marca = ins.cod_marca))
    SET cod_instal_marca_RECLAMAC = cod_instal_marca_DIM_INST_MAR
    But if I execute:
    UPDATE
    (select rec.cod_instalacion_marca cod_instal_marca_RECLAMAC, ins.cod_instalacion_marca cod_instal_marca_DIM_INST_MAR
    from ods.RECLAMAC rec
    INNER JOIN master_dwh.DIM_MODELOS mod ON (rec.cod_modelo = mod.cod_modelo)
    INNER JOIN master_dwh.DIM_INSTAL_MARCAS ins ON (rec.taller_implicado = ins.cod_instalacion and mod.cod_marca = ins.cod_marca))
    SET cod_instal_marca_RECLAMAC = cod_instal_marca_DIM_INST_MAR
    I receive the error ORA-01779: cannot modify a column that maps to a non-key preserved column
    I NEED IT...
    What unique index I have to create?
    Thanks very much!

  • ORA-01502 error in case of unusable unique index and bulk dml

    Hi, all.
    The db is 11.2.0.3 on a linux machine.
    I made a unique index unusable, and issued a dml on the table.
    Howerver, oracle gave me ORA-01502 error.
    In order to avoid ORA-01502 error, do I have to drop the unique index ,and do bulk dml, and recreate the index?
    Or Is there any other solution without re-creating the unique index?
    create table hoho.abcde as
    select level col1 from dual connect by level <=1000
    10:09:55 HOHO@PD1MGD>create unique index hoho.abcde_dx1 on hoho.abcde (col1);
    Index created.
    10:10:23 HOHO@PD1MGD>alter index hoho.abcde_dx1 unusable;
    Index altered.
    Elapsed: 00:00:00.03
    10:11:27 HOHO@PD1MGD>delete from hoho.abcde where rownum < 11;
    delete from hoho.abcde where rownum < 11
    ERROR at line 1:
    ORA-01502: index 'HOHO.ABCDE_DX1' or partition of such index is in unusable stateThanks in advance.
    Best Regards.

    Hi. all.
    The following is from "http://docs.oracle.com/cd/E14072_01/server.112/e10595/indexes002.htm#CIHJIDJG".
    Is there anyone who can show me a tip to avoid the following without dropping and re-creating an unique index?
    •DML statements terminate with an error if there are any unusable indexes that are used to enforce the UNIQUE constraint.
    Unusable indexes
    An unusable index is ignored by the optimizer and is not maintained by DML. One reason to make an index unusable is if you want to improve the performance of bulk loads. (Bulk loads go more quickly if the database does not need to maintain indexes when inserting rows.) Instead of dropping the index and later recreating it, which requires you to recall the exact parameters of the CREATE INDEX statement, you can make the index unusable, and then just rebuild it. You can create an index in the unusable state, or you can mark an existing index or index partition unusable. The database may mark an index unusable under certain circumstances, such as when there is a failure while building the index. When one partition of a partitioned index is marked unusable, the other partitions of the index remain valid.
    An unusable index or index partition must be rebuilt, or dropped and re-created, before it can be used. Truncating a table makes an unusable index valid.
    Beginning with Oracle Database 11g Release 2, when you make an existing index unusable, its index segment is dropped.
    The functionality of unusable indexes depends on the setting of the SKIP_UNUSABLE_INDEXES initialization parameter.
    When SKIP_UNUSABLE_INDEXES is TRUE (the default), then:
    •DML statements against the table proceed, but unusable indexes are not maintained.
    •DML statements terminate with an error if there are any unusable indexes that are used to enforce the UNIQUE constraint.
    •For non-partitioned indexes, the optimizer does not consider any unusable indexes when creating an access plan for SELECT statements. The only exception is when an index is explicitly specified with the INDEX() hint.
    •For a partitioned index where one or more of the partitions are unusable, the optimizer does not consider the index if it cannot determine at query compilation time if any of the index partitions can be pruned. This is true for both partitioned and non-partitioned tables. The only exception is when an index is explicitly specified with the INDEX() hint.
    When SKIP_UNUSABLE_INDEXES is FALSE, then:
    •If any unusable indexes or index partitions are present, any DML statements that would cause those indexes or index partitions to be updated are terminated with an error.
    •For SELECT statements, if an unusable index or unusable index partition is present but the optimizer does not choose to use it for the access plan, the statement proceeds. However, if the optimizer does choose to use the unusable index or unusable index partition, the statement terminates with an error.Thanks in advance.
    Best Regards.

  • Primary Key supported by a non-unique index?

    Encountered a weird situation today. A utility we setup which allows Analysts to restore data into their tables, started failing when it attempted to drop an index. The index was supporting a Primary Key. Makes sense. But our script was supposed to only be attempting to drop/recreate non-unique indexes. Turns out the supporting index on the Primary Key was non-unique, and to the best of my knowledge came about as follows:
    SQL> create table junk (f number(1));
    Table created.
    SQL> create index junk_ix on junk(f);
    Index created.
    SQL> select UNIQUENESS from DBA_INDEXES where index_name = 'JUNK_IX';
    UNIQUENES
    NONUNIQUE
    SQL> alter table forbesc.junk add constraint junk_pk primary key (f) using index junk_ix;
    Table altered.
    SQL> select UNIQUENESS from DBA_INDEXES where index_name = 'JUNK_IX';
    UNIQUENES
    NONUNIQUE
    SQL> insert into junk values (1);
    1 row created.
    SQL> insert into junk values (1);
    insert into junk values (1)
    ERROR at line 1:
    ORA-00001: unique constraint (FORBESC.JUNK_PK) violated
    SQL> select index_name from dba_constraints where constraint_name = 'JUNK_PK';
    INDEX_NAME
    JUNK_IXWhat I can't figure out is how a non-unique index is enforcing uniqueness. I thought that it was the key in that very same process. I thought that perhaps an index with the 'SYS_123456' was getting created, perhaps, but I couldn't find one:
    SQL> select object_name, object_type from dba_objects order by created desc;
    OBJECT_NAME   OBJECT_TYPE
    JUNK_IX     INDEX
    JUNK     TABLE
    ...How is the uniqueness getting enforced in this case? This is in Oracle 11.1.0.7
    Thanks,
    --=Chuck

    It has always been that way. Oracle can, and will, use a non-unique index to enforce a PK constraint, The existing index just needs to have the PK column(s) as the leading column(s) of the index:
    SQL> create table t (id number, id1 number, descr varchar2(10));
    Table created.
    SQL> create index t_ids on t(id, id1);
    Index created.
    SQL> select index_name from user_indexes
      2  where table_name = 'T';
    INDEX_NAME
    T_IDS
    SQL> alter table t add constraint t_pk
      2  primary key (id);
    Table altered.
    SQL> select index_name from user_indexes
      2  where table_name = 'T';
    INDEX_NAME
    T_IDS
    SQL> insert into t values (1, 1, 'One');
    1 row created.
    SQL> insert into t values (1, 2, 'Two');
    insert into t values (1, 2, 'Two')
    ERROR at line 1:
    ORA-00001: unique constraint (OPS$ORACLE.T_PK) violatedJohn

Maybe you are looking for