Not able to query with null values - sql

I need to query based on the parameter, used parameter in the CASE clause.
Parameter will contain these values : contactSuccess,contactFail,notcontacted
We have column : empCommunication which is boolean. It will take 0,1, null
Based on the Parameter value, I need to run the query.
Eg: if Parameter is contactSuccess then Where clause should be
empCommunication = 1
if Parameter is contactFail then Where clause should be
empCommunication = 0
The above two scenario's are working with the below query, but if fails with
Parameter is notContacted, in this case Where clause should be
empCommunication IS NULL.
Kindly help me on this.
SELECT
empCategory as name,
count(*) as value
from EmployeeRecords R
WHERE empCommunication =
CASE ?
WHEN 'contactSuccess' THEN 1
WHEN 'contactFail' THEN 0
WHEN 'notcontacted' THEN IS NULL
END
group by empCategory

Use coalesce() to cover the case where the parameter is 'notcontacted' with a different value like -1:
SELECT
empCategory as name,
count(*) as value
from EmployeeRecords R
WHERE coalesce(empCommunication, -1) =
CASE ?
WHEN 'contactSuccess' THEN 1
WHEN 'contactFail' THEN 0
WHEN 'notcontacted' THEN -1
END
group by empCategory

Assume that your param is p_param, you could change your query to
SELECT
empCategory AS name,
COUNT(*) AS value
FROM EmployeeRecords
WHERE
(empCommunication IS NULL AND p_param = 'notcontacted')
OR (empCommunication = 1 AND p_param = 'contactSuccess')
OR (empCommunication = 0 AND p_param = 'contactFail')
GROUP BY empCategory;

Try this one!
SELECT
empCategory as name,
count(*) as value
from EmployeeRecords R WHERE empCommunication =
(CASE a_column_in_table
WHEN 'contactSuccess' THEN 1
WHEN 'contactFail' THEN 0
WHEN 'notcontacted' THEN NULL
else null
END)
group by empCategory;`

Related

'CASE' expression whether to apply a WHERE condition to a query or not

I've been trying to accomplish something like the code below inside a stored procedure
Select * from TABLE1
CASE WHEN #SPParameter != 0 THEN -- if #SPParameter equals 0 then apply the where condition
WHERE Table1Column = #SPParameter -- apply a where condition
END
This query's goal is to select all rows from TABLE1 if #SPParameter is equal to zero, otherwise filter rows from TABLE1 if #SPParameter is not equal to zero.
Obviously the query above would throw an error message since the syntax is incorrect. Is this possible? Or is an if else statement the only way out?
Just use simple boolean logic1:
Select * from TABLE1
WHERE #SPParameter != 0 OR Table1Column = somevalue
CASE is an expression. It computes a value. It doesn't arbitrarily rearrange the parse tree of the statement it appears in.
1It'll be slightly more complex if we have to deal with NULLs but I've ignored them for now.
You can achieve by using OR condition like this way
WHERE (#SPParameter = 0 OR Table1Column = somevalue)
SELECT Name, JobType
FROM EMP
WHERE 1 = CASE
WHEN JobType = 'VC' THEN 1
WHEN JobType = 'HR' THEN 1
WHEN JobType = 'DEV' THEN 1
ELSE 0
END;
Above example CASE returns if jobtype present in table then it will be return the Name and JobType.
You try using case in where something like below:
Select * from TABLE1
where Table1Column = case when #SPParameter = 0 then #SPParameter else #SPParameter end;
Select * from TABLE1
WHERE Table1Column = CASE
WHEN #SPParameter != 0 THEN #SPParameter
END;
Here WHERE condition gets the value from the CASE statement, if #SPParameter is not equals zero, which means the value is present THEN it will be return the #SPParameter value.

single query that defines 2 tables has same row

query 1
(select count(*) from CALENDAR)
it returns 15
query 2
(select value from PARAMETER where name = 'PLAN_HORIZON')
it returns 15 too only when my programs runs without error. if error occurs,
it returns 10 or other values.
this↓ is wrong sql, but i want a single query which returns True or False.
select if (query1 == query2)
How can I define 2 sql has same result in a query?
The following SQL statement returns 0 or 1. It runs with SQL Server
SELECT CASE WHEN (select count(*) from CALENDAR) = (select value from PARAMETER where name = 'PLAN_HORIZON') THEN 1 ELSE 0 END
Something like this:
select count(*) = 0
from (
select count(*)
from calendar
except
select value
from parameter
where name = 'PLAN_HORIZON'
) t
You didn't specify your DBMS, but the above is standard SQL.
Try this query !
SELECT
CASE
WHEN (select count(*) from CALENDAR) = (select value from PARAMETER
where name = 'PLAN_HORIZON')
THEN true
ELSE false
END ;

How to check if all rows validate a predicate

I've a table in my database for which I need to check if all rows have one field not null.
If there are no row or if there is at least 1 row with the field null => true
If there are rows and they are all with the field not null => False
Is there a way to do this in on simple query? Or I need to check if my table is empty first then if it's not check if I've a row with the field value empty ?
This will count how many NULL values you have in a field;
SELECT
SUM(CASE WHEN FieldName IS NULL THEN 1 ELSE 0 END) NullValues
FROM TableName
Will return 0 if there are no NULL values, and will return the number of NULLS if there are any present.
If you actually want to return a value as 'True' or 'False' then do this;
SELECT CASE
WHEN a.NullValues > 0
THEN 'True'
ELSE 'False'
END CheckField
FROM (
SELECT
SUM(CASE WHEN FieldName IS NULL
THEN 1
ELSE 0
END) NullValues
FROM TableName
) a
Use count(*) and count(field) and compare the two:
select
case when count(*) > 0 and count(*) = count(field) then 1 -- not empty and no nulls
else 0 end as isgood
from mytable;
Oracle SQL has no boolean data type , so I use 1 for true and 0 for false. You can replace this with whatever you like (e.g. 'true' instead of 1 and 'false' instead of 0).
As to turning this into a predicate (correlated to a main query), you'd use something along the lines of:
select ...
from main
where exists
(
select 1
from mytable
where mytable.colx = main.coly
having count(*) > 0 and count(*) = count(field)
);
You can do this with aggregation. However, it is difficult to understand what you are asking for. If you want to check that a field has no NULL values, you can do:
select (case when count(*) > 0 then 1 else 0 end) as HasNullValues
from t
where field is null;
Alternate way I found using max with putting null first:
select case when
max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1
else 0 end as flag
from MYTABLE;

Return an INT from a Case statement

I am attempting to create a row called Flag that will keep a count of when Value is above 2. Later I will need to sum flag as a count.
I currently have:
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
I receive the error:
Conversion failed when converting the varchar value 'Flag' to data
type int.
How can I force the 1 or 0 to be an INT in order to do later math?
I've looked around and I can't seem to find a way that fits.
To be able to use previously created columns in the select, you'll need to use for example outer apply, with something like this:
select
*
from table1
outer apply (
select CASE WHEN Value > 2 THEN 1 ELSE 0 END AS Flag
) X
outer apply (
select CASE WHEN X.Flag = 1 THEN 1 ELSE 0 END AS FollowedUpCorrectly
) Y
Test this in SQL Fiddle
You could use CTE or a subquery to create a flag and then do your case statement as needed in the outer query like this:
;WITH q1
AS (
SELECT
col1
,col2
,col3
,CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag'
FROM your_table --change this to match your table and column name
)
SELECT q1.col1
,q1.col2
,q1.col3
,CASE
WHEN q1.Flag = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
FROM q1;
I might misunderstand what you are after.
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
If these two lines are in the same code block, 'Flag' is unknown in the second Case Statement.
Update: As Siyual has pointed out, Flag is a string literal. Try changing the name to something that is not a reserved word.
You are comparing a string ('Flag') to an int (1). Perhaps you meant to refer to the first case that you named 'Flag'. If so, try referring to it without using the single quotes. Then the analyzer will recognize it and accept it as an int, which it is. But 'Flag' is a string. Flag is an int.

SQL, Select if or select case

I am not sure what I am trying is achievable or not!!
I am trying to write a SQL query will will do select statement based on user input.
so if user input = 1 then I want it to select from actual table.
if user input = 0 then I want it do select 0 or null from dual. (if this is possible).
so Here is Parameter which will used to get input from user. ?i_userkey:'':null?
if user input's 1 then it will change null to 1.
I want to write a query using this parameter. something like this.
below is the logic.
IF i_userkey = 1 then
select ID,Gender,Age from TableA
If i_userkey = 0 then
select 0 or null from dual.
is this possible?
How about this:
SELECT
CASE WHEN i_userkey = 1 THEN ID ELSE NULL END AS ID
CASE WHEN i_userkey = 1 THEN Gender ELSE NULL END AS Gender
CASE WHEN i_userkey = 1 THEN AGE ELSE NULL END AS Age
FROM TableA
This will at least give you a consistent three-column result set you can work with. Having the query return differing column counts is not going to work.
select ID,Gender,Age
from TableA
where i_userkey = 1
union all
select 0, 0, 0
from dual
where i_userkey = 0
You might have to adjust the datatypes in the dual-select to match TableA