Carlo V. Dango
Carlo V. Dango

Reputation: 13832

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.

Upvotes: 30

Views: 54910

Answers (5)

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

Alternate syntax but should work the same as the accepted answer.

SELECT IIF(EXISTS (
    SELECT *
    FROM customer
    WHERE amount <> 0
        AND customerid = 22
    ), 1, 0) AS NonZeroExists

Upvotes: 0

Martin Smith
Martin Smith

Reputation: 452957

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

Upvotes: 35

RichardTheKiwi
RichardTheKiwi

Reputation: 107686

An alternative to EXISTS

select ISNULL((select TOP 1 1
               from customer
               where amount <> 0
                 and customerid = 22),0)

I already assumed that you will have an index on (customerid) or better (customerid,amount).

Upvotes: 2

Chris Shain
Chris Shain

Reputation: 51309

First index on customerid and amount

CREATE INDEX customer_idx ON customer(customerid, amount); 

then rewrite your query as

IF EXISTS (SELECT customerid
    FROM customer
    WHERE amount > 0 -- I am assuming here that amount cannot be a negative number.
    AND customerid = 22)
   SELECT 1
ELSE
   SELECT 0

This should result in an index seek on customer_idx. Otherwise you'll need to scan all rows for that customer (which your question seems to imply could be a lot).

Upvotes: 9

Conrad Frix
Conrad Frix

Reputation: 52645

Seems straight forward enough

IF EXISTS ( SELECT customerid
            FROM   customer
            WHERE  amount <> 0
                  and customerid = 22))
   SELECT 1
ELSE
   SELECT 0

Upvotes: 5

Related Questions