tags:

views:

38

answers:

1

Hi, How can I use If exist in this statement ?

select count(*) as found from names where myname = "Hulk"

which one will be better ?

+2  A: 

This statement:

SELECT  COUNT(*) AS found
FROM    names
WHERE   name = 'Hulk'

will return you the total number of records for 'Hulk'

This statement:

SELECT  1 AS found
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    names
        WHERE   name = 'Hulk'
        )

will return 1 if at least one record exists, otherwise it will return nothing.

If you just need to check that at least one record exists, the latter query is more efficient.

Quassnoi
@OP: And if you need to use `select count` for some reason, don't use `count(*)`, you're making the RDBMS work too hard. Use `count(name)` (in this case). That way, if the information is in an index, it can use it. (Although I'd expect systems to optimize it for you, I'm frequently surprised by what systems don't optimize for you, so...)
T.J. Crowder
@TJCrowder: all major systems will optimize `COUNT(*)` in best possible way. In this very case, `COUNT(name)` will be of same semantics and performance, but in general, the system will need to retrieve `name` to make sure it is not null, so it will be less efficient and possibly even produce the wrong results.
Quassnoi
Thank you all . Stackoverflow rocks !!!
ahmed