views:

741

answers:

4

I am looking for a fast sql sentence for determine when a field exist or not in a table .

actually i am using this sentence

Select 1 
   from dual
   where exists (select 1 
                   from all_tab_columns 
                  where table_name = 'MYTABLE' 
                    and column_name = 'MYCOLUMN')

I think there must be a fastest way to determine whether or not a column exist in ORACLE.

UPDATE

I'm optimizing a larger software system that makes multiple calls to this Query, I can not modify the source code ;( , only i can modify the query which is stored in an external file.

the Table all_tab_columns has over a million of records.

+5  A: 

Hi RRUZ,

the primary key of all_tab_columns is owner, table_name, column_name so looking for a particular owner will be faster (or use user_tab_columns).

Vincent Malgrat
+1 for adding the owner. Without a table owner the result will be pretty useless. Given that, I'd see what the effect of replacing it with a SELECT 1 FROM DUAL would have.If you want a useful answwer, it may pay to check USER_TAB_COLUMNS first, then ALL_SYNONYMS for either a specific synonym or PUBLIC synonym, then go to ALL_TAB_COLUMNS with the table owner. Note: you can have synonyms pointing to synonyms etc. So a correct answer will be slower.
Gary
+1  A: 

Querying the Oracle data dictionary - as you example indeed does, is probably the fastest way.

The data dictionary is cached in memory and should be able to satisfy the query pretty quickly. You may be able to get slightly faster results if you know the actual schema owner of the table - so that you don't incur the cost of searching against all schemas.

LBushkin
+2  A: 

I suggest reading this AskTom article. It explains that the fastest way to check is not to check at all.

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:698008000346356376

Joseph Bui
+1, very appropo link.
DCookie
A: 

This query is enough:

 SELECT null
  FROM user_tab_columns
 WHERE table_name = 'MYTABLE' and column_name = 'MYCOLUMN'

The only fastest way is to query directly from the internal tables which is not a recommended way and you need grants over sys objects:

select null
from sys.col$ c
   , sys.obj$ o
   , sys.obj$ ot
where o.name = 'MYTABLE'
  and c.name = 'MYCOLUMN'
  and o.obj# = c.obj#
  and o.owner# = userenv('SCHEMAID')
  and ot.type#(+) = 13
  and (o.type# in (3, 4)                                    
       or
       (o.type# = 2 
        and
        not exists (select null
                      from sys.tab$ t
                     where t.obj# = o.obj#
                       and (bitand(t.property, 512) = 512 or
                            bitand(t.property, 8192) = 8192))))

This query is taken from the USER_TAB_COLUMNS definition and it can change over different releases (10gR2 on my case). On this query I've cut the references to information not requested by you.

Anyway, why do you want to check this?

FerranB