简体   繁体   中英

Where clause is slowing my query from 2 seconds to 24 seconds

I am trying to write a simple query to count the results from a big table.

SELECT COUNT(*)
FROM DM.DM_CUSTOMER_SEG_BRIDGE_CORP_DW AL3
WHERE (AL3.REFERENCE_YEAR(+)   =2012)

Above query is taking around 24 seconds to return me output. If I remove where clause and execute same query, it is giving me result in 2 seconds.

May i know what is the reason for that. I am relatively new to SQL queries.

Please help

Thanks, Naveen

You might need an index on the table. Typically you will need an index on any columns used in the where clause

as for the (+) syntax I think it is redundant (i'm no Oracle expert) but see Difference between Oracle's plus (+) notation and ansi JOIN notation?

The reason may seem subtle. But there are multiple ways that Oracle could approach a query like this:

SELECT COUNT(*)
FROM DM.DM_CUSTOMER_SEG_BRIDGE_CORP_DW AL3

One way is to read all the rows in the table. Because this is a big table, that is not the most efficient approach. A second method would be to use statistics of some sort, where the number of rows are in the statistics. I don't think Oracle ever does this, but it is conceivable.

The final method is to read an index. Typically, an index would be much smaller than the table and it might already be in memory. The above query would be reading a much smaller amount of data. ( Here is an interesting article on counting all the rows in a table.)

When you introduce the where clause,

WHERE (AL3.REFERENCE_YEAR(+)   =2012)

Oracle can no longer scan just any index. It would have to scan the reference_year index. What is the problem? If it scanned an index, it would still need to fetch the data records to get the value of reference_year -- and that is equivalent (actually worse) than scanning the whole table.

Even with an index on reference_year , you are not guaranteed to use the index. The problem is something called selectivity . The number of rows that you are fetching may still be quite large, relative to the number of rows in the database (in this context, 10% is "quite large"). The Oracle optimize may choose to do a full table scan rather than read the index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM