SQL case expression with where condition - sql

how can I arrange the case expression of sql in the correct format as I am getting errors.
I am trying to make a condition if the field date of leaving is not null display left otherwise display active
SELECT DISTINCT
PEO.PEOPLE_ID AS [PEOPLE_ID]
,PEO.EMPLOYEECLOCKNO AS [EMPLOYEENUMBER]
,ISNULL(CONVERT(VARCHAR(50),PEO.DATEOFJOIN,103),'') AS [DATEOFJOIN]
--,ISNULL(PEO.DISPLAYSTATUS,'') AS [DISPLAYSTATUS]
,CASE
When ISNULL(PEO.STATUS,'' ) = 'A'
Then 'ACTIVE'
ELSE 'LEFT' WHERE PEO.DATEOFLEAVING <> NULL
END as [STATUS]
INTO #BSP_EMPLOYEEDETAILS
Thank you for your help.

I am trying to make a condition if the field date of leaving is not null display left otherwise display active
CASE WHEN PEO.DATEOFLEAVING IS NULL THEN 'ACTIVE' ELSE 'LEFT' END
(I prefer to make boolean checking positive-feeling rather than negative-feeling, but if you want it negative...)
CASE WHEN PEO.DATEOFLEAVING IS NOT NULL THEN 'LEFT' ELSE 'ACTIVE' END
Note well HoneyBadger's comment; you should only compare something to null using IS NULL or IS NOT NULL - the result of a null right operand with any non-IS operator, is null:
NULL IS NULL --true
NULL IS NOT NULL --false
NULL = NULL --null, which eventually will (probably) be processed as false
NULL <> NULL --null, which eventually will (probably) be processed as false
NULL != NULL --null, which eventually will (probably) be processed as false
NOT(NULL = NULL) --null, which eventually will (probably) be processed as false
I say "eventually" because it's important; null spreads. If you look at the last case, NULL=NULL is NULL, which then becomes NOT(NULL) which is also NULL. If NULL=NULL instantly became FALSE then NOT(NULL=NULL) would be NOT(FALSE) which would be TRUE. The fact that the null spreads throughout the entire set of operations you subject it do, popping out at the end and then being interpreted as false is something that may be advantageous, but always something you should be aware of...
Of course if the thing that receives it is intended for processing NULL, like COALESCE(NOT(NULL=NULL), 'it was null') then it will receive a null (and in this case would output 'it was null') but generally when youre using it in a boolean context like CASE WHEN NOT(mycolumn=NULL) THEN... or WHERE NOT(mycolumn=NULL) the NULL it becomes is received by case when/where and interpreted as false.
It's probably worth pointing out that SQLServer doesn't support booleans in these sort of contexts so you wouldn't get away with using a coalesce like that, or even the NOT(NULL=NULL) example but if you want to experiment to sound out your knowledge, MySQL is a lot more forgiving, and will allow queries like:
select case when (NOT(x = NULL)) IS NULL THEN 't' ELSE 'f' end
from (select null as x)y
select case when (NOT(x = NULL)) IS UNKNOWN THEN 't' ELSE 'f' end
from (select null as x)y
SQLServer expects you to make your null determinations sooner, and doesn't let you bandy around with things that it can see have become null/unknown
Footnote about UNKNOWN; it's generally treated (in the spec, even) as synonmous with a boolean NULL - it's talked about in the truth table sense as the third value in a tri-state boolean logic, but DBs generally make for interchangeable use if they support UNKNOWN as a keyword. For me, personally, I like one-less-thing-to-remember; you can learn how NULL behaves and achieve logically consistent results by applying those simple rules: IS NULL, IS NOT NULL, anything else becomes NULL which then nulls everything it touches

Related

SQL: Is there a way for me to call another table.field when my initial table.field = NULL?

