Labels

Script categories

Showing posts with label Constraints. Show all posts
Showing posts with label Constraints. Show all posts

Wednesday, 7 August 2013

Indentify unindexed Foreign Key columns

The following statement lists unindexed foreign key columns. The statement covers single as well as multi-column foreign key.

undefine schema_owner
set pagesize 5000
set linesize 350
column status format a10
column table_name format a30
column fk_name format a30
column fk_columns format a30
column index_name format a30
column index_columns format a30


select
        case
          when b.table_name is null then
            'unindexed'
          else
            'indexed'
        end               as status
       ,a.table_name      as table_name
       ,a.constraint_name as fk_name
       ,a.fk_columns      as fk_columns
       ,b.index_name      as index_name
       ,b.index_columns   as index_columns
from
    (
      select a.table_name
            ,a.constraint_name
            ,listagg(a.column_name, ',') within
             group (order by a.position) fk_columns
      from
             dba_cons_columns   a
            ,dba_constraints    b
      where
             a.constraint_name  = b.constraint_name
      and    b.constraint_type  = 'R'
      and    a.owner            = '&&schema_owner'
      and    a.owner            = b.owner
      group by a.table_name, a.constraint_name
    ) a
   ,(
      select table_name
            ,index_name
            ,listagg(c.column_name, ',') within
             group (order by c.column_position) index_columns
      from
             dba_ind_columns  c
      where  c.index_owner    = '&&schema_owner'
      group BY table_name, index_name
    ) b
where
      a.table_name        =     b.table_name(+)
and   b.index_columns(+)  like  a.fk_columns || '%'
order by 1 desc, 2;

 
Save the above statement in a file, identify_unindexed_foreign_keys.sql. 
Now test:

SQL> create table t1 (a number, b number);

Table created.

SQL> alter table t1 add constraint t1_pk primary key (a,b);

Table altered.

SQL> create table t2 (a number, b number, c number);

Table created.

SQL> alter table t2 add constraint t2_fk foreign key (a,b)
  2  references t1(a,b);

Table altered.

SQL> @identify_unindexed_foreign_keys.sql
Enter value for schema_owner: USERNAME

STATUS     TABLE_NAME FK_NAME FK_COLUMNS INDEX_NAME INDEX_COLUMNS
---------- ---------- ------- ---------- ---------- -------------
unindexed  T2         T2_FK   A,B
 

SQL> create index idx_t2 on t2 (a,b);

Index created.

SQL> @identify_unindexed_foreign_keys.sql
Enter value for schema_owner: USERNAME

STATUS     TABLE_NAME FK_NAME FK_COLUMNS INDEX_NAME INDEX_COLUMNS
---------- ---------- ------- ---------- ---------- -------------
indexed    T2         T2_FK   A,B        IDX_T2     A,B

The above statement does not however list indexes on composite foreign keys where the column order in the index differs to that of the foreign key constraint.

For example:

SQL> drop index idx_t2;

Index dropped.

SQL> create index idx_t2 on t2 (b,a);

Index created.

SQL> @identify_unindexed_foreign_keys.sql
Enter value for schema_owner: USERNAME

STATUS     TABLE_NAME FK_NAME FK_COLUMNS INDEX_NAME INDEX_COLUMNS
---------- ---------- ------- ---------- ---------- -------------
unindexed  T2         T2_FK   A,B



The statement requires some modification so as to list foreign keys as "indexed", regardless of the column order of the composite index.

the modified statement:

select
      case
        when i.index_name is not null then
          'indexed'
        else
          'unindexed'
       end                  as status
      ,c.table_name         as table_name
      ,c.constraint_name    as fk_name
      ,c.fk_columns         as fk_columns
      ,i.index_name         as index_name
      ,i.index_columns      as index_columns
from
    (
      select  a.table_name
             ,a.constraint_name
             ,listagg(b.column_name, ' ' )
              within group (order by column_name) as fk_columns
      from
              dba_constraints a
             ,dba_cons_columns b
      where
              a.constraint_name = b.constraint_name
      and     a.constraint_type = 'R'
      and     a.owner           = b.owner
      and     a.owner           = '&&schema_owner'
      group by
              a.table_name
             ,a.constraint_name
    ) c
