How can I get rid of this Lazy Spool, or otherwise improve this query's performance?When converting a table valued function to inline, why do I get a lazy spool?How to improve this queries performance by indexing properly?How to get rid of clustered index scan?How can I improve this update?varchar and nvarchar in tuning a stored procedure - how to improve performance in this scenario?Investigating errors from strange queryImplicit conversion causing error part of the timewhy is this left join faster than an inner join?How can I get rid of an unhelpful parallel branch when unpivoting a single row?Why does this derived table improve performance?

Vacuum collapse -- why do strong metals implode but glass doesn't?

In xXx, is Xander Cage's 10th vehicle a specific reference to another franchise?

E: Sub-process /usr/bin/dpkg returned an error code (1) - but how do I find the meaningful error messages in APT's output?

Starships without computers?

Have only girls been born for a long time in this village?

How could Tony Stark wield the Infinity Nano Gauntlet - at all?

Unity: transform.LookAt(target) not "looking at" target?

Count the frequency of items in an array

Moons that can't see each other

90s(?) book series about two people transported to a parallel medieval world, she joins city watch, he becomes wizard

Why don't politicians push for fossil fuel reduction by pointing out their scarcity?

Is a butterfly one or two animals?

How to think about joining a company whose business I do not understand?

IV curve on this solar panel datasheet

What happened after the end of the Truman Show?

Convert HTML color to OLE

Is it allowable to use an organization's name to publish a paper in a conference, even after I graduate from it?

How could China have extradited people for political reason under the extradition law it wanted to pass in Hong Kong?

!I!n!s!e!r!t! !n!b!e!t!w!e!e!n!

Why don't sharp and flat root note chords seem to be present in much guitar music?

Can I submit a paper under an alias so as to avoid trouble in my country?

Don't teach Dhamma to those who can't appreciate it or aren't interested

Can a Beast Master ranger choose a swarm as an animal companion?

Are there any OR challenges that are similar to kaggle's competitions?



How can I get rid of this Lazy Spool, or otherwise improve this query's performance?


When converting a table valued function to inline, why do I get a lazy spool?How to improve this queries performance by indexing properly?How to get rid of clustered index scan?How can I improve this update?varchar and nvarchar in tuning a stored procedure - how to improve performance in this scenario?Investigating errors from strange queryImplicit conversion causing error part of the timewhy is this left join faster than an inner join?How can I get rid of an unhelpful parallel branch when unpivoting a single row?Why does this derived table improve performance?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















Here is the plan: https://www.brentozar.com/pastetheplan/?id=rkM8d7ONS



I am mostly interested in how to get rid of the lazy spool?



This is the query:



