How do I format this case statement in sql? - sql

Basically, I want to return a 1 if the Field Blue is a 'Y' and a blank if it is not. Is this how I should go about this?
Case isnull(Blue, 'N') when Blue = 'Y' then 1 else '' end

Your null check is redundant. You only need to test for 'Y':
Case when Blue = 'Y' then '1' else '' end

you can do either
Case isnull(Blue, 'N') when 'Y' then '1' else '' end
or
Case when isnull(Blue, 'N') = 'Y' then '1' else '' end
see case

Related

Compare String in Oracle Case When

i have an issue with oracle case when.
SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' != ''
THEN '7C54D3E133830A78E040A8C010014B7D'
WHEN 'e84a4433966c4b8996ce34905acff63d' != ''
THEN 'e84a4433966c4b8996ce34905acff63d'
WHEN '7faa9126b1c6412fa58375ab2b2be1db' != ''
THEN '7faa9126b1c6412fa58375ab2b2be1db'
ELSE NULL
END
FROM DUAL
this query always returns null, though it's obvious the result should be the first case. Am i missing something about string comparison in oracle?
You are checking strings againts an empty string, thus having issues; in Oracle you'd better check if your string is not null:
SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' is not null
THEN '7C54D3E133830A78E040A8C010014B7D'
WHEN 'e84a4433966c4b8996ce34905acff63d' is not null
THEN 'e84a4433966c4b8996ce34905acff63d'
WHEN '7faa9126b1c6412fa58375ab2b2be1db' is not null
THEN '7faa9126b1c6412fa58375ab2b2be1db'
ELSE NULL
END
FROM DUAL
About the way Oracle treats empty string and null, here you find something more
An example:
select q'['' = '']' , case when '' = '' then 'YES' else 'NO' end from dual union all
select q'['' is null]' , case when '' is null then 'YES' else 'NO' end from dual union all
select q'['' = null ]' , case when '' = null then 'YES' else 'NO' end from dual union all
select q'[null = null]' , case when null = null then 'YES' else 'NO' end from dual union all
select q'[null is null]' , case when null is null then 'YES' else 'NO' end from dual union all
select q'['' != '']' , case when '' != '' then 'YES' else 'NO' end from dual union all
select q'['' is not null]' , case when '' is not null then 'YES' else 'NO' end from dual union all
select q'['' != null ]' , case when '' != null then 'YES' else 'NO' end from dual union all
select q'[null != null]' , case when null != null then 'YES' else 'NO' end from dual union all
select q'[null is not null]', case when null is not null then 'YES' else 'NO' end from dual
gives:
'' = '' NO
'' is null YES
'' = null NO
null = null NO
null is null YES
'' != '' NO
'' is not null NO
'' != null NO
null != null NO
null is not null NO
In a word, the only check you can rely on, when talking about NULL, is:
IS [NOT] NULL
Well, the reason of such a behaviour is that Oracle doesn't have empty string, but null; that's why
select case when 'abc' != ''
....
is actually
select case when 'abc' != null
and since anything != null is null (true, false, null boolean logic) all the when don't return true and else is executed.
The right syntax is
SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' IS NOT NULL
THEN '7C54D3E133830A78E040A8C010014B7D'
WHEN 'e84a4433966c4b8996ce34905acff63d' IS NOT NULL
THEN 'e84a4433966c4b8996ce34905acff63d'
WHEN '7faa9126b1c6412fa58375ab2b2be1db' IS NOT NULL
THEN '7faa9126b1c6412fa58375ab2b2be1db'
ELSE NULL
END
FROM DUAL

Returning Null Value instead of 'NOT UPDATED'

SELECT top 1 'Uploaded_Date' =
CASE isnull(Uploaded_Date,'')
WHEN Uploaded_Date THEN 'NOT UPDATED'
else uploaded_date
END
FROM ABC
or
SELECT top 1 'Uploaded_Date' =
CASE isnull(Uploaded_Date,0)
WHEN 0 THEN 'NOT UPDATED'
else uploaded_date
END
FROM ABC
when the column Uploaded_date is null or empty it is supposed to return NOT UPDATED but instead NULL is get returned..!
Thanks in Advance
Try with the below query.
SELECT top 1
CASE WHEN (Uploaded_Date IS NULL or LTRIM (RTRIM (isnull(Uploaded_Date,'')))='NULL')
THEN CAST('NOT UPDATED' AS VARCHAR(50))
ELSE CAST(uploaded_date AS VARCHAR(50)) END as 'Uploaded_Date'
FROM ABC
You are trying to set an int value to Uploaded_Date which is a varchar(50).Instead of storing int 0 store '0' i.e varchar and compare in the case statement.It should work.
SELECT top 1 'Uploaded_Date' =
CASE isnull(Uploaded_Date,'0')
WHEN '0' THEN 'NOT UPDATED'
else uploaded_date
END
FROM ABC

Optimizing a Postgres query