left outer join
  (
    select  table_name
           ,index_name
           ,cr
           ,listagg(column_name, ' ')
            within group (order by column_name) as index_columns
    from
        (
          select
                  table_name
                 ,index_name
                 ,column_position
                 ,column_name
                 ,connect_by_root(column_name) cr
          from
                  dba_ind_columns
          where
                  index_owner               = '&&schema_owner'
          connect
                 by prior column_position-1 = column_position
                 and prior index_name       = index_name
         )
    group by table_name
            ,index_name, cr
  ) i
      on c.fk_columns = i.index_columns
     and c.table_name = i.table_name;


the foreign key will now be shown as "indexed", once the script file has been modified :-)

SQL> @identify_unindexed_foreign_keys.sql
Enter value for schema_owner: USERNAME

STATUS     TABLE_NAME FK_NAME FK_COLUMNS INDEX_NAME INDEX_COLUMNS
---------- ---------- ------- ---------- ---------- -------------
indexed    T2         T2_FK   A,B        IDX_T2     A,B


Thursday, 11 July 2013

Table foreign key script generator

The script below generates a script, which when executed will create a table with data along with foreign keys and indexes on foreign key columns based on a table on a remote server and accessed via a database link.

  
set feedback off
set verify off
set linesize 1000
set pagesize 5000
set heading off

undefine Table_to_Script
undefine DB_Link_to_use

variable tbl_name varchar2(30);
variable db_link_name varchar2(30);
exec :tbl_name := '&Table_to_Script';
exec :db_link_name := '&DB_Link_to_use';

select 'Table selected for scripting : ' || upper(:tbl_name) || ';'
from dual;

select 'DB Link to use : ' || upper(:db_link_name) || ';'
from dual;

SELECT 'DROP TABLE ' || TABLE_NAME || ';'
FROM USER_TABLES
WHERE TABLE_NAME = :tbl_name;

set serveroutput on for wra size unlimited
begin
  dbms_output.put_line('prompt Create table ' || :tbl_name);
  dbms_output.put_line('create table '
                           || :tbl_name
                           || ' as (select * from '
                           || :tbl_name
                           || '@'
                           || :db_link_name
                           || ');');
end;
/

-- Create primary and/or unique keys first off
declare

  l_PK_Str    varchar2(4000);
  l_Tbl_Name  varchar2(30) := :tbl_name;

begin

  -- Assume that indexes will exist for all foreign keys
  for p in (select  uc.constraint_name as pk_constraint_name
                   ,uc.table_name
                   ,uc.constraint_type
                   ,'('||
                    listagg(ucc.column_name, ',')
                    within group (order by ucc.position)
                    || ')' as col_lst
            from
                    user_cons_columns   ucc
                   ,user_constraints    uc
            where
                    uc.table_name       = l_Tbl_Name
            and     uc.table_name       = ucc.table_name
            and     uc.constraint_name  = ucc.constraint_name
            and     uc.constraint_type  in ('P', 'U')
            group by uc.table_name

                    ,uc.constraint_name
                    ,uc.constraint_type
            ) loop


    l_PK_Str := 'alter table ' || l_Tbl_Name 
                               || ' add constraint ' 
                               || p.pk_constraint_name
                               || case p.constraint_type
                                     when 'P' then
                                       ' primary key '
                                     else
                                       ' unique '
                                   end
                               || p.col_lst || ';';

    dbms_output.put_line(null);
    dbms_output.put_line('prompt Add ' 

                            || case p.constraint_type 
                                 when 'P' then 
                                   ' primary ' 
                                 else 
                                   ' unique ' 
                               end 
                            || ' key to ' 
                            || p.table_name);

    dbms_output.put_line(l_PK_Str);

  end loop;

end;
/

declare
  l_FK_Str    varchar2(1000);
  l_Cnt       number;
  l_Tbl_Name  varchar2(30) := :tbl_name;