SELECT DISTINCT 
SM.Security_ID 'Security_ID',
Leg.Leg_Type 'Leg_Type',
Leg.Leg_Side 'Leg_Side',
Ct.Security_Type AS 'Swap_Type',
Leg.CDX_Indicator AS 'CDS_CDX_Flag',
SM.Currency AS 'Notional_Currency',
Ct.Cross_Currency_Flag AS 'Cross_Currency_Flag',
Ct.Custom_Overrides AS 'Special_Instructions',
Leg.Protection_Indicator AS 'Buy_Sell_Protection',
Leg.Commission_Direction AS 'Commission_Direction',
Leg.Dividend_Payment_Indicator AS 'Undl_Asset_Dividend_Flag',
SM.Issue_Date AS 'Effective_Date',
SM.Maturity_Date AS 'Maturity_Date',
Leg.Settlement_Frequency 'Settlement_Frequency',
Leg.Reset_Frequency 'Reset_Frequency',
Leg.Roll_Day AS 'Roll_Day',
Leg.Reset_Business_Day_Convention AS 'Reset_Business_Day_Convn',
Leg.Settlement_Business_Day_Convention AS 'Settlement_Business_Day_Convn',
Leg.First_Payment_Date AS 'First_Period_End_Date',
Leg.Day_Count AS 'Day_Count_Basis',
Leg.Interest_Rate AS 'Interest_Rate',
Leg.Spread AS 'Spread',
Leg.CDX_Attachment AS 'CDX_Attachment',
Leg.CDX_Detachment AS 'CDX_Detachment',
Leg.Factor AS 'Factor',
Leg.Commission AS 'Commission',
Leg.Reset_Lag AS 'Reset_Lag',
Leg.Initial_Index_Price AS 'Initial_Price',
Ct.Principal_Exchange_Initial AS 'Principal_Exchange_Initial',
Ct.Principal_Exchange_Final AS 'Principal_Exchange_Final',
IsNull(Leg.Delay_Days, 0) AS 'Settlement_Delay_Days',
Leg.Red_Code AS 'Red_Code',
Leg.Referenced_Asset AS 'Referenced_Asset',
SM.Short_Description AS 'Security_Description',
Leg.Notional_Reset_Type AS 'Notional_Reset_Type',
Leg.Reset_Arrears_Flag AS 'Reset_Arrears_Flag',
SM.MIC AS 'Position_Market',
SM.Currency AS 'Position_Currency',
1,
Ct.Security_Id,
Txn.CLEARED_TRD_INDICATOR
FROM
##AssetAddSwap_Tbl S
INNER JOIN Sch_Core_Data.Security_Master SM (NOLOCK) ON S.Security_ID = SM.Security_ID
INNER JOIN Sch_Core_Data.Security_Detail_SwapLeg Leg (NOLOCK) ON SM.Security_Id = Leg.Security_Id
INNER JOIN Sch_Core_Data.Security_Detail_SwapContract Ct (NOLOCK) ON Leg.Contract_Security_Id = Ct.Security_Id
LEFT JOIN Sch_Core_Data.VW_TRANSACTIONS_Abbreviated Txn WITH (NOLOCK) ON Leg.Security_ID = Txn.Security_ID
LEFT JOIN Sch_Core_Data.Security_Alt_Identifier SAI (NOLOCK) ON SAI.Security_Id = Leg.Security_Id
AND SAI.Identifier_Type = 'APXID' AND SAI.STATUS_FLAG = 'ACT'
WHERE
S.Retransmit_Flag = 1
OR (--Txn.Transaction_ID IS NOT NULL
--AND Txn.TRANSACTION_SOURCE_SYSTEM <> @TargetSystem
Txn.TRANSACTION_SOURCE_SYSTEM NOT IN (SELECT svalue from SCH_CORE_DATA.DBL WHERE PROCESS = 'SYSTEMS' AND [FUNCTION] = 'LIST' AND DESCRIPTION3 = 'NON-TOM')
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Transmitted, 3) = 0
AND IsNull(SAI.Identifier, '') = '')


Using this function:



-- =============================================
-- Author: Anuj Kalra
-- =============================================
CREATE FUNCTION [SCH_CORE_CODE].[UDF_CHK_BITVALUE]
(
@VALUE INT,
@FIND INT
)
RETURNS BIT
WITH EXECUTE AS 'USR_CORE'
AS
BEGIN
DECLARE @CHECK BIT;
SET @CHECK = 0;
IF ((POWER(2,@FIND) & @VALUE)<> 0)
BEGIN
SET @CHECK = 1;
END
RETURN @CHECK;









share|improve this question









New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

    – scsimon
    9 hours ago












  • Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

    – Aaron Bertrand
    8 hours ago












  • Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

    – Martin Smith
    7 hours ago






  • 2





    Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

    – Jeff
    6 hours ago






  • 1





    Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

    – Josh Darnell
    5 hours ago

















2















Here is the plan: https://www.brentozar.com/pastetheplan/?id=rkM8d7ONS



I am mostly interested in how to get rid of the lazy spool?



This is the query:



