Search code examples
sqlsql-servert-sql

Optimizing SELECT COUNT to EXISTS


I have a query to find certain customers from a table.

SELECT COUNT(*)
  FROM CUSTOMER
 WHERE amount <> 0
   AND customerid = 22

There is an index on customerid, so the DB scans all rows with customerid = 22.

Since the result is processed by checking whether the count returns zero or more than zero, how can I optimize the query? I.e. such that at the first customer row with amount <> 0 the query returns 0 else if all rows are = 0, then return 1.


Solution

  • select case
             when exists (select *
                          from   customer
                          where  amount <> 0
                                 and customerid = 22) then 1
             else 0
           end  as non_zero_exists