If there is no result your query can return null
, so in the general case you should check for it. E.g.:
SELECT TOP 1 Col1 FROM TABLE WHERE ...
The above query can return:
null
if there are no rows matching the WHERE clause
DBNull.Value
if the first matching row has a NULL value in Col1
- else a non-null value
If your query is such that you can guarantee there will always be a result, you only need to check for DBNull. E.g.
SELECT MAX(Col1) FROM TABLE WHERE ...
The above query will return DBNull.Value if there are no rows matching the WHERE clause. It never returns null
.
And of course there are some cases where you can guarantee a non-null result, in which case you don't need to test for null or DBNull. E.g.
SELECT COUNT(Col1) FROM TABLE WHERE ...
SELECT ISNULL(MAX(Col1),0) FROM TABLE WHERE ...
The above query will always return a non-null value. It never returns null
or DBNull.Value
.