Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server query performance

I have a stored procedure on a busy database which constantly come out top in the list of expensive queries (by some way). The query is very simple, it takes a single parameter (@ID, int) which is the primary key of the table, and selects the record that matches that ID. The primary key is an identity field with a clustered index, so I am stumped as to how to optimise this any further?

The query is as follows

CREATE PROCEDURE [dbo].[P_Call_Get]

    @ID int = null

AS

    select ID,
        AppID,
        AgentID,
        AgentLogin,
        Ext,
        VDN,
        VDNName,
        Skill,
        SkillName,
        CallFrom,
        TelNoFrom,
        ParentCallID,
        CallStart,
        ACWStart,
        CallEnd,
        Outcome,
        StageID,
        TxTo,
        TxSuccess,
        ServiceID,
        DiallerID,
        CRC,
        TSCallID,
        CallDirection,
        [Manual],
        CallBackAgent,
        CallBackDateTime,
        Notes
    from P_Call
    where (ID = @ID or @ID is null)

Not sure the best way to post the execution plan - all it shows is that 100% of the operation is taken up by the clustered index scan

like image 933
Macros Avatar asked Apr 15 '26 00:04

Macros


2 Answers

I think that by using where (ID = @ID or @ID is null) you are getting a sub optimal plan. Divide this into 2 separate queries so that in the case where @Id is not null it will just look it up directly and you will get a seek rather than a scan appear in the plan. You could maybe create a View with the columns you require to avoid the repetition (i.e. the Query without any where clause)

select ID,
    AppID,
    AgentID,
    AgentLogin,
    Ext,
    VDN,
    VDNName,
    Skill,
    SkillName,
    CallFrom,
    TelNoFrom,
    ParentCallID,
    CallStart,
    ACWStart,
    CallEnd,
    Outcome,
    StageID,
    TxTo,
    TxSuccess,
    ServiceID,
    DiallerID,
    CRC,
    TSCallID,
    CallDirection,
    [Manual],
    CallBackAgent,
    CallBackDateTime,
    Notes
from P_Call
like image 183
Martin Smith Avatar answered Apr 16 '26 22:04

Martin Smith


Try cleaning out procedure cache and memory buffers:

DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE

Doing so before testing your procedure's performance will prevent the use of cached execution plans and previous results cache.

like image 37
HTTP 410 Avatar answered Apr 17 '26 00:04

HTTP 410



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!