SELECT DISTINCT 
SM.Security_ID 'Security_ID',
Leg.Leg_Type 'Leg_Type',
Leg.Leg_Side 'Leg_Side',
Ct.Security_Type AS 'Swap_Type',
Leg.CDX_Indicator AS 'CDS_CDX_Flag',
SM.Currency AS 'Notional_Currency',
Ct.Cross_Currency_Flag AS 'Cross_Currency_Flag',
Ct.Custom_Overrides AS 'Special_Instructions',
Leg.Protection_Indicator AS 'Buy_Sell_Protection',
Leg.Commission_Direction AS 'Commission_Direction',
Leg.Dividend_Payment_Indicator AS 'Undl_Asset_Dividend_Flag',
SM.Issue_Date AS 'Effective_Date',
SM.Maturity_Date AS 'Maturity_Date',
Leg.Settlement_Frequency 'Settlement_Frequency',
Leg.Reset_Frequency 'Reset_Frequency',
Leg.Roll_Day AS 'Roll_Day',
Leg.Reset_Business_Day_Convention AS 'Reset_Business_Day_Convn',
Leg.Settlement_Business_Day_Convention AS 'Settlement_Business_Day_Convn',
Leg.First_Payment_Date AS 'First_Period_End_Date',
Leg.Day_Count AS 'Day_Count_Basis',
Leg.Interest_Rate AS 'Interest_Rate',
Leg.Spread AS 'Spread',
Leg.CDX_Attachment AS 'CDX_Attachment',
Leg.CDX_Detachment AS 'CDX_Detachment',
Leg.Factor AS 'Factor',
Leg.Commission AS 'Commission',
Leg.Reset_Lag AS 'Reset_Lag',
Leg.Initial_Index_Price AS 'Initial_Price',
Ct.Principal_Exchange_Initial AS 'Principal_Exchange_Initial',
Ct.Principal_Exchange_Final AS 'Principal_Exchange_Final',
IsNull(Leg.Delay_Days, 0) AS 'Settlement_Delay_Days',
Leg.Red_Code AS 'Red_Code',
Leg.Referenced_Asset AS 'Referenced_Asset',
SM.Short_Description AS 'Security_Description',
Leg.Notional_Reset_Type AS 'Notional_Reset_Type',
Leg.Reset_Arrears_Flag AS 'Reset_Arrears_Flag',
SM.MIC AS 'Position_Market',
SM.Currency AS 'Position_Currency',
1,
Ct.Security_Id,
Txn.CLEARED_TRD_INDICATOR
FROM
##AssetAddSwap_Tbl S
INNER JOIN Sch_Core_Data.Security_Master SM (NOLOCK) ON S.Security_ID = SM.Security_ID
INNER JOIN Sch_Core_Data.Security_Detail_SwapLeg Leg (NOLOCK) ON SM.Security_Id = Leg.Security_Id
INNER JOIN Sch_Core_Data.Security_Detail_SwapContract Ct (NOLOCK) ON Leg.Contract_Security_Id = Ct.Security_Id
LEFT JOIN Sch_Core_Data.VW_TRANSACTIONS_Abbreviated Txn WITH (NOLOCK) ON Leg.Security_ID = Txn.Security_ID
LEFT JOIN Sch_Core_Data.Security_Alt_Identifier SAI (NOLOCK) ON SAI.Security_Id = Leg.Security_Id
AND SAI.Identifier_Type = 'APXID' AND SAI.STATUS_FLAG = 'ACT'
WHERE
S.Retransmit_Flag = 1
OR (--Txn.Transaction_ID IS NOT NULL
--AND Txn.TRANSACTION_SOURCE_SYSTEM <> @TargetSystem
Txn.TRANSACTION_SOURCE_SYSTEM NOT IN (SELECT svalue from SCH_CORE_DATA.DBL WHERE PROCESS = 'SYSTEMS' AND [FUNCTION] = 'LIST' AND DESCRIPTION3 = 'NON-TOM')
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Transmitted, 3) = 0
AND IsNull(SAI.Identifier, '') = '')


Using this function:



-- =============================================
-- Author: Anuj Kalra
-- =============================================
CREATE FUNCTION [SCH_CORE_CODE].[UDF_CHK_BITVALUE]
(
@VALUE INT,
@FIND INT
)
RETURNS BIT
WITH EXECUTE AS 'USR_CORE'
AS
BEGIN
DECLARE @CHECK BIT;
SET @CHECK = 0;
IF ((POWER(2,@FIND) & @VALUE)<> 0)
BEGIN
SET @CHECK = 1;
END
RETURN @CHECK;









share|improve this question









New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

    – scsimon
    9 hours ago












  • Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

    – Aaron Bertrand
    8 hours ago












  • Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

    – Martin Smith
    7 hours ago






  • 2





    Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

    – Jeff
    6 hours ago






  • 1





    Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

    – Josh Darnell
    5 hours ago













2












2








2








Here is the plan: https://www.brentozar.com/pastetheplan/?id=rkM8d7ONS



I am mostly interested in how to get rid of the lazy spool?



This is the query:



