Bad execution plans when using parameters, subquery and partition by

We have an issue with the following...
We have this table:
CREATE TABLE dbo.Test (
Dt date NOT NULL,
Nm int NOT NULL,
CONSTRAINT PK_Test PRIMARY KEY CLUSTERED (Dt)
This table can have data but it will not matter for this topic.
Consider this query (thanks Tom Phillips for simplifying my question):
declare @date as date = '2013-01-01'
select *
from (
select Dt,
row_number() over (partition by Dt order by Nm desc) a
from Test
where Dt = @date
) x
go
This query generates an execution plan with a clustered seek.
Our queries however needs the parameter outside of the sub-query:
declare @date as date = '2013-01-01'
select *
from (
select Dt,
row_number() over (partition by Dt order by Nm desc) a
from Test
) x
where Dt = @date
go
The query plan now does a scan followed by a filter on the date.
This is extremely inefficient.
This query plan is the same if you change the subquery into a CTE or a view (which is what we use).
We have this kind of setup all over the place and the only way to generate a good plan is if we use dynamic sql to select data from our views.
Is there any kind of solution for this?
We have tested this (with the same result) on SQL 2008R2, 2012 SP1, 2014 CU1.
Any help is appreciated.

Hi Tom,
Parameter sniffing is a different problem. A query plan is made based on the value which may be really off in the data distribution. We do have this problem as well e.g. when searching for today's data when the statistics think the table only has yesterday's
data (a problem we have a lot involves the lack of sufficient amount of buckets in statistics objects).
This problem is different.
- It doesn't matter what the parameter value is.
- You can reproduce this example with a fresh table. I.e. without statistics.
- No matter what the distribution of data (or even if the statistics are correct), there is absolutely no case possible (in my example) where doing a scan followed by a filter should have better results than doing a seek.
- You can't change the behavior with hints like "option(recompile)" or "optimize for".
This problem has to do with the specific combination of "partition by" and the filter being done outside of the immediate query. Try it out, play with the code, e.g. move the where clause inside the subquery. You'll see what I mean.
Thanks for responding.
Michel

Similar Messages

  • Unable to get the execution plan when using dbms_sqltune (11gR2)

    Hi,
    Database version: 11gR2
    I have a user A that is granted privileges to execute dbms_sqltune.
    I can create a task, excute it and run the report.
    But, when I run the report I get the following error:
    SQL> show user
    USER is "A"
    SQL> set long 10000 longchunksize 10000 linesize 200 pagesize 000
    select dbms_sqltune.report_tuning_task(task_name => 'MYTEST') from dual;SQL>
    GENERAL INFORMATION SECTION
    Tuning Task Name : MYTEST
    Tuning Task Owner : A
    Workload Type : Single SQL Statement
    Scope : COMPREHENSIVE
    Time Limit(seconds): 1800
    Completion Status : COMPLETED
    Started at : 05/15/2013 11:53:22
    Completed at : 05/15/2013 11:53:23
    Schema Name: SYSMAN
    SQL ID : gjm43un5cy843
    SQL Text : SELECT SUM(USED), SUM(TOTAL) FROM (SELECT /*+ ORDERED */
    SUM(D.BYTES)/(1024*1024)-MAX(S.BYTES) USED,
    SUM(D.BYTES)/(1024*1024) TOTAL FROM (SELECT TABLESPACE_NAME,
    SUM(BYTES)/(1024*1024) BYTES FROM (SELECT /*+ ORDERED USE_NL(obj
    tab) */ DISTINCT TS.NAME FROM SYS.OBJ$ OBJ, SYS.TAB$ TAB,
    SYS.TS$ TS WHERE OBJ.OWNER# = USERENV('SCHEMAID') AND OBJ.OBJ# =
    TAB.OBJ# AND TAB.TS# = TS.TS# AND BITAND(TAB.PROPERTY,1) = 0 AND
    BITAND(TAB.PROPERTY,4194400) = 0) TN, DBA_FREE_SPACE SP WHERE
    SP.TABLESPACE_NAME = TN.NAME GROUP BY SP.TABLESPACE_NAME) S,
    DBA_DATA_FILES D WHERE D.TABLESPACE_NAME = S.TABLESPACE_NAME
    GROUP BY D.TABLESPACE_NAME)
    ERRORS SECTION
    - ORA-00942: table or view does not exist
    SQL>
    It seems there a missing privileg for dislaying the execution plan.
    As a workaround, this is solved by granting select any dictionay (which I don't want) to the user A.
    Does someone have an idea about what privilege is missing?
    Kind Regards.

    Hi,
    SELECT ANY DICTIONARY system privilege provides access to SYS schema objects only => which you are using as workaround
    SELECT_CATALOG_ROLE provides access to all SYS views only.==> Safe option
    SQL> grant SELECT ANY DICTIONARY to test;
    Grant succeeded.
    SQL> conn test/test
    Connected.
    SQL> select count(*) from  sys.obj$;
      COUNT(*)
         13284
    SQL> conn /as sysdba
    Connected.
    SQL> revoke SELECT ANY DICTIONARY from test;
    Revoke succeeded.
    SQL> grant SELECT_CATALOG_ROLE to test;
    Grant succeeded.
    SQL> conn test/test
    Connected.
    SQL> select count(*) from  sys.obj$;
    select count(*) from  sys.obj$
    ERROR at line 1:
    ORA-00942: table or view does not existHTH

  • What execution plan was used?

    Hi there
    How can I find out what execution plan was used for an SQL when it was executed as part of the batch-process at night? 10gR2 on ASM, RHEL 5.8 64bit.
    Best regards

    Are you using the enterprise edition?  Are you licensed to use the AWR?  If so, assuming that the query ran long enough to be captured in an AWR snapshot (which seems likely if you're asking this question), DBA_HIST_SQL_PLAN will have the plan information and DBA_HIST_SQLSTAT will tell you the plan_hash_value (or values) that were used for a particular SQL_ID in a particular SNAP_ID.  DBA_HIST_SNAPSHOT will tell you what SNAP_ID (or set of snap_id's) corresponds to whatever time period you are interested in.
    Justin

  • My iphone 5 has bad audio qualities when using the telephone properties: what solution was offered by apple or provider?

    I have a new iphone 5 that has a very bad audio quality when using the basic telephone function. Both wen called or calling the conversation is either of quite poor quality or drops awau alltogether. The latter happens sometimes 5 times on a row during one conversation or better attempt to have one..:)
    Who has similar problems and what has been the solution offered by apple or their provider?

    I have the same issue with the following setup:
    Garmin 2597LMT
    iPhone 5
    Motorola T605 bluetooth hardsfree system
    I ended up disabling the nuvi bluetooth -- I don't subscribe to any smartlink services -- so I'll guess i'll go without Weather on the nuvi for now.

  • My MacBook Pro is running very slow when using the internet and sometimes gives the pinwheel of death, any suggestions on how to fix?

    My MacBook Pro is running very slow when using the internet and sometimes gives the pinwheel of death, any suggestions on how to fix?

    <http://www.thexlab.com/faqs/sbbod.html>

  • After I installed the recent Apple security patch, I can no longer save PDFs when using Safari. And Firefox no longer can open website PDFs. Any suggestions?

    After I installed the recent Apple security patch, I can no longer save PDFs when using Safari. And Firefox no longer can open website PDFs. Any suggestions?

    Dansyacht wrote:
    If the previous Safari suggestion doesn't work try the following:
    In Finder, go to Macintosh HD/Library/Internet Plug-ins and move AdobePDFViewerNPAPI.plugin to the Disabled Plug-ins Folder.  Restart Safari.  If this works you may just want to delete that FUBAR plug-in.
    Thanks.  This was the solution for me.
    Message was edited by: tvdowntown

  • In Firefox 3.6.10 I was able to go forward and backwards between pages without the page defaulting to the top of the page. Is there any way to prevent the page from automatically moving to the top when using the forwards and back buttons in Firefox Four?

    I like to be able to navigate backwards and forwards without having to scroll down and find where I was previously. In Firefox Four, when using the forwards and back buttons, the page will automatically return to the top of the page. Is there any way to change this setting in Firefox Four to prevent it from doing that?

    Thanks for the response. No Time Machine, but I probably have a backup from a few months ago on an external hard drive. :/ I guess it'd have useful history, but not if it overwrote the last 3 months or so of Awesome Bar, that might not be so great.

  • Performance issues when using Smart View and Excel 2010

    Hello, we are experiencing very slow retrieval times when using Smart View and Excel 2010. Currently on v.11.1.3.00 and moved over from Excel 2003 in the last quarter. The same spreadsheets in 2010 (recreated) are running much slower than they used to in 2003 and I was wondering if anyone else out there has experienced similar problems?
    It looks like there is some background caching going on as when you copy and paste the contents into a new file and retrieve it is better.....initially. The size of the files are generally less than 2mb and there aren't an expecially large number of subcubes requested so I am at a loss to explain or alleviate the issues.
    Any advice / tips on how to optimise the performance would be greatly appreciated.
    Thanks,
    Nick

    Hi Nick,
    Office 2010 (32 bit) only is supported.
    Also check these documents:
    Refresh in Smart View 11.1.2.1 is Slow with MS Office 2010. (Doc ID 1362557.1)
    Smart View Refresh Returns Zeros (Doc ID 758892.1)
    Internet Explorer (IE7, IE8 and IE9) Recommended Settings for Oracle Hyperion Products (Doc ID 820892.1)
    Thank you,
    Charles Babu J
    Edited by: CJX on Nov 15, 2011 12:21 PM

  • Panel contents overlap when using borderSkin style and layout=absolute

    This problem has been reported on several occasions
    (http://bugs.adobe.com/jira/browse/SDK-14806)
    and there are several articles that talk about this:
    http://dougmccune.com/blog/2008/01/17/followup-about-flex-panel-bug/
    http://dougmccune.com/blog/2008/01/12/calling-********-on-a-resolved-flex-bug/
    I´m not an expert but think I found a fix/workaround for this.
    frameworks\projects\framework\src\mx\containers\Panel.as
    Must to be changed in the viewMetrics() method.
    Line:
    973- if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) 974- {
    Replace by:
    if ((FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) || (getQualifiedClassName(border) != "mx.skins.halo::PanelSkin") || (getStyle("borderStyle") != "default") ) {

    Hi Andres,<br /><br />I haven't tried to verify your fix, but would you be willing to fill out a contributor agreement and submit an official patch?<br /><br />Matt<br /><br /><br />On 4/25/08 12:34 PM, "Andres Serral" <[email protected]> wrote:<br /><br />A new discussion was started by Andres Serral in<br /><br />Developers --<br />  Panel contents overlap when using borderSkin style and layout=absolute<br /><br />This problem has been reported on several occasions<br />(http://bugs.adobe.com/jira/browse/SDK-14806)<br />and there are several articles that talk about this:<br />http://dougmccune.com/blog/2008/01/17/followup-about-flex-panel-bug/<br />http://dougmccune.com/blog/2008/01/12/calling-********-on-a-resolved-flex-bug/<br /><br />I´m not an expert but think I found a fix/workaround for this.<br /><br />frameworks\projects\framework\src\mx\containers\Panel.as<br />Must to be changed in the viewMetrics() method.<br /><br />Line:<br />973- if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) 974- {<br /><br />Replace by:<br />        if ((FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) || (getQualifiedClassName(border) != "mx.skins.halo::PanelSkin") || (getStyle("borderStyle") != "default") ) {<br /><br />________________________________<br />View/reply at Panel contents overlap when using borderSkin style and layout=absolute <a href=http://www.adobeforums.com/webx?13@@.59b51731><a href=http://www.adobeforums.com/webx?13@@.59b51731><br />Replies by email are OK.<br />Use the unsubscribe <a href=http://www.adobeforums.com/webx?280@@.59b51731!folder=.3c060fa3><a href=http://www.adobeforums.com/webx?280@@.59b51731!folder=.3c060fa3>  form to cancel your email subscription.

  • "Could not complete scan" error when using Windows Fax and Scan

    "Could not complete scan" error when using Windows Fax and Scan with a HP OfficeJet Pro 8600 Plus All-In-One network printer.
    Printing is fine.
    When using the HP Scan application, get the error "Scanner communication cannot be established".
    When scanning from the printer itself it fails with the same message. In addition the printer panel displays the error:
    "The scan could not be completed due to one or more of the following issues:
    Connection to the computer is lost
    The scanner is in use
    OCR application is not installed"
    My PC is a HP Compaq Pro 6300 SFF 64bit, with ethernet cable to the router and ethernet cable to the printer
    Originally ran Windows 8.0; recently upgraded to Windows 8.1.
    Older separate Netgear router and modem was replaced with a newer Netgear Router/Modem, but both experienced the same problem.
    There was no problem with the original Windows 8.0 configuration and only after upgrading to 8.1 did the problem emerge.
    On my home netowrk I have an HP ProBook 6550b running Windows 7 sp1 that uses wireless to get to the Router, and it has no problem with scanning.
    I have followed the recommendations of a number of articles relating to this issue (including: http://h10025.www1.hp.com/ewfrf/wc/document?cc=us&​lc=en&docname=c02915410&product=4323659#N94), but there has been no change in behaviour.
    The printer has a static IP address;
    Power settings have been adjusted to Never for Turn off Hard Disk; Sleep and Hybrid Sleep.
    Scanning has been tested with all firewalls and antivirus turned off and in Selective Startup.
    The printer has been plugged directly into the power socket.
    With all these settings the Windows 8.1 cannot scan while the Windows 7 laptop with wireless to the router has no problems.
    Appreciate any insights into this problem.
    I can only surmise that the problem is a compatibility problem between the 8600 Printer and Windows 8.1.
    Any ideas?
    regards,
    Motorbike

    You can determine if there is compatiblity between the printer and PC by checking the Windows 8.1 hardware compatibility list. I have done that and it is shown to be fully compatible.  If the driver you installed before was only the basic driver,it would explain the lack of scan and copy functionality.
    Download and install the Windows 8.1 full feature driver and software on the HP Compaq Pro 6300 SFF 64bit PC . 
    http://h10025.www1.hp.com/ewfrf/wc/softwareDownloa​dIndex?softwareitem=bi-108858-4&cc=us&dlc=en&lc=en​...
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • Where are my designs stored when using Adobe CC and can i access them if i cancel ?

    where are my designs stored when using Adobe CC and can i access them if i cancel ?

    This is answered in the CC FAQ: http://www.adobe.com/products/creativecloud/faq.html

  • HT204291 When using my iPad and playing videos, I only hear the sound. Why will it not show the video?

    When using my iPad and playing videos, I only hear the sound. Why will it not show the video?  My iPad 2 and iPhone 5 work no issues.

    Hi sheilafrommannford,
    Welcome to the Support Communities!
    The articles below may be able to help you with this issue.
    Click on the links to see more details and screenshots.
    Using AirPlay
    http://support.apple.com/kb/HT4437
    Troubleshooting AirPlay and AirPlay Mirroring
    http://support.apple.com/kb/TS4215
    Cheers,
    Judy

  • If i dont use the display when using the GPS and only listen to the voice instructions can that also makes the iphone overheat even if you dont use the display

    because when i use the gps app in my iphone 4s in the car my iphone gets overheat so
    if i dont use the display when using the GPS and only listen to the voice instructions can that also makes the iphone overheat even if you dont use the display
    will that help?

    When you use your GPS does your iPhone get hot enough to shutdown?  The reason I ask is that I have run my GPS app with the screen brightness set to near max connected to power for hours.  My iPhone got hot, but didn't shutdown.

  • Cannot download aperture when using trial version and all photo work will be lost if delete trial version

    App Store will not download aperture when using trial version and all 30 days of photo work will be lost if delete trial version to be able to purchase Aperture download version???  any ideas?    

    Your Aperture library is not deleted when you delete Aperture from the Applications folder. Neither are your settings BTW.
    Do make certain your library is backed up!

  • How can I force mount a dvd that isn't even seen by Disk Utility? I can see it on the Mac when using my Windows 7 partition via Boot Camp, but not in Lion, which is how I would rather be running.

    How can I force mount a dvd that isn't even seen by Disk Utility? I can see it on the Mac when using my Windows 7 partition via Boot Camp, but not in Lion, which is how I would rather be running.

    Well if there is a EFI block, then running a program in OS X isn't going to do a lick of good.
    After all EFI was designed for Trusted Computing and Digital Rights Management, to act between the OS and hardware, can read drives, contact the Internet and everything.
    Windows doesn't use EFI, will have UEFI in Windows 8 though.

Maybe you are looking for