I have following query
SELECT
ca.sfid,
CASE WHEN p.Name IS NOT NULL THEN p.Name ELSE '' END AS Property,
CASE WHEN uc.Name IS NOT NULL THEN uc.Name ELSE '' END AS UnitofInterest,
CASE WHEN fp.Name IS NOT NULL THEN fp.Name ELSE '' END AS FloorplanofInterest,
CASE WHEN ca.Status IS NOT NULL THEN ca.Status ELSE '' END AS Status,
CASE WHEN ca.Origin IS NOT NULL THEN ca.Origin ELSE '' END AS Origin,
CASE
WHEN ca.IC_Call_Answered_by_AH__c = 'true' THEN 'Anyone Home'
ELSE 'Property'
END AS AnswerBy,
CASE WHEN ca.CaseNumber IS NOT NULL THEN ca.CaseNumber ELSE '' END AS CaseNumber,
CASE WHEN ca.Ad_Source_Type__c IS NOT NULL THEN ca.Ad_Source_Type__c ELSE '' END AS Source,
CONCAT(c.FirstName,' ',c.LastName) AS contactname,
CASE WHEN (c.Phone IS NOT NULL OR c.Phone != '' ) THEN c.Phone ELSE '' END AS Phone,
CASE WHEN c.MobilePhone IS NOT NULL THEN c.MobilePhone ELSE '' END AS Mobile,
CASE WHEN c.Email IS NOT NULL THEN c.Email ELSE '' END AS Email,
CASE WHEN c.most_recent_military_pay_grade__c IS NOT NULL THEN c.most_recent_military_pay_grade__c ELSE '' END AS MilitaryPayGrade,
CASE WHEN ca.Price_Quoted_1__c IS NOT NULL THEN ca.Price_Quoted_1__c ELSE '' END AS "price/termquoted",
CASE WHEN ca.Move_in_Date__c IS NOT NULL THEN to_char(ca.Move_in_Date__c AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY') ELSE '' END AS MoveinDate,
CASE WHEN ca.Of_Occupants__c::varchar IS NOT NULL THEN ca.Of_Occupants__c::varchar ELSE '' END AS "#occupants",
CASE WHEN ca.Bed_Count_Pref__c IS NOT NULL THEN ca.Bed_Count_Pref__c ELSE '' END AS BedCountPref,
CASE WHEN ca.Bath_Count_Pref__c IS NOT NULL THEN ca.Bath_Count_Pref__c ELSE '' END AS BathCountPref,
CASE WHEN ca.Pet_Count__c::varchar IS NOT NULL THEN ca.Pet_Count__c::varchar ELSE '' END AS "#pets",
CASE WHEN ca.Pet_Type__c IS NOT NULL THEN ca.Pet_Type__c ELSE '' END AS PetTypes,
CASE WHEN ca.Breed__c IS NOT NULL THEN ca.Breed__c ELSE '' END AS Breed,
CASE WHEN ca.Pet_Name__c IS NOT NULL THEN ca.Pet_Name__c ELSE '' END AS PetName,
CASE
WHEN (ca.Desired_Rent_Start__c IS NOT NULL AND ca.Desired_Rent_Range_End__c IS NOT NULL) THEN CONCAT(ca.Desired_Rent_Start__c,' - ',ca.Desired_Rent_Range_End__c)
ELSE ''
END AS DesiredRentRange,
CASE WHEN ca.Desired_Lease_length__c::varchar IS NOT NULL THEN ca.Desired_Lease_length__c::varchar ELSE '' END AS DesiredLeaseLength,
CASE WHEN ca.Reason_for_Moving__c IS NOT NULL THEN ca.Reason_for_Moving__c ELSE '' END AS ReasonforMoving,
CASE WHEN ca.Notes__c IS NOT NULL THEN ca.Notes__c ELSE '' END AS Notes,
CASE WHEN ca.Reasons_For_Not_Setting_a_Showing__c IS NOT NULL THEN ca.Reasons_For_Not_Setting_a_Showing__c ELSE '' END AS ReasonforNotSettingShowing,
CASE WHEN ca.CreatedDate IS NOT NULL THEN to_char(ca.CreatedDate AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY HH:MI AM') ELSE '' END AS "date/timeopened",
CASE
WHEN app.appointment_date__c IS NOT NULL THEN CONCAT(to_char(app.appointment_date__c AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY'),' ',app.from__c,'-',app.to__c)
ELSE ''
END AS "appointmentdate/time",
CASE WHEN ca.Yardi_Guest_Card_ID__c IS NOT NULL THEN ca.Yardi_Guest_Card_ID__c ELSE '' END AS PMSGuestCardID,
rank() OVER (PARTITION BY ca.contactid, ca.property_of_interest__c ORDER BY ca.createddate DESC)
FROM
salesforce.Case ca
INNER JOIN salesforce.Contact c on ca.ContactId = c.sfid AND c.accountId = ca.accountId
LEFT JOIN salesforce.Appointment__c app ON ca.sfid = app.case__c
LEFT JOIN salesforce.Property__c p ON p.sfid = ca.Property_of_Interest__c AND p.account__c = ca.accountId
LEFT JOIN salesforce.Floor_Plan__c fp ON ca.Floor_Plan_of_Interest__c = fp.sfid AND fp.account__c = ca.accountId
LEFT JOIN salesforce.Unit__c uc ON ca.Unit_of_Interest__c = uc.sfid AND uc.account__c = ca.accountId
WHERE
ca.Guest_Card_Status__c = 'Sent via Workflow'
AND ca.accountId = '001i000000ESO3CAAX'
AND to_char(to_char(ca.createddate AT TIME ZONE 'UTC' AT TIME ZONE 'US/Pacific','YYYY-MM-DD HH24:MI:SS')::date, 'YYYY-MM-DD') BETWEEN '2016-06-02' AND '2016-07-02'
AND to_char(c.Last_Activity__c AT TIME ZONE 'US/Pacific', 'YYYY-MM-DD') BETWEEN '2016-03-04' AND '2016-07-02'
AND ( ca.Status IN ( 'Inquiry', 'Showing Set', 'Showing Completed', 'Application Pending', 'Resident' ) )
AND ( ca.IC_Call_Answered_by_AH__c IN ( 'false', 'true' ) )
AND ( ca.origin IN ( 'Phone', 'Email', 'Voicemail', 'Chat', 'Walk-In', 'Web' ) OR ca.origin IS NULL OR ca.origin = '' ) LIMIT 20 OFFSET 0
And following is the query plan for it
We have indexes on following columns:
AccountId
createddate
Status
Origin
Using PostgreSQL.
But query is taking long time to run. Can you please suggest any optimization in it?
Thanks
Without knowing much about your data set and being unable to read the screenshot of the query plan, I see a couple easy improvements you can make.
First, your use of the indexed columns accountId, status, and origin columns is fine. However, your usage of the createddate column is flawed. By converting the column to a string and then performing a comparison after it has been converted to a string, you are no longer using the index -- Postgres must perform a full scan and run two costly to_char conversions.
Qualify on your createddate column with a comparison native to the datatype of the column.
For example, if the datatype of createdate is timestamp, then you could qualify on it like this:
AND ca.createdate BETWEEN '2016-06-02'::timestamp AND '2016-07-02'::timestamp
This will use the index and it will perform much better.
Second, make sure that you've created one index that uses all four of the columns you've listed. If you have created four separate indexes for each of those columns, then you are not realizing the full performance gains possible from indexing. An index that uses all four of the columns will allow Postgres to progressively narrow down the result set with each column. If you have four separate indexes, then Postgres can only narrow down the result set with one column.

CASE statement giving wrong results inside my stored procedure

I have a case inside my stored procedure which I use before executing the data.
DECLARE #Setup nvarchar(50)
SELECT
#ZipCode = CASE
WHEN REPLACE(#ZipCode, '0', '') = ''
THEN NULL ELSE #ZipCode
END,
#ZipCodeEND = CASE
WHEN REPLACE(#ZipCodeEND, '0', '') = ''
THEN NULL ELSE #ZipCodeEND
END,
SELECT
#Setup = CASE WHEN (LEN(ISNULL(#ZipCode, ''))) > 0 THEN '1' ELSE '0' END +
CASE WHEN (LEN(ISNULL(#ZipCodeEND,''))) > 0 THEN '1' ELSE '0' END
IF ISNULL(#ID, 0) = 0
BEGIN
INSERT INTO dbo.MapToStaticValuesTable(ZipCode, ZipCodeEND, Setup)
VALUES(#ZipCode, #ZipCodeEND, #Setup)
END
The problem here is even if zipcode and zipcodeEnd are empty and set to null after being saved into the table I keep getting the value "11" instead of getting "00".
Now if I do the same example with nvarchar values it would work, but since ZipCode and ZipCodeEnd are set to int it's acting weird.
It is acting weird because you are using string functions on integers. Not sure what you are trying to achieve with your code but I'm sure it can be done just by checking the values as integers.
I guess this could be what you are looking for.
select case when nullif(#ZipCode, 0) is null then '0' else '1' end +
case when nullif(#ZipCodeEND, 0) is null then '0' else '1' end
One example of weird
select isNull(#ZipCode, '')
return 0 if #ZipCode is null.

Check if condition before when in case statement

Case stud.Status
when 'N'then 'NA'
end
How to add following condition before when statement above
IF #ID is not equal to 2. That is I want to assign 'NA' only when also the id <> 2 plus the above condition.
EDIT: Full Query
Case Stud.Status
when #ID = 2 AND Stud.Status = 'N' then 'To Be Submitted'
when 'N'then 'N/A'
else isnull(Stud.Status, '')
end
Like this:
CASE
WHEN #ID <> 2 AND stud.Status ='N' THEN 'NA'
END
This is the other form of the CASE expression.
Note that: The CASE expression has two forms:
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.
Update: Try this instead:
'StudStatus' =
CASE
WHEN #ID = 5 AND Stud.Status = 'N' THEN 'To Be Submitted'
WHEN Stud.Status = 'N' THEN 'N/A'
ELSE ISNULL(Stud.Status, '')
END
try this
Case stud.Status
when 'N' and #id<>2 then 'NA'
end
if #ID <> 2
begin
Case stud.Status
when 'N'then 'NA'
end
end