Morning All! Essentially, I found out that a potential table.field I'd like to use may not have the information I want, so, I might have to look into a separate field. My below thought process is:
If table.field1 = NULL then pull the value from table.field2. If table.field2 = NULL then state "No Phone"
My current SQL statement in the select, cause it's in a certain format, is:
substring(view_episode_summary_current.patient_home_phone, 1, 3) || ' ' || substring(view_episode_summary_current.patient_home_phone, 5, 8)
Above is let's say table.field1. I'm assuming I'll need to create a CASE statement right? I just didn't know how long it could be?
(case when view_episode_summary_current.patient_home_phone = NULL then table.field2)
But I don't know how to get it to evaluate if table.field2 = null and display the value.
In many databases, you can use coalesce() to implement that kind of logic:
coalesce(t1.field1, t2.field2) as myfield
coalesce() returns the first non-null value across its arguments. So it gives you t1.field1 if it is not null, else it falls back on t2.field2. If both are null, you get a null value as a result.
You could also use a case expression - there is no benefit as compared to colaesce(), but this can handle more complex cases than just nullity checks
case
when t1.field1 is not null then t1.field1
when t2.field2 is not null then t2.field2
end as myfield
case stops on the first branch where the condition is fulfilled. If no branch matches, it returns null - you can put an else branch at the end of your code to return something else.
Note that both techniques requires both fields to have similar data types.
You do not show your actual query so I cannot show how to use that in your code.

TSQL filter that I do not understand, 2 versions that I thought would return the same data do not

So I have a SQL statement that was not returning data like it should (MSSQL Server), in part of the query I had this
and t.Invc_Sts_Cd <> 2
turns out if I changed that to
and (t.Invc_Sts_Cd <> 2 OR t.Invc_Sts_Cd IS NULL)
then it returned the data I expected, I would have thought those 2 things would be equivalent but obviously not in TSQL.
Here is the full Statement
SELECT t.tm_sht_id,0
FROM tm_sht t
INNER JOIN cand c ON c.cand_id = t.cand_id
LEFT JOIN SOW_Resource sr on c.Req_Id = sr.Req_Id and (sr.Invoice_Timesheets=1 OR sr.Invoice_Timesheets is NULL)
WHERE t.tm_sht_sts_cd = 3
AND t.apvd_dt >= #Last_Run_Time
and c.clnt_org_id = #Org_Id
and (t.Suspend_Fg <> 1)
and (t.Invc_Sts_Cd <> 2 OR t.Invc_Sts_Cd IS NULL)
My question is why do those return different data sets?
t.Invc_Sts_Cd <> 2 and (t.Invc_Sts_Cd <> 2 OR t.Invc_Sts_Cd IS NULL) are not equivalent, but they are similar.
The key thing you need to understand here is how NULL values work. Nothing is equal to or not equal to NULL, including NULL itself; NULL = NULL isn't TRUE (though is isn't FALSE either, but I come to that shortly). The only way to evaluate against a NULL is using IS NULL and IS NOT NULL.
When doing a comparison against NULL, if you don't use IS (NOT) NULL then the result will be UNKNOWN. For a expression like WHERE Column = 1 then it isn't a problem when Column has the value NULL, as it isn't 1. For other expressions, it does.
For WHERE Column <> 2, when Column has the value NULL it gives result the UNKNOWN, which importantly is not TRUE. Thus the row does not meet to criteria.
The same is true for an expression like WHERE NOT(Column = 1). If Column has the value NULL, then Column = 1 = UNKNOWN and NOT(UNKNOWN) is still UNKNOWN.
Therefore, if you have NULL values, and are performiong comparisons which rely on them, you must include IS NULL and/or IS NOT NULL logic.
Remember, NULL means you don't know what the value is. This is subtly different than not having a value at all. When you don't know what the value is, it's still possible the value might be 2, and therefore NULL <> 2 could still possibly be false... but, again, the result is you don't know.
Therefore, if t.Invc_Sts_Cd is NULL, then t.Invc_Sts_Cd <> 2 must evaluate as... NULL, because we don't know what the result is. And NULL is falsy when you force it into a true/false boolean situation.
This is not about T-SQL, but SQL in general. NULL is the unknown value. If you compare it with some value, the result is hence unknown (i.e. it could or could not match the value).
So both
and t.Invc_Sts_Cd <> 2
and
and t.Invc_Sts_Cd = 2
exclude NULLs from the result, because for a NULL in Invc_Sts_Cd neither expression results in TRUE.
The crux here is that the logical comparison:
t.Invc_Sts_Cd <> 2
is actually false when the Invc_Sts_Cd value is NULL. The reason for this is that comparing NULL to any other value yields the value NULL, which will evaluate to false when it appears inside a WHERE clause.
The second version of your logic is correct:
and (t.Invc_Sts_Cd <> 2 OR t.Invc_Sts_Cd IS NULL)
This will be true when either Invc_Sts_Cd is not equal to 2, or this value happens to be NULL.

Simple where clause condition involving NULL

I have a query that needs to exclude both Null and Blank Values, but for some reason I can't work out this simple logic in my head.
Currently, my code looks like this:
WHERE [Imported] = 0 AND ([Value] IS NOT NULL **OR** [Value] != '')
However, should my code look like this to exclude both condition:
WHERE [Imported] = 0 AND ([Value] IS NOT NULL **AND** [Value] != '')
For some reason I just can't sort this in my head properly. To me it seems like both would work.
In your question you wrote the following:
have a query that needs to exclude both Null and Blank Values
So you have answered yourself, the AND query is the right query:
WHERE [Imported] = 0 AND ([Value] IS NOT NULL AND [Value] != '')
Here is an extract from the ANSI SQL Draft 2003 that I borrowed from this question:
6.3.3.3 Rule evaluation order
[...]
Where the precedence is not determined by the Formats or by
parentheses, effective evaluation of expressions is generally
performed from left to right. However, it is
implementation-dependent whether expressions are actually evaluated left to right, particularly when operands or operators might
cause conditions to be raised or if the results of the expressions
can be determined without completely evaluating all parts of the
expression.
You don't specify what kind of database system you are using but the concept of short-circuit evaluation which is explained in the previous paragraph applies to all major SQL versions (T-SQL, PL/SQL etc...)
Short-circuit evaluation means that once an expression has been successfully evaluated it will immediately exit the condition and stop evaluating the other expressions, applied to your question:
If value is null you want to exit the condition, that's why it should be the first expression (from left to right) but if it isn't null it should also not be empty, so it has to be NOT NULL and NOT EMPTY.
This case is a bit tricky because you cannot have a non empty string that is also null so the OR condition will also work but you will do an extra evaluation because short-circuit evaluation will never exit in the first expression:
Value is null but we would always need to check that value is also not an empty string (value is null or value is not an empty string).
In this second case, you may get an exception because the expression [Value] != '' may be checked on a null object.
So I think AND is the right answer. Hope it helps.
If the value was numeric and you didn't want either 1 or 2, you would write that condition as
... WHERE value != 1 AND value != 2
An OR would always be true in this case. For instance a value of 1 would return true for the check against 2 - and then the OR-check would return true, as at least one of the conditions evaluated to true.
When yu also want to check against null values, the situation is a bit more complicated. A check against a null value always fails: value != '' is false when value is null. That is why there is a special IS NULL or IS NOT NULL test.

SQL handling null values

The issue is i have 3 conditions good bad ugly. My goal is if one of the following condition is null then replace null to 0 else if all the conditions are null then show it as null
case when 'Good' is not null or 'Bad' is not null or 'Ugly' is not null
then coalesce(value,0)
else value
end result
The problem here is even with the condition it turns all the nulls to 0 which is not what i want. Thanks in advance
Your current expression says (in pseudocode):
IF <something is true>
IF value IS NULL
RETURN 0
ELSE
RETURN value
ENDIF
ELSE
RETURN value
ENDIF
Is that what you wanted?
I think maybe you want something like this. If I get more details I will update.
If I were just going off of this comment
the question is if good is null and bad and ugly for the same product
has a value 0-100 then i want the null to be replaced to 0. if all the
three are null for the same prod then i want them to be nulls and not
0
I would give you something like this
case
when good is not null then good
when good is null and coalesce(bad,-1) between (0 and 100) and coalesce( ugly,-1) between (0 and 100) then 0
else null
end
If you were trying to provide all 3 columns (I am assuming you have multiple columns) you might do something like this.
select
case
when good is null and bad is null and ugly is null then null
when good is null and (bad is not null or ugly is not null) then 0
else good
end as 'good column values'
,
case
when good is null and bad is null and ugly is null then null
when bad is null and (good is not null or ugly is not null) then 0
else bad
end as 'bad column values'
,
case
when good is null and bad is null and ugly is null then null
when ugly is null and (good is not null or bad is not null) then 0
else ugly
end as 'ugly column values'
Your code says "if one of good, bad, or ugly is not null" but your question says "if one of good, bad, or ugly is null"
If I'm understanding you correctly, just take out the nots.
Edit: I'm also assuming that you don't actually mean to use the literal strings "Good", "Bad" and "Ugly", but that they are meant to represent column names or something.
You should be aware that using these strings means that your code will never enter the "else" condition, as "Good", "Bad" and "Ugly" are not null.
EDIT 2: take your column names (good, bad, ugly) out of quotes so they will actually be evaluated. This is why you're still seeing that error.

Sql Server: CASE Statement does unexpected behavior when comparing to NULL

Given:
The following Select statement:
select case NULL
when NULL then 0
else 1
end
Problem:
I'm expecting this to return 0 but instead it returns 1. What gives?
Generally speaking, NULL is not something you should attempt to compare for equality, which is what a case statement does. You can use "Is NULL" to test for it. There is no expectation that NULL != NULL or that NULL = NULL. It's an indeterminate, undefined value, not a hard constant.
-- To encompass questions in the comments --
If you need to retrieve a value when you may encounter a NULL column, try this instead:
Case
When SomeColumn IS NULL
Then 0
Else 1
End
I believe that should work. As far as your original post is concerned:
Select Case NULL
When NULL then 0 // Checks for NULL = NULL
else 1 // NULL = NULL is not true (technically, undefined), else happens
end
The trouble is that your Case select automatically attempts to use equality operations. That simply doesn't work with NULL.
I was going to add this as a comment to Aaron's answer, but it was getting too long, so I'll add it as another (part of the) answer.
The CASE statement actually has two distinct modes, simple and searched.
From BOL:
The CASE expression has two formats:
The simple CASE expression compares an expression to a set of simple expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to determine the result.
When the simple CASE (your example) does what it describes as comparison it does an equality comparison - i.e. =
This is clarified in the later documentation:
The simple CASE expression operates by comparing the first expression
to the expression in each WHEN clause for equivalency. If these
expressions are equivalent, the expression in the THEN clause will be
returned.
Allows only an equality check.
Because anything = NULL is always false in ANSI SQL (and if you didn't know this, you need to read up on NULLs in SQL more generally, particularly also with the behavior in the other searched comparison - WHERE x IN (a, b, c)), you cannot use NULL in a simple case and have it ever be compared to a value, with a NULL either in the initial expression or in the list of expressions to be compared against.
If you want to check for NULL, you will have to use an IF/ELSE construct or the searched CASE with a full expression.
I agree that it's kind of unfortunate there is no version which supports an IS comparison to make it easier to write:
select case colname
when IS NULL then 0
else 1
end
Which would make writing certain long CASE statements easier:
select case colname
when IS NULL then ''
when 1 then 'a'
when 2 then 'b'
when 3 then 'c'
when 4 then 'd'
else 'z'
end
But that's just wishful thinking...
An option is to use ISNULL or COALESCE:
select case COALESCE(colname, 999999) -- 999999 is some value never used
when 999999 then ''
when 1 then 'a'
when 2 then 'b'
when 3 then 'c'
when 4 then 'd'
else 'z'
end
But it isn't always a great option.
In addition to the other answers, you need to change the syntax for CASE slightly to do this:
SELECT CASE
WHEN NULL IS NULL THEN 0
ELSE 1
END;
Using the value in your syntax implicitly uses an equals comparison. NULL is unknown, and so is NULL = NULL, so with your current code you will always get zero 1 (geez I did it too).
To get the behavior you want, you can use SET ANSI_NULLS ON; however note that this can change other code in ways you may not be able to predict, and the setting is deprecated - so it will stop working at all in a future version of SQL Server (see this SQL Server 2008 doc).
You need to use the IS NULL operator. Standard comparison operators do not work with NULL.
Check out these MSDN articles about Null that may be useful:
IS [NOT] NULL (Transact-SQL)
Null Values