SELECT DISTINCT 
SM.Security_ID 'Security_ID',
Leg.Leg_Type 'Leg_Type',
Leg.Leg_Side 'Leg_Side',
Ct.Security_Type AS 'Swap_Type',
Leg.CDX_Indicator AS 'CDS_CDX_Flag',
SM.Currency AS 'Notional_Currency',
Ct.Cross_Currency_Flag AS 'Cross_Currency_Flag',
Ct.Custom_Overrides AS 'Special_Instructions',
Leg.Protection_Indicator AS 'Buy_Sell_Protection',
Leg.Commission_Direction AS 'Commission_Direction',
Leg.Dividend_Payment_Indicator AS 'Undl_Asset_Dividend_Flag',
SM.Issue_Date AS 'Effective_Date',
SM.Maturity_Date AS 'Maturity_Date',
Leg.Settlement_Frequency 'Settlement_Frequency',
Leg.Reset_Frequency 'Reset_Frequency',
Leg.Roll_Day AS 'Roll_Day',
Leg.Reset_Business_Day_Convention AS 'Reset_Business_Day_Convn',
Leg.Settlement_Business_Day_Convention AS 'Settlement_Business_Day_Convn',
Leg.First_Payment_Date AS 'First_Period_End_Date',
Leg.Day_Count AS 'Day_Count_Basis',
Leg.Interest_Rate AS 'Interest_Rate',
Leg.Spread AS 'Spread',
Leg.CDX_Attachment AS 'CDX_Attachment',
Leg.CDX_Detachment AS 'CDX_Detachment',
Leg.Factor AS 'Factor',
Leg.Commission AS 'Commission',
Leg.Reset_Lag AS 'Reset_Lag',
Leg.Initial_Index_Price AS 'Initial_Price',
Ct.Principal_Exchange_Initial AS 'Principal_Exchange_Initial',
Ct.Principal_Exchange_Final AS 'Principal_Exchange_Final',
IsNull(Leg.Delay_Days, 0) AS 'Settlement_Delay_Days',
Leg.Red_Code AS 'Red_Code',
Leg.Referenced_Asset AS 'Referenced_Asset',
SM.Short_Description AS 'Security_Description',
Leg.Notional_Reset_Type AS 'Notional_Reset_Type',
Leg.Reset_Arrears_Flag AS 'Reset_Arrears_Flag',
SM.MIC AS 'Position_Market',
SM.Currency AS 'Position_Currency',
1,
Ct.Security_Id,
Txn.CLEARED_TRD_INDICATOR
FROM
##AssetAddSwap_Tbl S
INNER JOIN Sch_Core_Data.Security_Master SM (NOLOCK) ON S.Security_ID = SM.Security_ID
INNER JOIN Sch_Core_Data.Security_Detail_SwapLeg Leg (NOLOCK) ON SM.Security_Id = Leg.Security_Id
INNER JOIN Sch_Core_Data.Security_Detail_SwapContract Ct (NOLOCK) ON Leg.Contract_Security_Id = Ct.Security_Id
LEFT JOIN Sch_Core_Data.VW_TRANSACTIONS_Abbreviated Txn WITH (NOLOCK) ON Leg.Security_ID = Txn.Security_ID
LEFT JOIN Sch_Core_Data.Security_Alt_Identifier SAI (NOLOCK) ON SAI.Security_Id = Leg.Security_Id
AND SAI.Identifier_Type = 'APXID' AND SAI.STATUS_FLAG = 'ACT'
WHERE
S.Retransmit_Flag = 1
OR (--Txn.Transaction_ID IS NOT NULL
--AND Txn.TRANSACTION_SOURCE_SYSTEM <> @TargetSystem
Txn.TRANSACTION_SOURCE_SYSTEM NOT IN (SELECT svalue from SCH_CORE_DATA.DBL WHERE PROCESS = 'SYSTEMS' AND [FUNCTION] = 'LIST' AND DESCRIPTION3 = 'NON-TOM')
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Transmitted, 3) = 0
AND IsNull(SAI.Identifier, '') = '')


Using this function:



-- =============================================
-- Author: Anuj Kalra
-- =============================================
CREATE FUNCTION [SCH_CORE_CODE].[UDF_CHK_BITVALUE]
(
@VALUE INT,
@FIND INT
)
RETURNS BIT
WITH EXECUTE AS 'USR_CORE'
AS
BEGIN
DECLARE @CHECK BIT;
SET @CHECK = 0;
IF ((POWER(2,@FIND) & @VALUE)<> 0)
BEGIN
SET @CHECK = 1;
END
RETURN @CHECK;









share|improve this question









New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











Here is the plan: https://www.brentozar.com/pastetheplan/?id=rkM8d7ONS



