Function Based Indexes in Primary Key Definition

Hello.
I have been looking into function based indexes. I have been able to create them using unique indexes. However, when I try to create them on primary keys, the engine complains.
Any ideas? Does anyone know if you can create function based indexes on primary keys?
An example would be great!
Thanks,
Brad

Hi,
You can create a function-based Index by going to the Properties dialog for the Index in the Relational model (not the Physical model). If you select the Index Expression tick box, you can then enter the expression into the Expression text area.
David

Similar Messages

  • Function Based Index - Query Performance

    HI,
    Good Day to All..
    I'd like to use function based indexes on following column(to_char(ps.user_pc_id)).
    Whereas this column is part of PRIMARY KEY.
    Is it possible to create a function based index on PRIMARY KEY Column?
    Attached below is the query with the explain plan ...
    TO_CHAR Expression - Performance
    Thanks for your reply.

    DTYLER_APP@pssdev2> create table dt_fbi_pk(id varchar2(20));
    Table created.
    DTYLER_APP@pssdev2> drop table dt_fbi_pk;
    Table dropped.
    DTYLER_APP@pssdev2> create table dt_fbi(id number);
    Table created.
    DTYLER_APP@pssdev2> create index dt_fbi_idx on dt_fbi(to_char(id));
    Index created.
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_pk primary key (id);
    Table altered.
    DTYLER_APP@pssdev2> select constraint_name,constraint_type, index_name from user_constraints where table_name='DT_FBI';
    CONSTRAINT_NAME                C INDEX_NAME
    DT_FBI_PK                      P DT_FBI_PK
    1 row selected.When we created the primary key constraint, Oracle created a new index rather than using the existing one because....
    DTYLER_APP@pssdev2> alter table dt_fbi drop primary key;
    Table altered.
    DTYLER_APP@pssdev2> select index_name from user_indexes where table_name ='DT_FBI';
    INDEX_NAME
    DT_FBI_IDX
    1 row selected.
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_pk primary key (id) using index dt_fbi_idx;
    alter table dt_fbi add constraint dt_fbi_pk primary key (id) using index dt_fbi_idx
    ERROR at line 1:
    ORA-14196: Specified index cannot be used to enforce the constraint.
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_uk unique(id) using index dt_fbi_idx;
    alter table dt_fbi add constraint dt_fbi_uk unique(id) using index dt_fbi_idx
    ERROR at line 1:
    ORA-14196: Specified index cannot be used to enforce the constraint.We can't use a function based index to enforce a unique or primary key constraint. Changing the syntax does not help..
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_uk unique(TO_CHAR(id)) using index dt_fbi_idx;
    alter table dt_fbi add constraint dt_fbi_uk unique(TO_CHAR(id)) using index dt_fbi_idx
    ERROR at line 1:
    ORA-00904: : invalid identifierWe can create a unique index however
    DTYLER_APP@pssdev2> drop index dt_fbi_idx;
    Index dropped.
    DTYLER_APP@pssdev2> create unique index dt_fbi_idx on dt_fbi(to_char(id));
    Index created.but we still can't use it to enforce a unique or primary key constraint
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_pk primary key (id) using index dt_fbi_idx;
    alter table dt_fbi add constraint dt_fbi_pk primary key (id) using index dt_fbi_idx
    ERROR at line 1:
    ORA-14196: Specified index cannot be used to enforce the constraint.
    DTYLER_APP@pssdev2> alter table dt_fbi add constraint dt_fbi_uk unique(id) using index dt_fbi_idx;
    alter table dt_fbi add constraint dt_fbi_uk unique(id) using index dt_fbi_idx
    ERROR at line 1:
    ORA-14196: Specified index cannot be used to enforce the constraint.So no, you can't use it for a primary key. If you just want to enforce uniqueness then yes, you can do it with a unique index, but not a constraint.
    DTYLER_APP@pssdev2> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    5 rows selected.HTH
    Daviid

  • Function-based index, NOT NULL bug?

    ALTER SESSION SET OPTIMIZER_MODE = FIRST_ROWS_10;
    ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE;
    CREATE TABLE xxx (code CHAR(6) NOT NULL);
    create index xxx_idx on xxx (upper(code));
    select * from xxx order by upper(code);
    -> ORA-03113: end-of-file on communication channel
    (Oracle 9.0.1, Windows 2000)

    I know it's quite a long-time that anyone replied this post, but I just need to report our attempts to workaround that.
    Dropping function-based indexes in primary database, just before creation of Logical Dataguard hasn't solved our problem, neither dropping indexes in logical database.
    In my opinion and after some docs in metalink, I think there's no way to solve it.
    Or you drop them or you migrate to 10g.
    Regards.

  • Storage for Foreign Keys and Function based indexes

    This may well be the silliest question of the day, but is it possible to specify the storage for a Foreign key or a function based index? I'm not even sure that it would make sense.

    Well, a foreign key constraint is not a segment, nor is any other type of constraint. However, a function-based index is a segment, just like any other index. So, in that case, specify a tablespace, just like you would with any other index.
    Something like this:
    create index my_fbi on my_tab(upper(last_name)) tablespace my_index_tablespace;
    -Mark
    Message was edited by:
    mbobak
    Fixed minor typo.

  • Function based indexes on CLOB storage

    On a 10gR2 database, with schema-less CLOB storage for an XMLType column:
    (1) Can a function based index include a wildcard in the namespace ? Or do I need a new function based index for each specific namespace ?
    (2) I must create a new function based index for each different element that I want an indexed search on ?
    (3) What limit is there on the number of function based indexes per table ?
    (4) I believe XQuery can include a wildcard for namespaces, but XPath 1.x can't. Can I create a function based index using XQuery, rather than XPath ?
    Documents conforming to different versions of an XML schema will be present (schema versioning), but I want to search across all documents irrespective of a specific namespace - e.g. "Find any document with reference = 'some Value' , and amount = 1000".
    CLOB storage is proposed, due to the need to handle documents from multiple versions of an XML schema. The knowledge of the XSD is not known at development time, but is user definable, and it must be possible to change the structure without system down time. Structured storage is not suitable, due to Oracle's requirement for downtime if the schema changes (CopyEvolve drops/recreates tables), and Oracle doesn't support schema collections, so you can't bind an XML column to multiple schemas.
    Here is some sample code of what I'm trying to do:
    create table BulkTest
    ID NUMBER(10) not null primary key,
    USERFIELDS XMLTYPE
    create sequence S_BulkTest;
    --Document conforming to version 1 of schema
    INSERT INTO BulkTest(id, Userfields) VALUES
    (S_BulkTest.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <mt395 xmlns="urn:incident:mt395-1">
         <reference>FH12345678</reference>
         <relatedReference>FH23456789</relatedReference>
         <queries>Here is some query text.</queries>
         <narrative>Here is some narrative text.</narrative>
         <relatedMessageType>300</relatedMessageType>
         <relatedMessageDate>2005-03-29</relatedMessageDate>
         <direction>R</direction>
         <sessionNumber>1234</sessionNumber>
         <isn>123456</isn>
         <relatedMessageDescription>This is the deal where I bought USD 1 million for GBP at 1.76.</relatedMessageDescription>
         <otherParty>232332</otherParty>
    </mt395>'
    --Document conforming to version 2 of schema
    INSERT INTO BulkTest(id, Userfields) VALUES
    (S_BulkTest.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <mt395 xmlns="urn:incident:mt395-2">
         <guid>0f9a08f6-b052-4693-baba-8f7dc881e7e8</guid>
         <reference>333333</reference>
         <queries>Another query</queries>
         <narrative>Some narrative</narrative>
         <direction>R</direction>
         <sessionNumber>1234</sessionNumber>
         <isn>223456</isn>
    </mt395>'
    --It seems I need to create a new index for each field I want to search on
    create index iBulkTest_REFERENCE
    on BulkTest
    (extractValue(UserFields,'/mt395/reference', 'xmlns="urn:incident:mt395-1"'));
    --And that a new index is required for each specifc namespace that is present
    --Can't we include a wildcard in the namespace ?
    create index iBulkTest_REFERENCE_2
    on BulkTest
    (extractValue(UserFields,'/mt395/reference', 'xmlns="urn:incident:mt395-2"'));
    --If I want to query, I have to explicitly specify each namespace.
    --Can't I specify a wildcard ?
    --This will make it "fun" querying across namespaces!
    select
    id,
    extractValue(UserFields,'/mt395/reference', 'xmlns="urn:incident:mt395-2"') As Reference,
    t.userfields.getclobval() userfields
    from bulktest t
    WHERE extractValue(UserFields,'/mt395/reference', 'xmlns="urn:incident:mt395-2"') = '333333'

    Andy
    #1. You do not have scehma versioning here. Your model is totally incorrect. You shoud not change the namespace when versioning the XML Schema. You have 2 different and totally disjoint XML Schemas. The correct was to version, as distinct from evolve an XML Schema is to change the Schema Location Hint associated with your XML...
    Eg
    INSERT INTO BulkTest(id, Userfields) VALUES
    (S_BulkTest.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <mt395 xmlns="urn:incident:mt395" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:incident:mt395 mt395-1.xsd">
    <reference>FH12345678</reference>
    <relatedReference>FH23456789</relatedReference>
    <queries>Here is some query text.</queries>
    <narrative>Here is some narrative text.</narrative>
    <relatedMessageType>300</relatedMessageType>
    <relatedMessageDate>2005-03-29</relatedMessageDate>
    <direction>R</direction>
    <sessionNumber>1234</sessionNumber>
    <isn>123456</isn>
    <relatedMessageDescription>This is the deal where I bought USD 1 million for GBP at 1.76.</relatedMessageDescription>
    <otherParty>232332</otherParty>
    </mt395>'
    --Document conforming to version 2 of schema
    INSERT INTO BulkTest(id, Userfields) VALUES
    (S_BulkTest.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <mt395 xmlns="urn:incident:mt395 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:incident:mt395 mt395-2.xsd">
    <guid>0f9a08f6-b052-4693-baba-8f7dc881e7e8</guid>
    <reference>333333</reference>
    <queries>Another query</queries>
    <narrative>Some narrative</narrative>
    <direction>R</direction>
    <sessionNumber>1234</sessionNumber>
    <isn>223456</isn>
    </mt395>'
    This is the correct way of versioning an XML Schema. THe namespace stays the same, the SchemaLocationHint in the SchemaLocation tag changes.
    Bear in mind that if you use the technique you are currently using you will make any path expressions you need to write absolutely unmaintaining and the processing of them very inefficient.
    Some questions to consider
    Node 'X' in namespace 'X' is never the same as Node 'X' in namespace 'Y'.
    How would you write an Xpath or XQuery that targetted multiple versions, but not all versions ?
    What happens if you have other documents that are really in a different namespace ? Using wildcards can you differentiate them..
    From the problem you are describing and the terminolgy you are using it looks like you've been an early customer of Yukon. MSFT clearly didn't understand schema versioning in the early beta releases and used the 'change the namespace' schema for modelling schema versioning.
    We do have some technology coming down the pipe which can address the issue, regardless of whether or not it is too late for you to correct the versioning scheme you have selected. However I cannot discuss that in a public forum. If you want to learn about these features and are prepared to enter an NDA with Oracle in order to do so please contact me directly. You can do this a number of ways...
    Guess my email address @oracle.com
    Post your email address here and I'll delete the post as soon as I have it..
    Update your OTN Forum profile to include your email address
    Open a TAR and post the tar number here. You can then softclose the tar as this is simply a method for me to get your contact info.

  • Query not considering function based index in oracle 11g

    I have a query which used Function Based Index when run in oracle 9i but when I run the same query
    without any changes, it does not consider index. Below is the query:
    SELECT distinct patient_role.domain_key, patient_role.patient_role_key,
    patient_role.emergency_contact_name,
    patient_role.emergency_contact_phone, patient_role.emergency_contact_note,
    patient_role.emergency_contact_relation_id,
    patient_role.financial_class_desc_id, no_known_allergies, patient_role.CREATED_BY,
    patient_role.CREATED_TIMESTAMP,
    patient_role.CREATED_TIMESTAMP_TZ, patient_role.UPDATED_BY, patient_role.UPDATED_TIMESTAMP,
    patient_role.UPDATED_TIMESTAMP_TZ,
    patient_role.discontinued_date
    FROM encounter, patient_role
    WHERE patient_role.patient_role_key = encounter.patient_role_key
    AND UPPER(TRIM(leading :SYS_B_0 from encounter.account_number)) = UPPER(TRIM(leading :SYS_B_1 from
    :SYS_B_2))
    AND patient_role.discontinued_date IS null
    AND encounter.discontinued_date IS null ;
    Index definition:
    CREATE INDEX "user1"."IX_TRIM_ACCOUNT_NUMBER" ON "user1."ENCOUNTER" (UPPER(TRIM(LEADING
    '0' FROM "ACCOUNT_NUMBER")), "PATIENT_ROLE_KEY", "DOMAIN_KEY", "DISCONTINUED_DATE")
    PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
    BUFFER_POOL DEFAULT)
    TABLESPACE "user1"
    Database : Oracle 11g (11.2.0.3)
    O/S : Linux 64 bit (the query does not consider index even on windows os)
    Any suggestions?
    -Onkar
    Edited by: onkar.nath on Jul 2, 2012 3:32 PM

    Onkar,
    I don't appreciate you posting this question in several forums at the same time.
    If I would know you also posted this on Asktom, I wouldn't even have bothered.
    As to your 'issue':
    First of all: somehow cursor_sharing MUST have been set to FORCE. Oracle is a predictable system, not a fruitmachine.
    Your statement the '0' is replaced by a bind variable anyway is simply false. If you really believe it is not false, SUBMIT a SR.
    But your real issue is not Oracle: it is your 'application', which is a mess anyway. Allowing for alphanumeric numbers is a really bad idea.
    Right now you are already putting workaround on workaround on workaround on workaround.
    Issue is the application: it is terminal., and you either need to kill it, or to replace it.
    Sybrand Bakker
    Senior Oracle DBA

  • Query Transformation in Function Based Index's Expression

    Hi All,
    I am having a wired issue with Function Based Indexes on Orcale 10.2.0.3 running on Solaris 5.9.
    I have created two FBI on two tables using following syntax.
    CREATE INDEX EQHUB.IDX_BBO_WRT_DES_FBI ON EQHUB.BBO_WARRANT_PRICING (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END);
    CREATE INDEX EQHUB.IDX_BBO_DES_FBI ON EQHUB.BBO_DESCRIPTIVE_DATA (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END);
    For the second command (IDX_BBO_DES_FBI), when i query DBA_IND_EXPRESSIONS view, i found that Oracle has done some kind of QUERY TRANSFORMATION (?) and converted
    FBI expression to CASE "LATEST_VERSION_FLAG" WHEN 'Y' THEN 1 ELSE NULL END.At the same time,EXPRESSION on first index is not changed.
    Now,my question is what has made transformation to occure only for second index.
    I also found that inspite of highly SELECTIVE nature of both the indexes, only SECOND index is being used by CBO (for which trasnformation occured)
    and IDX_BBO_WRT_DES_FBI is not being used(FTS is happening instead).
    Query is using same expression for both the tables as
    (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END)=1
    INDEX_NAME                          TABLE_NAME                          COLUMN_EXPRESSION
    IDX_BBO_WRT_DES_FBI                 BBO_WARRANT_PRICING                 CASE  WHEN "LATEST_VERSION_FLAG"='Y' THEN 1 ELSE NULL END
    IDX_BBO_DES_FBI                     BBO_DESCRIPTIVE_DATA                CASE "LATEST_VERSION_FLAG" WHEN 'Y' THEN 1 ELSE NULL ENDI read that expression should be evaluated including CASE of characters and spaces in query.Is that true?
    Appreciating responses in advance.

    Randolf.
    It's a shame that I forgot to look into the full execution plan information to check how Oracle really handles my queries.
    Look here(edited for clarity):
    explain plan for
    select /*+ case1 ordered use_nl(x, y) */ count(case c1
        when '1' then 1
        when '2' then 2
        when '3' then 3
        else 4
      end) from
    (select level from dual connect by level <= 300000) x,
    (select
    from t1
    ) y;
    | Id  | Operation                       | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |      |     1 |     2 |     5   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE                 |      |     1 |     2 |            |          |
    |   2 |   NESTED LOOPS                  |      |     3 |     6 |     5   (0)| 00:00:01 |
    |   3 |    VIEW                         |      |     1 |       |     2   (0)| 00:00:01 |
    |   4 |     CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
    |   5 |      FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL            | T1   |     3 |     6 |     3   (0)| 00:00:01 |
    Column Projection Information (identified by operation id):
       1 - (#keys=0) COUNT(CASE  WHEN "T1"."C1"='1' THEN 1 WHEN "T1"."C1"='2' THEN
           2 WHEN "T1"."C1"='3' THEN 3 ELSE 4 END )[22]
       2 - (#keys=0) "T1"."C1"[CHARACTER,1]
       4 - "DUAL".ROWID[ROWID,10], LEVEL[4]
       5 - "DUAL".ROWID[ROWID,10]
       6 - "T1"."C1"[CHARACTER,1]
    32 rows selected.
    explain plan for select /*+ case2 ordered use_nl(x, y) */ count(case
        when c1 = '1' then 1
        when c1 = '2' then 2
        when c1 = '3' then 3
        else 4
      end) from
    (select level from dual connect by level <= 300000) x,
    (select
    from t1
    ) y;
    | Id  | Operation                       | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |      |     1 |     2 |     5   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE                 |      |     1 |     2 |            |          |
    |   2 |   NESTED LOOPS                  |      |     3 |     6 |     5   (0)| 00:00:01 |
    |   3 |    VIEW                         |      |     1 |       |     2   (0)| 00:00:01 |
    |   4 |     CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
    |   5 |      FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL            | T1   |     3 |     6 |     3   (0)| 00:00:01 |
    Column Projection Information (identified by operation id):
       1 - (#keys=0) COUNT(CASE  WHEN "T1"."C1"='1' THEN 1 WHEN "T1"."C1"='2' THEN
           2 WHEN "T1"."C1"='3' THEN 3 ELSE 4 END )[22]
       2 - (#keys=0) "T1"."C1"[CHARACTER,1]
       4 - "DUAL".ROWID[ROWID,10], LEVEL[4]
       5 - "DUAL".ROWID[ROWID,10]
       6 - "T1"."C1"[CHARACTER,1]As you exactly mentioned, I was executing different SQL but actually same queries!
    Thanks for pointing my flaws.
    PS) OP, forgive me for bothering you with off-topic things. :)
    ================================
    Dion Cho - Oracle Performance Storyteller
    http://dioncho.wordpress.com (english)
    http://ukja.tistory.com (korean)
    ================================
    Edited by: Dion_Cho on Feb 10, 2009 5:45 AM
    Typo

  • Creating function-based indexes

    I'm trying to create a function-based index in one of the user's schemas and am getting an insufficient privilege error. Below are the examples:
    connect scott/tiger ;
    CREATE INDEX emp_ename_idx ON ename( emp ) ;
    Index created.
    CREATE INDEX upper_ename_idx ON ename( upper(ename)) ;
    ERROR at line1:
    ORA-01031: insufficient privileges
    The DBA granted the CREATE ANY INDEX privilege to user scott already. Any ideas???
    Thanks,
    SY

    Hi, all.
    I didn't hear about function-based index before, so I did some testing. Instead of using Oracle predefined functions (upper, lower, substr etc.), I created my own function and tried to create an index on it. I received an error that function is not deterministic. The definition of deterministic from Oracle docs:
    DETERMINISTIC
    This hint helps the optimizer avoid redundant function calls. If a stored function was called previously with the same arguments, the optimizer can elect to use the previous result. The function result should not depend on the state of session variables or schema objects. Otherwise, results might vary across calls. Only DETERMINISTIC functions can be called from a function-based index or a materialized view that has query-rewrite enabled.
    So, I put word deterministic in function declaration and everything works OK. Then I modified function to use some of the tables (I used tables across different schemas), recreated the index and it also worked fine.
    Question - is this statement correct: You can use schema objects in function which is in turn used for indexes as long as you put word deterministic in function declaration and all objects (function, index) will be valid, but ORACLE doesn't guarantee that result produced using that index will be correct?
    Thank you.

  • Primary Key definition does not copy over to alias

    I imported a db table in physical layer and defined the key on it.
    When I create an alias of this table, the key definition is not copied over to alias. Is this standard behavior? Do I need to create primary key definition for each alias separately or am I missing something?

    Yes its standard behavior.
    Since key are generated based on joins for that object and can may not be duplicated
    Appreciate if you mark as correct
    Edited by: Veeravalli on Nov 29, 2012 1:14 PM

  • Function-based index with OR in the wher-clause

    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    --We use Oracle 8i (8.1.7)
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index I_FUNCTION_TPERSON_NAME and we have a full table scan in the execution-plan.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like a hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our select-statement is:
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    thank you for time..
    email: [email protected]

    In the realistic statement you write :
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    as far as i know, NULL values are not indexed, "or (NAME is NULL)" have to generate a full table scan.
    HTH
    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    --We use Oracle 8i (8.1.7)
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index I_FUNCTION_TPERSON_NAME and we have a full table scan in the execution-plan.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like a hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our select-statement is:
    select * FROM TPERSON
    where (upper(NAME) like 'MIL%' or (NAME is null))
    and (upper(FIRSTNAME) like 'MICH% or (FIRSTNAME is null))
    and ...;
    thank you for time..
    email: [email protected]

  • Creation of function based index using escape

    Hello,
    I have the following SQL, sometimes performing bad:
    SELECT DISTINCT UPPER(A.PROCESSIDCODE), UPPER(A.RULENAME), CHARSET
    FROM XIB_DETECT A, XIB_PROCESSIDPROPERTIES B, XIB_RULES C
    WHERE ( A.KEY1 = :P1 OR ( :P1 like REPLACE(REPLACE(REPLACE(REPLACE(KEY1,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\' AND A.REGFLAGS1 = 'Y') OR A.KEY1 = '*' AND A.REGFLAGS1 = 'Y')
    AND (A.KEY2 = :P2 OR ( :P2 like REPLACE(REPLACE(REPLACE(REPLACE(KEY2,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\' AND A.REGFLAGS2 = 'Y') OR (A.KEY2 IS NULL AND A.REGFLAGS2 IS NULL ) )
    AND (A.KEY3 = :P3 OR ( :P3 like REPLACE(REPLACE(REPLACE(REPLACE(KEY3,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\' AND A.REGFLAGS3 = 'Y') OR (A.KEY3 IS NULL AND A.REGFLAGS3 IS NULL ) )
    AND (A.KEY4 = :P4 OR ( :P4 like REPLACE(REPLACE(REPLACE(REPLACE(KEY4,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\' AND A.REGFLAGS4 = 'Y') OR (A.KEY4 IS NULL AND A.REGFLAGS4 IS NULL ) )
    AND (A.KEY5 = :P5 OR ( :P5 like REPLACE(REPLACE(REPLACE(REPLACE(KEY5,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\' AND A.REGFLAGS5 = 'Y') OR (A.KEY5 IS NULL AND A.REGFLAGS5 IS NULL ) )
    AND (A.KEY6 IS NULL OR A.KEY6 = '*' AND REGFLAGS6 = 'Y')
    AND (A.KEY7 IS NULL OR A.KEY7 = '*' AND REGFLAGS7 = 'Y')
    AND (A.KEY8 IS NULL OR A.KEY8 = '*' AND REGFLAGS8 = 'Y')
    AND (A.KEY9 IS NULL OR A.KEY9 = '*' AND REGFLAGS9 = 'Y')
    AND (A.KEY10 IS NULL OR A.KEY10 = '*' AND REGFLAGS10 = 'Y')
    AND ( ( A.PROCESSIDCODE IS NOT NULL AND UPPER(A.PROCESSIDCODE) = UPPER(B.PROCESSIDCODE) AND A.XLEVEL = B.XLEVEL AND B.ACTIVEFLAG = 'Y' )
    OR ( A.RULENAME IS NOT NULL AND UPPER(A.RULENAME) = UPPER(C.RULENAME) AND A.XLEVEL = C.XLEVEL AND C.ACTIVEFLAG = 'Y' ) );
    Now I want to create a function based index on the key1 column:
    CREATE INDEX xib_detect_ix ON xib_detect (REPLACE(REPLACE(REPLACE(REPLACE(KEY1,'%', '\%'),'_', '\_'),'?', '_'),'*','%') escape '\') TABLESPACE ... ONLINE;
    However, this is not working with "escape" '\', throwing: ORA-00907: missing right parenthesis
    Any idea how to create an index on this construct with "escape"?
    Database version is 10.2.0.3.
    Thanks a lot.
    Regards
    Oliver

    Hi,
    You can get the "missing right parenthesis" error for many different syntax errors.
    In this case, you really are missing a right parenthesis.  Your statement has 5 left '('s, but only 4 right ')'s.  It's easy to see this if you format your code:
    CREATE  INDEX xib_detect_ix
    ON  xib_detect ( REPLACE ( REPLACE ( REPLACE ( REPLACE ( KEY1
                     escape '\'
    ESCAPE is an option that you can use with the LIKE operator.  It gives you a mechanism for cancelling the special meaning of symbols like '%'.    You're not using the LIKE operator to create the index.  You're only using REPLACE, and no characters have any special meaning in REPLACE, so there's no way (or reason) to escape them.  Use ESCAPE in queries that use LIKE, when appropriate.

  • Function-Based Indexes for 8.1.6 SE and 9iAS

    I have installed the 9iAS Portal into a 8.1.6 SE database, and I cannot get the Function-Based Index feature to turn on. I have set QUERY_REWRITE_INTEGRITY=trusted, QUERY_REWRITE_ENABLED=true and COMPATIBLE="8.1.0.0.0". The feature will still not enable.
    I have 2 questions:
    1. Is there anything else I can do to turn this feature on.
    2. If not, do I have to upgrade to 8.1.7 or to 8.1.* Enterprise Edition to make use of this feature.

    Could you give the statement for the index you have used, the query you try to do and a description of columns and datatypes of the table? How do you know/check that is doesn't work? Execution plan, errors?...

  • FUNCTION-BASED INDEX ( ORACLE 8I NEW FEATURE )

    제품 : ORACLE SERVER
    작성날짜 : 2004-08-16
    FUNCTION-BASED INDEX ( ORACLE 8I NEW FEATURE )
    ==============================================
    SCOPE
    10g Standard Edition(10.1.0) 이상 부터 Function-based Index 기능이 지원된다.
    Explanation
    1. 개요
         Function-based index는, 함수(function)이나 수식(expression)으로 계산
    된 결과에 대해 인덱스를 생성하여 사용할 수 있는 기능을 제공한다.
         질의 수행 시 해당 함수나     수식을 처리하여     결과를 가져 오는 것이 아니라,
         인덱스 형태로 존재하는 미리 계산되어 있는 결과를 가지고 처리하므로
         성능 향상을 기할 수 있다.
    2. 제약사항
    1) aggregate function 에 대한 function-based index 생성 불가.
    (예 : sum(...) )
    2) LOB, REF, nested table 컬럼에 대한 function-based index 생성 불가.
    3. 주요 특징
         1) cost-based optimizer에 의해 사용됨.
         2) B*Tree / bitmap index로 생성 가능.
         3) 산술식 (arithmetic expression), PLSQL function, SQL built-in
    function 등에 적용 가능.
         4) 함수나 수식으로 처리된 결과에 대한 range scan 가능
         5) NLS SORT 지원
         6) SELECT/DELETE를 할 때마다 함수나 수식의 결과를 계산하는 것이 아니라
         INSERT/UPDATE 시 계산된 값을 인덱스에 저장.
         7) 질의 속도 향상
         8) object column이나 REF column에 대해서는 해당 object에 정의된
         method에 대해 function-based index 생성 가능.
    4. 생성 방법
         CREATE [UNIQUE | BITMAP ] INDEX <index_name>
         ON <tablename> (<index-expression-list>)
         <index-expression-list> -> { <column_name> | <column_expression> }
         예) CREATE INDEX EMP_NAME_INDEX ON EMP (UPPER(ENAME));
         CREATE INDEX EMP_SAL_INDEX ON EMP( SAL + COMM, empno);
         * Function-based index를 생성하기 위해서는 QUERY REWRITE 권한이
         부여 되어 있어야만 한다.
         예) GRANT QUERY REWRITE TO SCOTT;
    5. Function-Based Index 사용을 위한 사전 작업
         1) Function-based index는 cost based optimizer에서만 사용 가능하므로,
         테이블에 대해 미리 analyze 해 주는 것이 바람직하다.
         그리고 init 파일에서 OPTIMIZER_MODE 를 FIRST_ROWS 나 ALL_ROWS 등으
    로 지정하거나 HINT 등을 사용하여 cost based optimizer가 사용되도록
    한다.
         2) init 파일에서 COMPATIBLE 파라미터 값을 8.1 이상으로 설정되어 있어야
    한다.
         ( 예 : COMPATIBLE = 8.1.6 )
         3) session/instance level 에서 QUERY_REWRITE_ENABLED 값이 TRUE 지정
    되어 있어야 한다.
         ( 예 : ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE; )
    6. 예제
         1) init 파라미터에서 다음과 같이 지정
         compatible = 8.1.6 (반드시 8.1이상이어야 한다)
         query_rewrite_enabled = true
         query_rewrite_integrity = trusted
         2) SCOTT 유저에서 function_based_index 생성
         create index idx_emp_lower_ename
         on emp
         ( lower(ename) ) ;
         3) EMP table analyze
         analyze table emp compute statistics ;
         4) PLAN_TABLE 생성
         @ ?/rdbms/admin/utlxplan.sql
         5) Cost based optimizer 선택
         alter session set optimizer_mode = FIRST_ROWS ;
         6) Query 실행
         explain plan set statement_id='qry1' FOR
         select empno, ename
         from emp
         where lower(ename) = 'ford' ;
         7) PLAN 분석
         SELECT LPAD(' ',2*level-2)||operation||' '||options||' '||object_name query_plan
         FROM plan_table
         WHERE statement_id='qry1'
         CONNECT BY prior id = parent_id
         START WITH id = 0 order by id ;
         -> 결과
         QUERY_PLAN
         SELECT STATEMENT
         TABLE ACCESS BY INDEX ROWID EMP
         INDEX RANGE SCAN IDX_EMP_LOWER_ENAME
    7. 결론
    Function-based index는 적절하게 사용될 경우 성능상의 많은 이점을 가져
    온다. Oracle8i Designing and Tuning for Performance에서도 가능한 한
    Function-based index를 사용하는 것을 권장하고 있으며, LOWER(), UPPER()
    등의 함수를 사용하여 불가피하게 FULL TABLE SCAN을 하는 경우에 대해서도
    효과적으로 처리해 줄 수 있는 방안이라 할 수 있다.
    Reference Documents
    -------------------

    Partha:
    From the Oracle8i Administrators Guide:
    "Table owners should have EXECUTE privileges on the functions used in function-based indexes.
    For the creation of a function-based index in your own schema, you must be
    granted the CREATE INDEX and QUERY REWRITE system privileges. To create
    the index in another schema or on another schemas tables, you must have the
    CREATE ANY INDEX and GLOBAL QUERY REWRITE privileges."
    Hope this helps.
    Peter

  • Function-based indexes

    Oracle documentation on "How Function-Based Indexes Work" states that for the creation of a function-based index in the user's own schema, the user must be granted the QUERY REWRITE system privileges. And MUST have the following initialization parameters defined to create a function-based index:
    QUERY_REWRITE_INTEGRITY set to TRUSTED
    QUERY_REWRITE_ENABLED set to TRUE.
    I have created a function-based unique index, which uses the SQL function DECODE(). But the user doesn't have the QUERY REWRITE sytem privilege. The user has the following privileges:
    CREATE PROCEDURE
    CREATE SEQUENCE
    CREATE SESSION
    CREATE TABLE
    CREATE TRIGGER
    CREATE VIEW
    And also the initialization parameters for QUERY_REWRITE_INTEGRITY and QUERY_REWRITE_ENABLED are set to their DEFAULT values as follows:
    QUERY_REWRITE_INTEGRITY set to ENCFORCED
    QUERY_REWRITE_ENABLED set to FALSE.
    Note: The index is an unique index for data integrity purpose. I am using Oracle 9.2.0.6 version.
    Kindly explain me the reason how the function-based index is created without the system privilege and the initialization parmaters defined as stated in the Oracle9i Database Administrator's Guide Release 2 (9.2).

    You can change those parameter at session level as well.
    Following link would be helpful:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:2552324147195810457::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:667694821129
    Jaffar

  • Function-based Index and an OR-condition in the WHERE-clause

    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    (We use oracle 8i (8.1.7))
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like an hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our prepared select-statement run in
    SQL Plus:
    define x_name = 'MIL%';
    define x_firstname = '';
    select * FROM TPERSON
    where (upper(NAME) like '&x_name' or ( '&x_name' = ''))
    and (upper(FIRSTNAME) like '&x_firstname' or ('&x_firstname' = ''))
    and ...;
    In particular we dont refernce the tablecolumn , but the QUERY-Parameter
    yield the second boolean value in the or-condition.
    The problem is that this condition ('&x_name' = '') dont use any index.
    thanks a lot for spending your time with this problem

    Try
    SELECT /*+ RULE */
    as your hint. I don't have the book with me, but this last weekend I read a section about your very problem. The book was a Oracle Press gold cover about Oracle 8i Performance tuning. If you e-mail me I can quote you the chapter when I get home Friday.

Maybe you are looking for

  • Summarising Summary Fields

    Post Author: lazarus CA Forum: Formula Just want to say that i'm glad this forum exists. Many a late night has been spend trawling the net for solutions to CR issues which ultimately never get resolved. Hopefully this lovely forum can get me and the

  • Upgrading Imac g4 flat panel 800 mhz

    I decided to post this information here because a lot of people are wondering how do i go about upgrading a macintosh imac g4 A.K.A Ilamp as it is known in the mac community. Well this tutorial will walk you through a basic configuration that i recen

  • Insert Record not saving values

    Hi, I am extremely new to Dreamweaver. I am using MX2004. I am trying to work with a remote database that I created in MySQL and I am using PHP. I created a PHP page added my form, added my input fields, and used the Insert Record wizard to get to my

  • Sap script block positioning.

    hi, i have 2 pages in my sap script. both the pages have the same "main" window. i have given box command in the begining of this main window: /:BOX XPOS '.5' CM YPOS '0' CM WIDTH '25' CM HEIGHT '1'  CM FRAME 0 TW  INTENSITY 15 /:BOX XPOS '.5' CM YPO

  • How to assign characteristic to Dimension ( Advices)

    Hello Experts, I need small clarification from your side. When assigning the characterstic to perticular dimension (What are the precautions we have to take care). how to deside this characterstic has to be  assign to this dimension , i confused many