Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple check for SELECT query empty result

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?

like image 617
Denys S. Avatar asked May 21 '10 19:05

Denys S.


People also ask

How do you know if a SELECT statement returns nothing?

You can use @@ROWCOUNT. For e.g. You will get 0 if first statement will not return any rows. You can also use if statement to check that just after first statement.

What does an empty SQL query return?

Of course it returns 1! If there is a row being returned it doesn't matter what the row's columns look like. A column with null value can be valuable information.

Is Empty in SQL query?

The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

IF EXISTS(SELECT * FROM service s WHERE s.service_id = ?)  BEGIN    --DO STUFF HERE   END 
like image 87
Ed B Avatar answered Oct 11 '22 10:10

Ed B


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.

like image 23
marc_s Avatar answered Oct 11 '22 11:10

marc_s