begin
  for r in (select  u1.constraint_name    as constraint_name
                   ,u1.r_constraint_name  as r_constraint_name
                   ,u1.table_name         as table_name
                   ,u2.table_name         as Ref_Tbl
            from
                    user_constraints      u1
                   ,user_constraints      u2
            where
                    u1.table_name         = l_Tbl_Name
            and     u1.constraint_type    = 'R'
            and     u1.r_constraint_name  = u2.constraint_name 

           )        loop


    l_FK_Str := 'alter table ' || r.table_name
                || ' add constraint '
                || r.constraint_name
                || ' foreign key (';

    -- add table foreign key columns
    for k in (select  column_name
              from    user_cons_columns
              where   constraint_name = r.constraint_name
              order by position) loop

      l_FK_Str := l_FK_Str || k.Column_Name || ',';
    end loop;

    -- strip off trailing commans and replace with ')'
    l_FK_Str :=    substr(l_FK_Str, 1, length(l_FK_Str) - 1)
                || ') references '
                || r.Ref_Tbl
                || '(';

    -- add reference table key columns
    for k in (select  column_name
              from    user_cons_columns
              where   constraint_name = r.r_constraint_name
              order by position) loop

      l_FK_Str := l_FK_Str || k.Column_Name || ',';
    end loop;

    l_FK_Str := substr(l_FK_Str, 1, length(l_FK_Str) - 1) || ');';

    dbms_output.put_line(null);
    dbms_output.put_line('prompt Add foreign key to table ' 

                          || l_Tbl_Name 
                          || ' references ' 
                          || r.Ref_Tbl 
                          || substr(l_FK_Str
                                   ,instr(l_FK_Str,  '(', 1)
                                   ,(instr(l_FK_Str,')',1) -  

                                     instr(l_FK_Str,'(',1)+1)
                                   )
                        );
    dbms_output.put_line(l_FK_Str);
  end loop;

  -- Assume that indexes will exist for all foreign keys
  for i in (select  'idx_'
                    || substr(uc.constraint_name,1,26) as index_name
                   ,uc.table_name
                   ,'('||
                    listagg(ucc.column_name, ',')
                    within group (order by ucc.position)
                    || ')' as col_lst
            from
                    user_cons_columns ucc
                   ,user_constraints  uc
            where
                    uc.table_name      = :tbl_name
            and     uc.table_name      = ucc.table_name
            and     uc.constraint_name = ucc.constraint_name
            and     uc.constraint_type = 'R'
            group by uc.table_name, uc.constraint_name) loop

    l_FK_Str := 'create index ' || i.Index_Name
                                || ' on '
                                || i.table_name 

                                || i.col_lst 
                                || ';';
 

    dbms_output.put_line(null);
    dbms_output.put_line('prompt prompt Add index on ' 

                            || i.table_name 
                            || i.col_lst);

    dbms_output.put_line(l_FK_Str);

  end loop;


end;
/

set feedback on
set verify on
set heading on

Wednesday, 16 November 2011

Report historical wait times per event for a specific Table

I always try and name my constraint and index names
with the same prefix as my table name and then suffix it with
a few characters to indicate what type of constraint or index it is.

For Example;

For a table such as TRADE_DEAL;

create table Trade_Deal
(Deal_ID      number          not null
,Deal_Type    varchar2(10)
,Deal_version integer
,Created      timestamp default current_timestamp
,Trade_Risk   integer
,GBP_Amnt     number          not null
,USD_Amnt     number);

The primary key would be named as follows;

alter table trade_deal 
add constraint TRADE_DEAL_PK primary key (deal_id);

A check constraint might be named as follows;

alter table trade_deal add constraint
TRADE_DEAL_CK_RISK check (trade_risk in (1,2,3,4,5,6,7,8,9));

The main reason for naming my objects using the above convention
is that it simplifies running queries to asses performance
stats on a particular set of related objects.

For example, the AWR query below will output the time waited
per wait event for a set of related table and indexes.

First set the start and end snapshot ID as variables before
attempting to run the query below. Use this script if you want;
http://bluefrog-oracle.blogspot.com/2011/11/set-start-and-end-snapshot-id-for-awr.html

