sql-serversql-server-2022

How to count 0 or >0 rows in the EXCEPT query?


I have a query like

SELECT  ct=COUNT(*)
        FROM ( select f1, f2, ..., f52 from t1 except select f1, f2, ..., f52 from t2 where ... )

But by fact the result ct used as ct>0.
How to change/optimize the query above?


Solution

  • Original Query:

    SELECT  ct=COUNT(*)
            FROM ( select f1, f2, ..., f52 from t1 except select f1, f2, ..., f52 from t2 where ... )
    

    i edited to test with some dummy data:

    SELECT  ct=COUNT(*)
            FROM ( select * from works w1 except select * from works w2 where w2.company_name = 'Company1' )
    

    got this: (1 row affected) Table 'works'. Scan count 2, logical reads 15, physical reads 1, ...

    edited version:

    if exists (
        select *
        from works w1
        except
        select *
        from works w2
        where w2.company_name = 'Company1'
    )
    begin
        select 1 -- logic for when count(*) > 0
    end
    

    Table 'works'. Scan count 2, logical reads 11, physical reads 1, ...

    You can also add else for when count(*) = 0

    Basically, if exists will stop after the first occurrence of any match in the except clause, where count(*) will keep going until it gets the exact count number. This should improve performance imo.