I am mostly interested in how to get rid of the lazy spool?



This is the query:



SELECT DISTINCT 
SM.Security_ID 'Security_ID',
Leg.Leg_Type 'Leg_Type',
Leg.Leg_Side 'Leg_Side',
Ct.Security_Type AS 'Swap_Type',
Leg.CDX_Indicator AS 'CDS_CDX_Flag',
SM.Currency AS 'Notional_Currency',
Ct.Cross_Currency_Flag AS 'Cross_Currency_Flag',
Ct.Custom_Overrides AS 'Special_Instructions',
Leg.Protection_Indicator AS 'Buy_Sell_Protection',
Leg.Commission_Direction AS 'Commission_Direction',
Leg.Dividend_Payment_Indicator AS 'Undl_Asset_Dividend_Flag',
SM.Issue_Date AS 'Effective_Date',
SM.Maturity_Date AS 'Maturity_Date',
Leg.Settlement_Frequency 'Settlement_Frequency',
Leg.Reset_Frequency 'Reset_Frequency',
Leg.Roll_Day AS 'Roll_Day',
Leg.Reset_Business_Day_Convention AS 'Reset_Business_Day_Convn',
Leg.Settlement_Business_Day_Convention AS 'Settlement_Business_Day_Convn',
Leg.First_Payment_Date AS 'First_Period_End_Date',
Leg.Day_Count AS 'Day_Count_Basis',
Leg.Interest_Rate AS 'Interest_Rate',
Leg.Spread AS 'Spread',
Leg.CDX_Attachment AS 'CDX_Attachment',
Leg.CDX_Detachment AS 'CDX_Detachment',
Leg.Factor AS 'Factor',
Leg.Commission AS 'Commission',
Leg.Reset_Lag AS 'Reset_Lag',
Leg.Initial_Index_Price AS 'Initial_Price',
Ct.Principal_Exchange_Initial AS 'Principal_Exchange_Initial',
Ct.Principal_Exchange_Final AS 'Principal_Exchange_Final',
IsNull(Leg.Delay_Days, 0) AS 'Settlement_Delay_Days',
Leg.Red_Code AS 'Red_Code',
Leg.Referenced_Asset AS 'Referenced_Asset',
SM.Short_Description AS 'Security_Description',
Leg.Notional_Reset_Type AS 'Notional_Reset_Type',
Leg.Reset_Arrears_Flag AS 'Reset_Arrears_Flag',
SM.MIC AS 'Position_Market',
SM.Currency AS 'Position_Currency',
1,
Ct.Security_Id,
Txn.CLEARED_TRD_INDICATOR
FROM
##AssetAddSwap_Tbl S
INNER JOIN Sch_Core_Data.Security_Master SM (NOLOCK) ON S.Security_ID = SM.Security_ID
INNER JOIN Sch_Core_Data.Security_Detail_SwapLeg Leg (NOLOCK) ON SM.Security_Id = Leg.Security_Id
INNER JOIN Sch_Core_Data.Security_Detail_SwapContract Ct (NOLOCK) ON Leg.Contract_Security_Id = Ct.Security_Id
LEFT JOIN Sch_Core_Data.VW_TRANSACTIONS_Abbreviated Txn WITH (NOLOCK) ON Leg.Security_ID = Txn.Security_ID
LEFT JOIN Sch_Core_Data.Security_Alt_Identifier SAI (NOLOCK) ON SAI.Security_Id = Leg.Security_Id
AND SAI.Identifier_Type = 'APXID' AND SAI.STATUS_FLAG = 'ACT'
WHERE
S.Retransmit_Flag = 1
OR (--Txn.Transaction_ID IS NOT NULL
--AND Txn.TRANSACTION_SOURCE_SYSTEM <> @TargetSystem
Txn.TRANSACTION_SOURCE_SYSTEM NOT IN (SELECT svalue from SCH_CORE_DATA.DBL WHERE PROCESS = 'SYSTEMS' AND [FUNCTION] = 'LIST' AND DESCRIPTION3 = 'NON-TOM')
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1
AND Sch_Core_Code.Udf_Chk_BitValue(Txn.Transmitted, 3) = 0
AND IsNull(SAI.Identifier, '') = '')


Using this function:



