Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a SQL Select statement returns no rows

I have a select statement

SELECT     QBalance
FROM         dbo.CustomerBalance
WHERE     (CustomerID = 1) AND (MarchentID = @MerchantId)

I want to check if that statement returns 0 rows. I tried to use the ISNULL and IFNULL but it seems that I'm missing something.

like image 229
Islam Avatar asked Oct 28 '11 16:10

Islam


People also ask

How can you tell if a SELECT returned no rows?

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 happens if SQL query returns nothing?

Your query is returning nothing because the execution engine is using an index that is incorrectly referenced by this specific application (Sage BusinessVision) you have to work around the issue.

How do you execute a SQL query only if another SQL query has no results?

The common table expression ( WITH clause) wraps the first query that we want to execute no matter what. We then select from the first query, and use UNION ALL to combine the result with the result of the second query, which we're executing only if the first query didn't yield any results (through NOT EXISTS ).

Can we use if condition in SELECT statement?

It is like a Shorthand form of CASE statement. We can conveniently use it when we need to decide between two options. There are three parts in IIF statement, first is a condition, second is a value if the condition is true and the last part is a value if the condition is false.


4 Answers

To find out whether no matching rows exist you can use NOT EXISTS. Which can be more efficient than counting all matching rows

IF NOT EXISTS(SELECT * FROM ...)
BEGIN
PRINT 'No matching row exists'
END
like image 196
Martin Smith Avatar answered Oct 05 '22 12:10

Martin Smith


If this is SQL Server, try @@ROWCOUNT.

like image 40
Dave Avatar answered Oct 05 '22 11:10

Dave


SELECT    COUNT(*) 
FROM         dbo.CustomerBalance 
WHERE     (CustomerID = 1) AND (MarchentID = @MerchantId) 

If you get 0, you got 0. :)

like image 21
Stuart Ainsworth Avatar answered Oct 05 '22 10:10

Stuart Ainsworth


You can use @@ROWCOUNT. For e.g.

SELECT     QBalance
FROM         dbo.CustomerBalance
WHERE     (CustomerID = 1) AND (MarchentID = @MerchantId)

--This will return no of rows returned by above statement.
SELECT @@ROWCOUNT

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. e.g.

IF @@ROWCOUNT <> 0 
  PRINT 'Select statement is returning some rows'
ELSE 
  PRINT 'No rows returned' 
like image 5
Bharat Prasad Satyal Avatar answered Oct 05 '22 11:10

Bharat Prasad Satyal