Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to filter rows in each union table select or filter only once on the parent select

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.

like image 971
Gloria Avatar asked Mar 15 '23 00:03

Gloria


2 Answers

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.

like image 197
Dumitrescu Bogdan Avatar answered Mar 17 '23 15:03

Dumitrescu Bogdan


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.

like image 44
Nickthename Avatar answered Mar 17 '23 16:03

Nickthename