-- =============================================
-- Author: Anuj Kalra
-- =============================================
CREATE FUNCTION [SCH_CORE_CODE].[UDF_CHK_BITVALUE]
(
@VALUE INT,
@FIND INT
)
RETURNS BIT
WITH EXECUTE AS 'USR_CORE'
AS
BEGIN
DECLARE @CHECK BIT;
SET @CHECK = 0;
IF ((POWER(2,@FIND) & @VALUE)<> 0)
BEGIN
SET @CHECK = 1;
END
RETURN @CHECK;






sql-server sql-server-2012 execution-plan






share|improve this question









New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 5 hours ago









Josh Darnell

11.5k3 gold badges27 silver badges58 bronze badges




11.5k3 gold badges27 silver badges58 bronze badges






New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 9 hours ago









JeffJeff

112 bronze badges




112 bronze badges




New contributor



Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




Jeff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

    – scsimon
    9 hours ago












  • Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

    – Aaron Bertrand
    8 hours ago












  • Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

    – Martin Smith
    7 hours ago






  • 2





    Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

    – Jeff
    6 hours ago






  • 1





    Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

    – Josh Darnell
    5 hours ago

















  • Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

    – scsimon
    9 hours ago












  • Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

    – Aaron Bertrand
    8 hours ago












  • Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

    – Martin Smith
    7 hours ago






  • 2





    Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

    – Jeff
    6 hours ago






  • 1





    Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

    – Josh Darnell
    5 hours ago
















Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

– scsimon
9 hours ago






Welcome to SO! Is your ultimate goal to identify why your query is slow and how to improve it? If so, include your DDL scripts for your table definitions and indexes and some information about your environment. Good job on providing the plan and researching lazy spool

– scsimon
9 hours ago














Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

– Aaron Bertrand
8 hours ago






Your biggest cost is a distinct sort (I/O cost = 10375.6). Why are you worried about the lazy spool (I/O cost = 0.1)? It is more than 10,000 times cheaper than the sort (and is only there because of DISTINCT). Have you considered removing DISTINCT? Is it even doing what you think it's doing?

– Aaron Bertrand
8 hours ago














Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

– Martin Smith
7 hours ago





Also regarding perf it estimates that it will evaluate the Scalar UDFs 21,498,301 times each. Have you tried replacing Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1 with Txn.Account_Subscription & 8 =8(and same for the other one) to see what hit those are causing you?

– Martin Smith
7 hours ago




2




2





Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

– Jeff
6 hours ago





Aaron - My understanding about the lazy spool is that often the metric you see in the query plan is not really representative of the actual expense of the lazy spool. I may be able to remove the distinct. I am not sure yet.

– Jeff
6 hours ago




1




1





Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

– Josh Darnell
5 hours ago





Hi, Jeff - if you want more detailed help, it would be helpful if you could provide an actual execution plan (the one you linked to is an estimated plan). Also, the definition of the view would be useful VW_TRANSACTIONS_Abbreviated .

– Josh Darnell
5 hours ago










1 Answer
1






active

oldest

votes


















5














The use of a scalar user-defined function is inhibiting parallelism in this query, which is hinted at in the execution plan XML: NonParallelPlanReason="CouldNotGenerateValidParallelPlan"



One option would be to manually inline this function's implementation. So this:



Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1


Becomes this:



CASE WHEN (POWER(2,3) & Txn.Account_Subscription)<> 0 THEN 1 ELSE 0 END = 1


Note: you would need to do this for both references to the function



There are some large index scans in the execution plan (22 million rows are read from the ACCOUNT table). If the query really needs to process this many rows, parallelism can help a lot.



