views:

104

answers:

7

Hi. Can anyone point out how to check if a select query returns non empty result set?

For example I have next query:

SELECT * FROM service s WHERE s.service_id = ?;

Should I do something like next:

ISNULL(SELECT * FROM service s WHERE s.service_id = ?)

to test if result set is not empty?

+5  A: 
IF EXISTS(SELECT * FROM service s WHERE s.service_id = ?)
 BEGIN
   --DO STUFF HERE

 END
Ed B
Change 'SELECT *' to 'SELECT TOP 1 *' for efficiency
Ed B
@Ed B: It doesn't matter because EXISTS returns true on the first successful match. Test using `EXISTS (SELECT 1/0 FROM SERVICE...` - it should return a can't divide by zero, but it won't
OMG Ponies
KM
Oh yes..you're right
Ed B
@OMG Ponies, @KM - The only reason I tell my developers to use Select 1 is to simplify searches to squash uses of Select *. In addition, I have run into efficiency problems in databases other than SQL Server (cough Access cough) where it did something with the Select clause for some silly reason.
Thomas
A: 
SELECT count(*) as count FROM service s WHERE s.service_id = ?;

test if count == 0 .

More baroquely:

select case when (SELECT count(*) as count FROM service s WHERE s.service_id = ?) = 0 then 'No rows, bro!' else 'You got data!" end as stupid_message;

tpdi
+2  A: 

I agree with Ed B. You should use EXISTS method but a more efficient way to do this is:

IF EXISTS(SELECT 1 FROM service s WHERE s.service_id = ?)
BEGIN
   --DO STUFF HERE

END

HTH

Raja
If you agree, you should vote for that answer. Rather than repost identical content...
OMG Ponies
@OMG Ponies: It's not identical. He changed the * to a 1.
Mark Byers
Well, using "(SELECT TOP 1 * ..." would be more efficient than using "SELECT 1..."
Ed B
I get identical query plans using `SET SHOWPLAN_ALL ON` for `IF EXISTS (SELECT * FROM ...` and `IF EXISTS (SELECT 1 FROM ...`
KM
A: 

Use @@ROWCOUNT:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT > 0 
   -- do stuff here.....

According to SQL Server Books Online:

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

marc_s
This is quiet straight forward, I like it. And that's what I was looking for. Thanks.
den-javamaniac
A: 

try:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT=0
BEGIN
    PRINT 'no rows!'
END
KM
A: 

To summarize the below posts a bit:

If all you care about is if at least one matching row is in the DB then use exists as it is the most efficient way of checking this: it will return true as soon as it finds at least one matching row whereas count, etc will find all matching rows.

If you actually need to use the data for processing or if the query has side effects, or if you need to know the actual total number of rows then checking the ROWCOUNT or count is probably the best way on hand.

Donnie
A: 
SELECT COUNT(1) FROM service s WHERE s.service_id = ?
ovais.tariq