confusing where clause in SQL Server - sql-server

I want to have a simple condition in my where clause, on one of the columns like:
When #PostTypeid is null then where should be PostTypeid in (4,5) and if
#PostTypeid is not null then where clause should be PostTypeId = #PostTypeId
I am trying to use case for this purpose but I think I am getting confused with the syntax. Here is what I have come up with so far:
(PostTypeid = case(#PostTypeId) when null then in (4,18) else #PostTypeId end)
The error is when I use in, I dont think that's a valid syntax. What is the correct way to do this? thanks. I Tried shifting the braces to several other places but in vain.
Thanks

Something like:
WHERE
(#PostTypeID IS NULL AND PostTypeId IN (4, 5)) OR
(#PostTypeId IS NOT NULL AND PostTypeID = #PostTypeID)
perhaps?

You cant use = and in operators in one statement
EDIT:
(PostTypeid = case(#PostTypeId) when null then in (4,18) else #PostTypeId end)
if the #PostTypeId is null then it will goes like this.
(PostTypeid = in (4,8))
and this is syntax error.
case(#PostTypeID) when IS NULL then PostyTypeId in (4,18) else PostTypeId = PostTypeId
this case should return single result.

Related

SQL ISNULL CASE

Can someone please explain to me in laymen terms why do we put ISNULL? I have an understanding of IS NULL but can't seem to put it together in this CASE context and what would be the impact if you didn't put it.
UpdateTime refers to when a particular row has been updated with new information
Example 1:
CASE WHEN ISNULL(DB1.UpdateTime,'') >= ISNULL(DB2.UpdateTime,'') THEN ISNULL(DB1.UpdateTime,'')
ELSE DB2.UpdateTime
END AS UpdateTime
FROM dbo.DB1_Result DB1 INNER JOIN dbo.DB2 DB2
ON DB1.ID = DB2.ID
Example 2:
StartTime = 01/01/2022
WHERE
(ISNULL(DB1.UpdateTime,'') >= #StartTime
Thank you!
SQL uses trinary logic: true, false, and null. null means the value is unknown, it could be anything.
If you try to compare anything with null you get null, even null. null = anything is null. null <> anything is null. null < anything is null. null > anything is also null.
Null is neither equal nor not equal to itself. null = null is null and null <> null is null. This is why we write x is null not x = null.
If you were to write
case
when DB1.UpdateTime >= DB2.UpdateTime then
db1.UpdateTime
else
db2.UpdateTime
end
and if either one is null the DB1.UpdateTime >= DB2.UpdateTime will be null. Case will treat that as false and return DB2.UpdateTime. If either value is null, you always get DB2.UpdateTime even if it's null and DB1.UpdateTime is not.
They don't want that. If DB2.UpdateTime is null, they want to return DB1.UpdateTime. If DB1.UpdateTime is null, they want to return DB2.UpdateTime. So they've used isnull to convert null to something that will compare as less than any time; '' works for that.
Demonstration.
Note: ELSE DB2.UpdateTime may want to be ELSE isnull(DB2.UpdateTime, '') to be consistent with THEN ISNULL(DB1.UpdateTime,'').
Note: isnull is a SQL Server extension. The SQL standard is coalesce.
Note: '' is not a timestamp. It happens to work, but other SQL servers will reject it. 1900-01-01 would be better.

SQL CASE when text field is NULL not working

I'm trying to run the following case statement in SQL:
CASE
WHEN P.Photos_Cloned_From IS NULL
THEN 'http://www.toolboxbarn.com/v/vspfiles/photos/'+P.ProductCode+'-2T.jpg'
ELSE 'http://www.toolboxbarn.com/v/vspfiles/photos/'+P.Photos_Cloned_From+'-2T.jpg'
END AS image_link,
The statements works, but only for those records that are not NULL. For items that are NULL, the statement is not returning the THEN condition.
Any suggestions?
Try this and let us know what happens.
'http://www.toolboxbarn.com/v/vspfiles/photos/'+
COALESCE(P.Photos_Cloned_From,P.ProductCode,'DEFAULT')+'-2T.jpg'
AS image_link,
Using coalesce here is better than the case statement. Some platforms can optimize coalesce and it lets you easily make a default value.
#hogan's Suggestion is a great one to save code, but ultimately it should have the same result as your case statement if you don't introduce his new 'default' case. It is most likely that the ProductCode is also NULL is that a possibility?
Why string + NULL = NULL because NULL is an unknown in sql most db platforms will nullify the entire value when null is aggregated or concatenated.
So Think of the following test cases:
Id ProductCode Photos_Cloned_From
1 1 ClonedFrom
2 2 Null
3 NULL Null
The results of your case expression and Hogan's Suggestion would be:
1) ELSE 'http://www.toolboxbarn.com/v/vspfiles/photos/ClonedFrom-2T.jpg'
2) WHEN 'http://www.toolboxbarn.com/v/vspfiles/photos/2-2T.jpg'
3) WHEN NULL
CASE WHEN ISNULL(P.Photos_Cloned_From,'') = '' THEN 'http://www.toolboxbarn.com/v/vspfiles/photos/'+P.ProductCode+'-2T.jpg'
ELSE 'http://www.toolboxbarn.com/v/vspfiles/photos/'+P.Photos_Cloned_From+'-2T.jpg'
END AS image_link,
SELECT
F.Name
, F.Address
, F.InDate
, ( CASE WHEN (F.Date_Down IS NULL and F.Cod_Down = 0 )THEN 0 ELSE -1 END) as 'sn_Down'
FROM
Folders F

Different conditions in WHERE clause

Is there a way to write this simplier?
WHERE
(
(#IdAgent IS NULL AND IdAgent IS NULL)
OR
(#IdAgent IS NOT NULL AND IdAgent = #IdAgent)
)
You can trivially remove one test, since = will never match a NULL and a non-NULL value:
WHERE
(#IdAgent IS NULL AND IdAgent IS NULL)
OR
IdAgent = #IdAgent
You could try using the method from this answer, which, when applied to your situation, would look something like this:
WHERE EXISTS (SELECT IdAgent
INTERSECT
SELECT #IdAgent)
You'll probably need to test it for performance in your particular environment to see if it doesn't run significantly slower than your present solution.

Using a bit input in stored procedure to determine how to filter results in the where clause

I'm beating my head against the wall here... can't figure out a way to pull this off.
Here's my setup:
My table has a column for the date something was completed. If it was never completed, the field is null. Simple enough.
On the front end, I have a checkbox that defaults to "Only show incomplete entries". When only pulling incomplete entries, it's easy.
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL
But offering the checkbox option complicates things a great deal. My checkbox inputs a bit value: 1=only show incomplete, 0=show all.
The problem is, I can't use a CASE statement within the where clause, because an actual value uses "=" to compare, and checking null uses "IS". For example:
SELECT
*
FROM Sometable
WHERE Completed_Date IS <---- invalid syntax
CASE WHEN
...
END
SELECT
*
FROM Sometable
WHERE Completed_Date =
CASE WHEN #OnlyIncomplete = 1 THEN
NULL <----- this translates to "WHERE Completed_Date = NULL", which won't work.. I have to use "IS NULL"
...
END
Any idea how to accomplish this seemly easy task? I'm stumped... thanks.
...
WHERE #OnlyIncomplete = 0
OR (#OnlyIncomplete = 1 AND Completed_Date IS NULL)
Hmmm... I think what you want is this:
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL OR (#OnlyIncomplete = 0)
So that'll show Date=NULL plus, if OnlyIncomplete=0, Date != Null. Yeah, I think that's it.
If you still want to use a CASE function (although it may be overkill in this case) :
SELECT
*
FROM Sometable
WHERE 1 =
(CASE WHEN #OnlyIncomplete = 0 THEN 1
WHEN #OnlyIncomplete = 1 AND Completed_Date IS NULL THEN 1
END)

How do I handle Error in sql queries?

For sql queries like..
select Quantity_Books/datepart(hour,Rent_Hour) from Rent_Book where (some conditions..)
They will return error when datepart(hour,Rent_Hour) is 0.
If sth like that Happens, I would like to show 0.
I know I should use case when But I am not really sure how..
Or any other better method?
You'd simply test the value first
select
CASE
WHEN datepart(hour,Rent_Hour) = 0 THEN 0
ELSE Quantity_Books/datepart(hour,Rent_Hour)
END
from
Rent_Book where (some conditions..)
Alternatively, use NULL rules
ISNULL((Quantity_Books / (NULLIF(datepart(hour,Rent_Hour), 0))), 0)
select case when datepart(hour,Rent_Hour)<>0 then Quantity_Books/datepart(hour,Rent_Hour) else 0 end as col ...

Resources