开发者

Optimizing SELECT COUNT to EXISTS

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

SELECT COUNT(*)
  FROM CUSTOMER
 WHERE amount <> 0
   开发者_JS百科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.


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


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).


Seems straight forward enough

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