If the DISTINCT is not required for correct results, removing that could help with performance as well (preventing the potentially costly Sort (Distinct Sort) in the plan.



As far as the spool is concerned, it might actually be helping in this case. You can try suppressing the spool by adding OPTION (QUERYTRACEON 8690) to the end of the query and seeing how the plan / query execution time is different. On SQL Server 2016 onward, the query hint NO_PEROFRMANCE_SPOOL is available.






share|improve this answer





























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "182"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Jeff is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f245667%2fhow-can-i-get-rid-of-this-lazy-spool-or-otherwise-improve-this-querys-performa%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    The use of a scalar user-defined function is inhibiting parallelism in this query, which is hinted at in the execution plan XML: NonParallelPlanReason="CouldNotGenerateValidParallelPlan"



    One option would be to manually inline this function's implementation. So this:



    Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1


    Becomes this:



    CASE WHEN (POWER(2,3) & Txn.Account_Subscription)<> 0 THEN 1 ELSE 0 END = 1


    Note: you would need to do this for both references to the function



    There are some large index scans in the execution plan (22 million rows are read from the ACCOUNT table). If the query really needs to process this many rows, parallelism can help a lot.



    If the DISTINCT is not required for correct results, removing that could help with performance as well (preventing the potentially costly Sort (Distinct Sort) in the plan.



    As far as the spool is concerned, it might actually be helping in this case. You can try suppressing the spool by adding OPTION (QUERYTRACEON 8690) to the end of the query and seeing how the plan / query execution time is different. On SQL Server 2016 onward, the query hint NO_PEROFRMANCE_SPOOL is available.






    share|improve this answer































      5














      The use of a scalar user-defined function is inhibiting parallelism in this query, which is hinted at in the execution plan XML: NonParallelPlanReason="CouldNotGenerateValidParallelPlan"



      One option would be to manually inline this function's implementation. So this:



      Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1


      Becomes this:



      CASE WHEN (POWER(2,3) & Txn.Account_Subscription)<> 0 THEN 1 ELSE 0 END = 1


      Note: you would need to do this for both references to the function



      There are some large index scans in the execution plan (22 million rows are read from the ACCOUNT table). If the query really needs to process this many rows, parallelism can help a lot.



      If the DISTINCT is not required for correct results, removing that could help with performance as well (preventing the potentially costly Sort (Distinct Sort) in the plan.



      As far as the spool is concerned, it might actually be helping in this case. You can try suppressing the spool by adding OPTION (QUERYTRACEON 8690) to the end of the query and seeing how the plan / query execution time is different. On SQL Server 2016 onward, the query hint NO_PEROFRMANCE_SPOOL is available.






      share|improve this answer





























        5












        5








        5







        The use of a scalar user-defined function is inhibiting parallelism in this query, which is hinted at in the execution plan XML: NonParallelPlanReason="CouldNotGenerateValidParallelPlan"



        One option would be to manually inline this function's implementation. So this:



        Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1


        Becomes this:



        CASE WHEN (POWER(2,3) & Txn.Account_Subscription)<> 0 THEN 1 ELSE 0 END = 1


        Note: you would need to do this for both references to the function



        There are some large index scans in the execution plan (22 million rows are read from the ACCOUNT table). If the query really needs to process this many rows, parallelism can help a lot.



        If the DISTINCT is not required for correct results, removing that could help with performance as well (preventing the potentially costly Sort (Distinct Sort) in the plan.



        As far as the spool is concerned, it might actually be helping in this case. You can try suppressing the spool by adding OPTION (QUERYTRACEON 8690) to the end of the query and seeing how the plan / query execution time is different. On SQL Server 2016 onward, the query hint NO_PEROFRMANCE_SPOOL is available.






        share|improve this answer















        The use of a scalar user-defined function is inhibiting parallelism in this query, which is hinted at in the execution plan XML: NonParallelPlanReason="CouldNotGenerateValidParallelPlan"



        One option would be to manually inline this function's implementation. So this:



        Sch_Core_Code.Udf_Chk_BitValue(Txn.Account_Subscription, 3) = 1


        Becomes this:



        CASE WHEN (POWER(2,3) & Txn.Account_Subscription)<> 0 THEN 1 ELSE 0 END = 1


        Note: you would need to do this for both references to the function



        There are some large index scans in the execution plan (22 million rows are read from the ACCOUNT table). If the query really needs to process this many rows, parallelism can help a lot.



        If the DISTINCT is not required for correct results, removing that could help with performance as well (preventing the potentially costly Sort (Distinct Sort) in the plan.



        As far as the spool is concerned, it might actually be helping in this case. You can try suppressing the spool by adding OPTION (QUERYTRACEON 8690) to the end of the query and seeing how the plan / query execution time is different. On SQL Server 2016 onward, the query hint NO_PEROFRMANCE_SPOOL is available.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 hours ago

























        answered 5 hours ago









        Josh DarnellJosh Darnell

        11.5k3 gold badges27 silver badges58 bronze badges




        11.5k3 gold badges27 silver badges58 bronze badges























            Jeff is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Jeff is a new contributor. Be nice, and check out our Code of Conduct.












            Jeff is a new contributor. Be nice, and check out our Code of Conduct.











            Jeff is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f245667%2fhow-can-i-get-rid-of-this-lazy-spool-or-otherwise-improve-this-querys-performa%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

            The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

            19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу