I'm trying to understand the performance logic between the following two stored procedures. Let's say I have a stored procedure that counts rows from three different tables based on a variable called @user. Is it better to filter the output on each table select or to filter only once on the "parent" select.
Stored Procedure 1
CREATE PROCEDURE [dbo].[myProcedure1]
@user NVARCHAR(150),
@postCount int out
AS
BEGIN
SELECT @postCount = COUNT(unionPostCount.IDpost)
FROM (
SELECT IDpost FROM Table1 WHERE Table1.IDuser = @user
UNION ALL SELECT IDpost FROM Table2 WHERE Table2.IDuser = @user
UNION ALL SELECT IDpost Table3 WHERE Table3.IDuser = @user
)
AS unionPostCount
END
Stored Procedure 2
CREATE PROCEDURE [dbo].[myProcedure2]
@user NVARCHAR(150),
@postCount int out
AS
BEGIN
SELECT @postCount = COUNT(unionPostCount.IDpost)
FROM (
SELECT IDpost FROM Table1
UNION ALL SELECT IDpost FROM Table2
UNION ALL SELECT IDpost Table3
)
AS unionPostCount WHERE unionPostCount.IDuser = @user
END
I have the feeling that with very huge tables Procedure 2 is slower because it has to select all rows from three tables and then filter them but I might be wrong. Which of the two procedures is faster in performance? All help is well apprecated.
I changed the answer as indeed Viktor was right. The plans are identical.
I still believe that 3 count operations should be faster depending on the size of the data retrieved, thought the most time spent is in finding the rows in all solutions. So I guess all solutions are close in terms of performans.
I guess the'll have the same execution plan. Just be sure to have an index on IDuser for all tables involved. For a faster solution count each select separately and add results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With