Where clause causing a query to slow down in a cursor

I have a table "the_table" with about 10,000 rows and four columns (id, description, inventory, and category).
This query returns all rows immediately:
    select id
         , description
         , inventory
    from the_table
    where category =  nvl(null, category);
However, when it is put into a cursor, like this:
(p_user_category is a user-defined variable which can be null if the user wants all of the rows)
    c_results  sys_refcursor;
    open c_results for
        select id
             , description
             , inventory
        from the_table
        where category =  nvl(p_user_category, category);
    fetch c_results into v_id, v_description, v_inventory;
    close c_results;
then it takes five minutes to return even just one row when p_user_category is null.
However, if I change the where clause to:
    where (p_user_category is null or category = p_user_category)
then it returns all rows immediately.
It started being a problem right around the time of the most recent update - I am running 11.2.0.2.0 (64-bit production).

The optimizer is smart enough to recognise that null is null, so "nvl(null,category)" collapses to "category", and your predicate "category = nvl(null, category)" is transformed to "category is not null" (if it's allowed to be null) or simply disappears - so the SQL test is not the same as the PL/SQL run.
In PL/SQL your manual rewrite is not logicall the same as the original unless you have declared category to be non-null because your first disjunct will allow rows with a null category to be reported, while the original query would lose them.
Check the execution plans for the SQL and the PL/SQL versions.
Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
Now on Twitter: @jloracle

Similar Messages

  • How do you use 3 Where Clauses in a query

    Hi, i am trying to figure out how to use 3 Where Clauses in a Query where 2 of the Where Clauses uses a Sub query.
    Display the OrderID of all orders that where placed after all orders placed by “Bottom-Dollar Markets”.
    Order the result by OrderID in ascending order.
    First WHERE clause checks for OrderDate and uses a sub query with ALL keyword.
    Second WHERE clause use equals and sub query.
    Third WHERE clause uses equal and company name.
    This is what i have so far but i am pretty confused on how to do this.
    My Code for NorthWind:
    Select OrderID
    From Orders o
    Where o.OrderID IN (Select OrderDate From Orders Where Orders.OrderID > ALL
    (Select CompanyName From Customers Where CompanyName = 'Bottom-Dollar Markets'));
    The book shows how to use the ALL Keyword but not in a Sub query with Multiple Where Clauses.
    Select VenderName, InvoiceNumber, InvoiceTotal
    FROM Invoices JOIN Vendors ON Invoices.VendorID = Vendors.VendorID
    WHERE InvoiceTotal > ALL (Select InvoiceTotal From Invoices Where VendorID = 34)
    ORDER BY VendorName;

    >Where Orders.OrderDate
    > ALL  (Select
    CompanyName
    The comparison operator (>) requires compatible data types.
    DATETIME is not compatible with VARCHAR string for comparison.
    Here is your homework:
    SELECT orderid
    FROM orders o
    WHERE o.orderdate > ALL (SELECT orderdate
    FROM orders
    WHERE shipvia = (SELECT Max(shipvia)
    FROM orders o
    INNER JOIN customers c
    ON c.customerid =
    o.customerid
    WHERE
    c.companyname = 'Bottom-Dollar Markets'));
    11064
    11065
    11066
    11067
    11068
    11069
    11070
    11071
    11072
    11073
    11074
    11075
    11076
    11077
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • I am having issues related to storage and I believe this is causing my computer to slow down. "Other" files part is the major occupier(180 GB). I have done Omni disk and multiple other cleaning(iTunes-device, restart, etc), yet have not been able to empty

    I am having issues related to storage and I believe this is causing my computer to slow down. "Other" files part is the major occupier(180 GB). I have done Omni disk and multiple other cleaning(iTunes-device, restart, etc), yet have not been able to empty any more space, nor to speed up my computer? Any suggestions? All your contributions are welcomed. Thanks. Mehmet Mazhar Celikoyar

    Below is the result:
    Hardware Information:
              MacBook Pro (15-inch, Mid 2009)
              MacBook Pro - model: MacBookPro5,3
              1 3.06 GHz Intel Core 2 Duo CPU: 2 cores
              4 GB RAM
    Video Information:
              NVIDIA GeForce 9400M - VRAM: 256 MB
              NVIDIA GeForce 9600M GT - VRAM: 512 MB
    Audio Plug-ins:
              BluetoothAudioPlugIn: Version: 1.0
              AirPlay: Version: 1.9
              AppleAVBAudio: Version: 2.0.0
              iSightAudio: Version: 7.7.3
    Startup Items:
              HP IO - Path: /Library/StartupItems/HP IO
    System Software:
              OS X 10.9 (13A603) - Uptime: 3 days 22:8:6
    Disk Information:
              ST9500420ASG disk0 : (500.11 GB)
                        EFI (disk0s1) <not mounted>: 209.7 MB
                        Macintosh HD (disk0s2) /: 499.25 GB (220.49 GB free)
                        Recovery HD (disk0s3) <not mounted>: 650 MB
              HL-DT-ST DVDRW  GS23N 
    USB Information:
              Apple Inc. Built-in iSight
              Apple Internal Memory Card Reader
              Apple Inc. Apple Internal Keyboard / Trackpad
              Apple Computer, Inc. IR Receiver
              Apple Inc. BRCM2046 Hub
                        Apple Inc. Bluetooth USB Host Controller
    FireWire Information:
    Thunderbolt Information:
    Kernel Extensions:
              com.rim.driver.BlackBerryUSBDriverInt          (0.0.64)
              com.livedrive.filesystems.livedrivefs          (2.1.14)
    Problem System Launch Daemons:
    Problem System Launch Agents:
    Launch Daemons:
              [loaded] com.adobe.fpsaud.plist
              [loaded] com.adobe.versioncueCS4.plist
              [loaded] com.creativebe.MainMenuHelper.plist
              [loaded] com.macpaw.CleanMyMac2.Agent.plist
              [loaded] com.magican.castle.plist
              [loaded] com.microsoft.office.licensing.helper.plist
              [loaded] com.rim.BBDaemon.plist
              [failed] com.zeobit.MacKeeper.plugin.AntiTheft.daemon.plist
    Launch Agents:
              [loaded] com.adobe.CS4ServiceManager.plist
              [loaded] com.hp.messagecenter.launcher.plist
              [loaded] com.hp.productresearch.plist
              [loaded] com.rim.BBLaunchAgent.plist
    User Launch Agents:
              [loaded] com.adobe.ARM.[...].plist
              [failed] com.macpaw.CleanMyMac2Helper.diskSpaceWatcher.plist
              [failed] com.macpaw.CleanMyMac2Helper.scheduledScan.plist
              [failed] com.macpaw.CleanMyMac2Helper.trashWatcher.plist
              [failed] com.UninstallerTool.plist
              [failed] com.VolumeWatcherTool.plist
              [failed] com.zeobit.MacKeeper.Helper.plist
    User Login Items:
              BlackBerry Device Manager
              HP Scheduler
    3rd Party Preference Panes:
              Adobe Version Cue CS4
              DC30 Xact Driver Panel
              Flash Player
              Flip4Mac WMV
              Perian
    Internet Plug-ins:
              AdobePDFViewer.plugin
              AdobePDFViewerNPAPI.plugin
              Default Browser.plugin
              Flash Player.plugin
              FlashPlayer-10.6.plugin
              Flip4Mac WMV Plugin.plugin
              iPhotoPhotocast.plugin
              JavaAppletPlugin.plugin
              OfficeLiveBrowserPlugin.plugin
              QuickTime Plugin.plugin
              SharePointBrowserPlugin.plugin
              Silverlight.plugin
    User Internet Plug-ins:
              OctoshapeWeb.plugin
    Bad Fonts:
              None
    Time Machine:
              Mobile backups: OFF
              Auto backup: NO
              Volumes being backed up:
                        Macintosh HD: Disk size: 499.25 GB Disk used: 278.75 GB
              Destinations:
                        TOSHIBA EXT [Local] (Last used)
                        Total size: 2 TB
                        Total number of backups: 5
                        Oldest backup: 2013-10-24 23:21:31 +0000
                        Last backup: 2013-10-25 02:59:08 +0000
                        Size of backup disk: Excellent
                                  Backup size 2 TB > (Disk size 499.25 GB X 3)
    Top Processes by CPU:
                   3%          WindowServer
                   1%          EtreCheck
                   1%          Microsoft PowerPoint
                   0%          BBLaunchAgent
                   0%          fontd
                   0%          aosnotifyd
    Top Processes by Memory:
              168 MB             Microsoft PowerPoint
              123 MB             Safari
              86 MB              Mail
              74 MB              WindowServer
              45 MB              com.apple.WebKit.Networking
              45 MB              com.apple.WebKit.WebContent
              41 MB              Finder
              41 MB              PluginProcess
              41 MB              mds_stores
              33 MB              Notes
    Virtual Memory Statistics:
              72 MB              Free RAM
              1.27 GB            Active RAM
              1.24 GB            Inactive RAM
              667 MB             Wired RAM
              2.58 GB            Page-ins
              111 MB             Page-outs

  • Regarding  dynamically assigning the where clause to select query

    hi,
      Please send the code regarding how to dynamically assign the where clause to select query.
    thanks in advance

    SELECT <fileds>
            INTO TABLE itab
            FROM dbase
            WHERE  condition.

  • How to change where clause in VO query in bean

    Hi experts
    I have to modify vo object query where clause on run time .. is it possible??
    if yes please suggest me,

    as mentioned by Timo, it is very much possible
    see this following link -
    Changing the WHERE clause or VO Query at runtime in Oracle ADF | Techartifact
    Dynamically changing query in view object in Oracle ADF | Techartifact

  • After upgrading from Snow Leopard to Mountain Lion, the text preference, Middle Eastern, causes Photoshop CS6 to slow down.  Can this be fixed?

    After upgrading from Snow Leopard to Mountain Lion, and setting the text preference, Middle Eastern, causes Photoshop CS6 to slow down.  Can this be fixed?

    I'm Win, not Mac, but I do have a couple saved messages
    Mac 10.8.3 Bug w/Encore and BluRay http://forums.adobe.com/thread/1198709
    -create folder not ISO http://forums.adobe.com/thread/1216127

  • Hello, I'm pretty sure my fan on my 2009 mac book pro has stopped running. Would this cause the computer to slow down and take for ever to boot up and show the color wheel every time I select an application ?

    Hello, I'm pretty sure my fan on my 2009 mac book pro has stopped running. Would this cause the computer to slow down and take for ever to boot up and show the color wheel every time I select an application ? how involved to replace fan ? cost ?
    thanks

    Not directly, but if the CPU overheats because of incompatible software, that would cause slowdowns. Do not allow the computer to run if the fan is not working unless you wish to fry your motherboard. Please make a Genius Appointment and take it in for service.

  • Query Designer slows down after working some time with it

    Hi all,
    the new BEx Query Designer slows down when working some time with it. The longer it remains open, the slower it gets. Especially formula editing slows down extremely.
    Did anyone of you encounter the same problem? Do you have an idea, how to fix this. To me it seems as if the Designer allocates more and more RAM and does not free that up.
    My version: BI AddOn 7.X, Support Package 13, Revision 467
    Kind regards,
    Philipp

    I have seen a similar problem on one of my devices, the 'Samsung A-920'. Every time the system would pop up the 'Will you allow Network Access' screen , the imput from all keypresses from then on would be strangely delayed. It looked like the problem was connected with the switching from my app and the system dialog form. I tried for many many long hours / days to fix this, but just ended up hacking my phone to remove the security questions. After removing the security questions my problem went away.
    I don't know if it's an option in your application, but is it possible to do everything using just one Canvas, and not switch between displayables? You may want to do an experiment using a single displayable Canvas, and just change how it draws. I know this will make user input much more complicated, but you may be able to avoid the input delays.
    In my case, I think the device wasn't properly releasing / un-registering the input handling from the previous dialogs, so all keypresses still went through the non-current network-security dialog before reaching my app.

  • VPD - How to make the where clause a correlated query

    Hi,
    My VPD function has the following where clause:
    where_clause:= ' project_id in (select object_id from pa_project_classes p'||
    ' where p.class_category='||''''||l_cat||''''||
    ' and p.CLASS_CODE='||''''||l_class||''''||
    ' and p.OBJECT_TYPE=''PA_PROJECTS'''||
    The problem is that the subquery is not using the unique key defined on the table pa_project_classes. What I need is something as follows:
    where_clause:= ' project_id in (select object_id from pa_project_classes p'||
    ' where p.class_category='||''''||l_cat||''''||
    ' and p.CLASS_CODE='||''''||l_class||''''||
    ' and p.OBJECT_TYPE=''PA_PROJECTS'''||
    ' and p.object_id=mainquery.project_id ||
    The problem is that since the table pa_project_classes also has a column project_id, I have to prefix the column name by the alias of the main query like 'mainquery.project_id'. However this seems impossible as main query is not unknown .
    I would be grateful if you could suggest any workaround or solution.
    Thanks

    Just have a look over these two statements if it solves your problem
    one time where clause
    Set_Block_Property('BLOCK_NAME',ONETIME_WHERE,your form item);
    dynamic where clause
    set_block_property('BLOCK_NAME'default_where, your form itme)
    you can where clause at run time from any procedure or some triggers

  • How to use string operation in where clause of select query

    Hello All,
    I just want to know how can i write a restriction in select query saying retrive data only begins with name "DE*".
    Explaination: If my table has records and names starts with character then i want to write a query to fetch all the records in which names starts with DE*.
    Thanks in advance for your quick reply...
    Dev.

    Hi
    In the where clause you need to write like
    WHERE NAME LIKE 'DE%'
    Regards
    Sudheer

  • Dynamic where clause in my query

    I am using a view
    select * from vw_pt_inv_customer
    My requirement is have a web page where users can search for customers by filling in a form which has the following feilds: - User can fill in the form with all the feilds or not. I want a dynamic where clause.. how can i get this work for me?
    Title
    Firstname
    Surname
    Address1
    Address2
    Postcode
    Telephone No

    879796 wrote:
    I am using a view
    select * from vw_pt_inv_customer
    My requirement is have a web page What web frame work is used? Apex? Something else?
    where users can search for customers by filling in a form which has the following feilds: - User can fill in the form with all the feilds or not. I want a dynamic where clause.. how can i get this work for me?Dynamic where clauses are a Very Bad Idea (tm).
    And having an open ended search function on a web page is also not a great idea.
    If you are using Apex, the for performance (and even query flexibility) it will be better creating a separate reporting region for each unique query. A boolean rendering condition checks the existing bind variables in order to determine if that specific reporting region should be executed.
    This results in a reporting region having a proper and dedicated SQL query (no hacking of the where clause) and that region only being rendered for the proper combination of supplied filter criteria.
    A slightly more complex, but more flexible approach, is using a generic reporting region that calls a PL/SQL function that creates returns the SQL query for execution and rendering. The approach to this is very similar to constructing a SQL ref cursor (dynamically) for a client. The only difference is that instead of creating the actual ref cursor, the code simply needs to return the SQL source code statement - with bind variables. The Apex run-time does the rest (does the binds and execution and rendering).
    If you are not using Apex - you should still consider these approaches. And not hacking a single SQL to cater for all different types of filter conditions.

  • Dynamic where clause in select query

    Hi
    I'm trying for a dynamic query and in the dynamic where clause i'm checking a field for constant.....for instance if i wanna to use WERKS EQ '0478' how to declare it in dync where clause. i tried for the following:
    SELECT  (TAB_FIELD) INTO TABLE DITAB UP TO 10 ROWS FROM (TAB_NAME) WHERE (CONDI).
    heree CONDI = 'werks eq 0287'   . in this case the query fails as the werks shud be equal to '0287' and not just 0287. How to handle this? i tried for the following
    CONDI = 'werks eq " '0287' " ' but no luck as it is not a valid stmt as i knew.

    hi prabhu,
    this is how u select dynamically...
    DATA: COND(72) TYPE C,
    ITAB LIKE TABLE OF COND.
    PARAMETERS: CITY1(10) TYPE C, CITY2(10) TYPE C.
    DATA WA TYPE SPFLI-CITYFROM.
    CONCATENATE 'CITYFROM = ''' CITY1 '''' INTO COND.
    APPEND COND TO ITAB.
    CONCATENATE 'OR CITYFROM = ''' CITY2 '''' INTO COND.
    APPEND COND TO ITAB.
    CONCATENATE 'OR CITYFROM = ''' 'BERLIN' '''' INTO COND.
    APPEND COND TO ITAB.
    LOOP AT ITAB INTO COND.
    WRITE COND.
    ENDLOOP.
    SKIP.
    SELECT CITYFROM
    INTO WA
    FROM SPFLI
    WHERE (ITAB).
    WRITE / WA.
    ENDSELECT.
    regards,
    sohi

  • How to dynamically add field name in where clause of select query in web dynpro?

    Hello,
    Can any body tell me how i can use select query with dynamic wheere condition.
    i have a requirement like there are multiple input fields  and i want to select data from two database
    and condition may vary .

    Hi
    In the where clause you need to write like
    WHERE NAME LIKE 'DE%'
    Regards
    Sudheer

  • Performance hit using "where" clause in the query

    Hi All,
    I am facing a huge performance hit in the java code when using "where" clause in queries. Following are the details:
    1. SELECT * FROM Employee
    2. SELECT * FROM Employee where employeeid in (26,200,330,571,618,945)
    There is no difference in Query Execution Time for both queries.
    Business Logic Time is huge in second case as compared to first one (ratio - 1:20).
    Rows returned are more in first case as compared to second case.(ratio - 1:4)
    Business Logic is same for both the cases where I iterate through the ResultSet, get the objects and set them in a data structure.
    Does anybody know the reason of unexpected time difference for the business logic in the second case?

    Since you're mentioning clustering your index, I'll assume you are using Oracle. Knowing what database you are using makes it a lot easier to suggest things.
    Since you are using Oracle, you can get the database to tell you what execution plan it is using for each of the 2 SQL statements, and figure out why they have similar times (if they do).
    First, you need to be able to run SQL*Plus; that comes as part of a standard database installation and as part of the Oracle client installation - getting it set up and running is outside the scope of this forum.
    Second, you may need your DBA to enable autotracing, if it's not already:
    http://asktom.oracle.com/~tkyte/article1/autotrace.html
    http://www.samoratech.com/tips/swenableautotrace.htm
    Once it's all set up, you can log in to your database using sql*plus, issue "SET AUTOTRACE ON", issue queries and get execution plan information back.
    For example:
    SQL> set autotrace on
    SQL> select count(*) from it.ticket where ticket_number between 10 and 20;
      COUNT(*)
            11
    Execution Plan
    Plan hash value: 2983758974
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            |     1 |     4 |     1   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE   |            |     1 |     4 |            |          |
    |*  2 |   INDEX RANGE SCAN| TICKET_N10 |    12 |    48 |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("TICKET_NUMBER">=10 AND "TICKET_NUMBER"<=20)
    Statistics
              0  recursive calls
              0  db block gets
              1  consistent gets
              0  physical reads
              0  redo size
            515  bytes sent via SQL*Net to client
            469  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processed
    SQL> This tells me that this query used an INDEX RANGE SCAN on index TICKET_N1; the query can't do much better than that logically... In fact, the statistic "1 consistent gets" tells me that Oracle had to examine only one data block to get the answer, also can't do better than that. the statistic, "0 physical reads" tells me that the 1 data block used was already cached in Oracle's memory.
    the above is from Oracle 10g; autotrace is available back to at least 8i, but they've been adding information to the output with each release.
    If you have questions about sql_plus, check the forums at asktom.oracle.com or http://forums.oracle.com/forums/category.jspa?categoryID=18
    since sql*plus is not a JDBC thing...
    Oh, and sql*plus can also give you easier access to timing information, with "set timing on".

  • ADF dynamic where clause for VO query using BC

    I'm hoping someone can help me out. I have a read only view object that I want to filter results based on some user choices. For example the user may want to see all results or they may only want to see a much smaller subset. This is for an error dashboard, the smaller subset maybe by application or maybe by application and by error severity. I think I can use a dynamic where clause but I'm not sure, Can someone get me started down the right path, or post an example that I can see.

    Hi user,
    You can use a dynamic where clause for this, but maybe there is a more practical option. Maybe you can have a fixed where clause, but using a bind parameter, like:
    vo.application like :applicationParam. This makes an executeWithParams method available that you can call from your page, and use in the bindings. This parameter you can populate with the results of for example a poplist, with a default value of '%'.
    When you do want to use a dynamic where clause, you will need to add a method to the java code of your application module, and make this method available for the client. In this method, you can use findViewObject to retrieve your VO, use VO.setWhereClause to set the whereclause to what you want, and then call VO.executeQuery. This method can then again be called from the page.
    Success,
    Jeroen van Veldhuizen

Maybe you are looking for

  • Invalid security code?

    I have bought about 12 games off the app store, but now it asks me to sign in my billing info, the only thing that was giving me problems was the security code, it constantly tells me "Invalid security code" and it's the right one, I know where it is

  • TS1474 Two separate accounts on one computer

    How do you sync 2 seperate I pads from 2 accouonts to one computer without getting them mixed up?

  • Adobe Photoshop 3.2

    Hi, I am having the same problem as other people on here about getting pictures out of the Adobe 3.2 after the sunscription ran out. Of course I can't register and unlock it because it is no longer supported. I tried this a couple of years ago and te

  • QuickTime in OS 9 Classic environment

    I have bought a commercial CD that contains words and still pictures which was made to run on pre-OS X software. Is it possible to download an earlier version of QuickTime so that I can view this CD in the Classic environment? I wouldn't want to do a

  • ED on Trading Material

    Hi All Plz help me with the following scenario The company i am working for has several Businesslines like Mfg.Porjects,Trading too. Now My concern is as company is liable to pay ED on MFG products from let us say Plant 101 & through same plant it tr