variable p_Schema varchar2(30);
exec :p_Schema := sys_context('USERENV','CURRENT_SCHEMA');

col Object_Name format a32
col Object_Type format a10
col Event_Name  format a40
select
  /*+ all_rows */
   ds.Instance        as Instance_Number
  ,ao.Object_Name     as Object_Name
  ,ao.Object_Type     as Object_Type
  ,ds.Event           as Event_Name
  ,sum(ds.Cnt)        as Event_Wait_Cnt
  ,sum(Time_Waited)   as Time_Waited
from
  (
   select    /*+ all_rows */
             au.Username
            ,e.Name          as Event
            ,count(*)        as Cnt
            ,sum(Wait_Time)  as Time_Waited
            ,da.Current_Obj# as Object_ID
            ,Instance_Number as Instance
   from
             dba_hist_active_sess_history da
            ,v$Event_Name e
            ,all_users   au
   where     da.Event_ID = e.Event_ID
   and       da.User_ID  = au.User_ID
   and       da.Snap_ID  between :p_Start_Snap_ID and :p_End_Snap_ID
   and       au.Username = :p_Schema
   group by  au.Username
            ,e.Name
            ,da.Current_Obj#
            ,da.Instance_Number
   order by 3 desc
  )                     ds
  ,dba_Objects          ao
where
          ao.Object_ID          = ds.Object_ID
and       ao.Object_name        like  '&Object%'
and       ao.Object_Type        in ('TABLE','INDEX')
-- Exclude SQL Client type of waits
and       ds.Event              not like 'SQL*Net%'
group by  ao.Object_Name
         ,ao.Object_Type
         ,ds.Event
         ,ds.Instance
order by 5 desc, 4
/

Thursday, 13 October 2011

View constraints in a hierarchy

To view a hierarchy of all constraints, starting with a Master table, use the following SQL statement;

select lpad(' ', 4 * level - 1 ) || sys_connect_by_path(Child, '/') as Hierarchy
from
  (
    select  ac.owner || '.' ||  ac.table_name as Child
           ,r.owner  || '.' ||  r.table_name  as Master
    from    all_constraints     ac
           ,all_constraints     r
    where   r.Owner             = ac.r_Owner
    and     r.Constraint_Name   = ac.r_Constraint_Name
    and     ac.Constraint_Type  = 'R'
)
start with Master =  sys_context('userenv','current_schema')||'.CLIENT'
connect by prior Child =  Master
/

For example, given the following set of tables and foreign keys;

create table product (p_id          number
                     ,product_name  varchar2(10)
                     ,price number);
alter table product add constraint p_pk primary key (p_id);

create table client  (c_id number
                     ,client_name varchar2(10));
alter table client add constraint c_pk primary key (c_id);

create table client_order (co_id  number
                          ,c_id   number
                          ,d      date);
alter table client_order add constraint co_pk primary key (co_id);

alter table client_order add constraint co_fk
foreign key (c_id) references client (c_id);

create table order_line (ol_id      number
                        ,co_id      number
                        ,p_id       number
                        ,qty        number
                        ,ol_amount  number);
alter table order_line add constraint ol_pk primary key (ol_id);

alter table order_line add constraint ol_cl_fk
foreign key (co_id) references client_order (co_id);

alter table order_line add constraint ol_po_fk
foreign key (p_id) references product (p_id);

Running the SQL against the CLIENT table will produce the following result;

SQL> variable cs varchar2(30)
SQL> exec :cs := sys_context('userenv','current_schema');

PL/SQL procedure successfully completed.

SQL> select    lpad(' ', 4 * level - 1 )
  2         || sys_connect_by_path(Child, '/') as Hierarchy
  3  from
  4    (
  5      select  ac.owner || '.' ||  ac.table_name as Child
  6             ,r.owner  || '.' ||  r.table_name  as Master
  7      from    all_constraints     ac
  8             ,all_constraints     r
  9      where   r.Owner             = ac.r_Owner
 10      and     r.Constraint_Name   = ac.r_Constraint_Name
 11      and     ac.Constraint_Type  = 'R'
 12  )
 13  start with Master=:cs||'.CLIENT'
 14  connect by prior Child =  Master;

HIERARCHY
------------------------------------------------------------
   /XDB_DEV4.CLIENT_ORDER
       /XDB_DEV4.CLIENT_ORDER/XDB_DEV4.ORDER_LINE

The following query lists the path leading to each table and the level at which the set of foreign key s exists within the path.

with t as
(
    select  Ref_Level
           ,Path
           ,substr(Path

                   ,instr(Path, '/', 1,Ref_Level) +1
                   , length(Path) ) as Table_Name
    from
    (
    select distinct
           level as ref_level
          ,lpad(' ', 4 * level - 1 ) 

               || sys_connect_by_path(Master, '/') as Path
    from
      (
        select  ac.table_name       as Child
               ,r.table_name        as Master
        from   
                all_constraints     ac
               ,all_constraints     r
        where  
                r.Owner             = ac.r_Owner
        and     r.Owner             = '&SCHEMA'
        and     r.Constraint_Name   = ac.r_Constraint_Name
        and     ac.Constraint_Type  = 'R'
    )
    connect by nocycle prior Child = Master
    )
)
--
select *
from
(
select
        Ref_Level
       ,nvl(first_value(Ref_Level) 

        over (partition by table_name 
              order by rn), Ref_Level) as last_level
       ,Path
       ,Table_Name
       ,rn
from
    (
    select     
            Ref_Level
           ,Path 
           ,Table_Name
           ,row_number() 

            over (partition by table_name 
                  order by Ref_Level desc) as rn
    from
            t
    )
);

Listing all foreign key constraints

select ac.owner
      ,ac.table_name
      ,r.owner        as ref_owner
      ,r.table_name   as ref_table
from   all_constraints ac
      ,all_constraints r 
where  r.owner            = ac.r_owner
and    r.constraint_name  = ac.r_constraint_name
and    ac.constraint_type = 'R'
/

Thursday, 22 September 2011

Deferred constraints

DEFERRED forces the check to occur on COMMIT, whereas IMMEDIATE forces the check to occur on INSERT.


The following is an example;


SQL> create table t1 ( a number, b number);

Table created.

SQL> alter table t1 add constraint t1_pk primary key (a);

Table altered.

SQL> create table t2 (a number);

Table created.

SQL> alter table t2 add constraint t2_fk
  2  foreign key (a) references t1 (a)
  3  deferrable initially immediate;
 

Table altered.

SQL> insert into t1 values (1,1);

1 row created.

SQL> insert into t2 values (2);
insert into t2 values (2)
*
ERROR at line 1:
ORA-02291: integrity constraint (XDB_DEV3.T2_FK) violated - parent key not found

SQL> alter session set constraints = deferred;

Session altered.

SQL> insert into t2 values (2);

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (XDB_DEV3.T2_FK) violated - parent key not found

Foreign Keys

create table contact (id number
                     ,referred_by number
                     ,user_refer_type varchar2(1)
                     ,prospect_refer_type varchar2(1));

create table users(id number, refer_type varchar2(1) default 'U');

create table prospect(id number,refer_type varchar2(1) default 'P');

alter table users    add constraint u_pk primary key(id,refer_type);
alter table prospect add constraint p_pk primary key(id,refer_type);

alter table contact add constraint c1_fk foreign key
(referred_by, user_refer_type) references users (id, refer_type);

alter table contact
add constraint c2_fk foreign key (referred_by, prospect_refer_type)
references prospect (id, refer_type);

insert into users (id) values (1);

insert into prospect (id) values (2);

insert into contact (id, referred_by, user_refer_type)
values (1, 1, 'U');

insert into contact (id, referred_by, prospect_refer_type)
values  (2, 2, 'P');

insert into contact (id) values  (3);

Mandatory/optional property of FK is related to mandatory/optional property of FK columns:
Mandatory FK - FK columns will be "not null"
Optional  FK - FK columns will allow nulls