84

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?

Denys S.
  • 6,358
  • 12
  • 43
  • 65
  • What are you trying to do? What will you do next after making the check? – Mark Byers May 21 '10 at 19:42
  • it is not clear if you want a result set returned and then check if any rows were int it, or if you just want to check if a query returns any rows without a result set?? – KM. May 21 '10 at 19:53
  • 1
    I want to know, if there will be any rows in a result set. – Denys S. May 21 '10 at 20:32

12 Answers12

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

 END
Ed B
  • 6,028
  • 3
  • 26
  • 35
  • 5
    Change 'SELECT *' to 'SELECT TOP 1 *' for efficiency – Ed B May 21 '10 at 19:49
  • 20
    @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 May 21 '10 at 20:04
  • 1
    @Ed B & @OMG Ponies, yea, I think SQL Server is smart enough to optimize the `EXISTS (SELECT *` or `EXISTS (SELECT 1` or `EXISTS (SELECT 1/0` away – KM. May 21 '10 at 20:08
  • 2
    @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 May 21 '10 at 20:37
  • 1
    I can note this is better than the accepted answer when you _only_ want to test if it is empty and not return a result set, such as if in a stored proc you do not want to return a result yet. – Mike M May 29 '20 at 00:10
103

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
  • 732,580
  • 175
  • 1,330
  • 1,459
14

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
  • 3,608
  • 3
  • 28
  • 39
  • 16
    If you agree, you should vote for that answer. Rather than repost identical content... – OMG Ponies May 21 '10 at 19:38
  • 1
    @OMG Ponies: It's not identical. He changed the * to a 1. – Mark Byers May 21 '10 at 19:44
  • 1
    Well, using "(SELECT TOP 1 * ..." would be more efficient than using "SELECT 1..." – Ed B May 21 '10 at 19:48
  • 5
    I get identical query plans using `SET SHOWPLAN_ALL ON` for `IF EXISTS (SELECT * FROM ...` and `IF EXISTS (SELECT 1 FROM ...` – KM. May 21 '10 at 19:51
  • 1
    Identical results because RDBMS optimizes suboptimal query implicitly. For my taste, this answer is cleaner and doesn't depend on optimization. Nothing is done "behind the scene" and it doesn't require knowledge about query optimizations. – Harry Apr 09 '21 at 09:18
12

You can do it in a number of ways.

IF EXISTS(select * from ....)
begin
 -- select * from .... 
end
else
 -- do something 

Or you can use IF NOT EXISTS , @@ROW_COUNT like

select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end
Samim Hussain
  • 396
  • 5
  • 14
7

try:

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

IF @@ROWCOUNT=0
BEGIN
    PRINT 'no rows!'
END
KM.
  • 101,727
  • 34
  • 178
  • 212
4
SELECT COUNT(1) FROM service s WHERE s.service_id = ?
ovais.tariq
  • 2,627
  • 17
  • 12
3

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
  • 45,732
  • 10
  • 64
  • 86
2
SELECT * FROM service s WHERE s.service_id = ?;
IF @@rowcount = 0
begin
select 'no data'
end
0

In my sql use information function

select FOUND_ROWS();

it will return the no. of rows returned by select query.

Sunil Kumar
  • 655
  • 1
  • 7
  • 12
0
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
  • 34,554
  • 11
  • 80
  • 120
0

SELECT count(*) as CountThis ....

Then you can compare it as string like so:

IF CHECKROW_RS("CountThis")="0" THEN ...

CHECKROW_RS is an object

csandreas1
  • 2,026
  • 1
  • 26
  • 48
0

well there is a way to do it a little more code but really effective

$sql = "SELECT * FROM messages";  //your query
$result=$connvar->query($sql);    //$connvar is the connection variable
$flag=0;
     while($rows2=mysqli_fetch_assoc($result2))
    { $flag++;}
    
if($flag==0){no rows selected;}
else{
echo $flag." "."rows are selected"
}