I've attempted the below query in postgres 11
CASE
WHEN planning_status::varchar in (('Application Under Consideration'::varchar,'Appeal In Progress'::varchar)) then 'this_label'
WHEN planning_status::varchar = 'Approved' and actual_completion_date is not null then 'that_label'
ELSE 'reject_label'
END
I can't get the query to run, initially getting error on mismatching operator to record type. I also attempted IN (VALUES()) method. The below works:
CASE
WHEN planning_status = 'Application Under Consideration' then 'this_label'
WHEN planning_status = 'Appeal In Progress' then 'this_label'
WHEN planning_status = 'Application Received' then 'this_label'
WHEN planning_status = 'Approved' and actual_completion_date is not null then 'that_label'
ELSE 'reject_label'
END
Is it possible to use the IN query within a CASE WHEN query with strings. The strings are categorical but not stored as such
The problem are the double parentheses:
-- this doesn't work:
SELECT CASE WHEN 1 IN ((1, 2)) THEN 'works' ELSE 'weird' END;
ERROR: operator does not exist: integer = record
LINE 1: SELECT CASE WHEN 1 IN ((1, 2)) THEN 'works' ELSE 'weird' END...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
-- this works:
SELECT CASE WHEN 1 IN (1, 2) THEN 'works' ELSE 'weird' END;
case
═══════
works
(1 row)
The reason is that in the first statement, the inner parentheses are forming a composite type (record) with two elements, and PostgreSQL doesn't know how to compare that to the integer 1.
If the = version works, then this should work:
(CASE WHEN planning_status IN ('Application Under Consideration', 'Appeal In Progress', 'Application Received')
THEN 'this_label'
WHEN planning_status = 'Approved' and actual_completion_date is not null
THEN 'that_label'
ELSE 'reject_label'
END)
There should be no need for an explicit type conversion. If this doesn't work, what is the type of planning_status?
Related
I have to update a newly created metadata table (which holds a 1-1 relations with a person table) in PostgreSQL (>=12):
UPDATE public.metadata m
SET print_status =
CASE
WHEN p.print IS NOT NULL THEN 'done'
ELSE 'not done'
END
FROM public.people p
WHERE m.fk_people_id = p.id;
but I face this error:
ERROR: column "print_status" is of type print_statuses but expression is of type text
LINE 18: CASE
^
HINT: You will need to rewrite or cast the expression.
SQL state: 42804
Character: 477
print_statuses is an enum containing ('done', 'doing', 'not done'). And the print_status column of the metadata table is of type print_statuses (it also defaults to 'not done', so I wouldn't need the ELSE part anymore I guess).
It seems I do have to type cast the 'not done' text in the ELSE part of the CASE statement like this for this query to work:
UPDATE public.metadata m
SET print_status =
CASE
WHEN p.print IS NOT NULL THEN 'done'
ELSE 'not done'::print_statuses
END
FROM public.people p
WHERE m.fk_people_id = p.id;
Why do I have to do a type cast here, and not when using a simple UPDATE statement as in:
UPDATE public.metadata m SET print_status = 'not done' FROM public.people p WHERE g.fk_people_id = i.id;
?
My assumption was that it would return a true if that value was numeric (within the isnumeric range) but FALSE if the ISNULL returns 'blah'. Seems like my assumption was off...
I'm using the it in the following way
case when ISNULL(ISNUMERIC(c.npinumber), 'blah') = 1
then c.NPiNUmber
else 'not valid: ' + c.NpiNumber
end as npi
Building on Dhruvesh's answer,
case
when ISNUMERIC(c.npinumber) = 1 then c.NPiNUmber
else 'not valid: ' + c.NpiNumber
end as npi
Will produce NULL anytime NpiNumber is NULL. The reason is that NULL + any string will still return NULL. The solution is to simply use the COALESCE function
case
when ISNUMERIC(c.npinumber) = 1 then c.NPiNUmber
else 'not valid: ' + COALESCE(c.NpiNumber, 'NULL VALUE')
end as npi
select ISNUMERIC(ISNULL(NULL, 'blah')),
ISNUMERIC(ISNULL(1234, 'blah')),
ISNUMERIC(ISNULL('ab', 'blah'))
Returns 0, 1, 0 - so your logic is correct.
When SQL's not behaving I like to simplify my query. Try running the query without your case statement first. If the results look right, then add additional logic.
What collation is your database? It's always a good idea to keep your column names properly cased (I'm looking at that all-lowercase column name over there...).
You don't require ISNULL. ISNUMERIC will return 1 if it's numberic or 0 if it's NULL or non-numeric.
case
when ISNUMERIC(c.NpiNumber) = 1 then c.NPiNUmber
else 'not valid: ' + c.NpiNumber
end as npi
Also as Euric Mentioned you may want to look at your all-lowercase column name.
I am having problems returning a VARCHAR out of a derived column.
Below are extremely simplified code examples.
I have been able to do this before:
SELECT *, message =
CASE
WHEN (status = 0)
THEN 'aaa'
END
FROM products
But when I introduce a Common Table Expression or Derived Table:
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'aaa'
END
FROM CTE_products
this seems to fail with the following message:
Conversion failed when converting the varchar value 'aaa' to data type int.
When I tweak the line to say:
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN '123'
END
FROM CTE_products
It returns correctly.
...
When I remove all the other clauses prior to it, it also works fine returning 'aaa'.
My preference would be to keep this as a single, stand-alone query.
The problem is that the column is an integer dataype and sql server is trying to convert 'aaa' to integer
one way
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'aaa' else convert(varchar(50),status)
END
FROM CTE_products
I actually ended up finding the answer.
One of my CASE/WHEN clauses used a derived column from the CTE and that ended up causing the confusion.
Before:
WITH CTE_products AS (SELECT *, qty_a + qty_b as qty_total FROM products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'Status is 0, the total is: ' + qty_total + '!'
END
FROM CTE_products
Corrected:
WITH CTE_products AS (SELECT *, qty_a + qty_b as qty_total FROM products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'Status is 0, the total is: ' + CAST(qty_total AS VARCHAR) + '!'
END
FROM CTE_products
I ended up removing WHEN/THEN clauses within the CASE statement right afterwards to see if it was a flukey parentheses error when I realized that in the absence of any of the WHEN/THEN clauses that included the derived column from the CTE, it was able to return VARCHAR.
Can anyone tell me how to translate the following T-SQL statement:
SELECT fileld1 = CASE
WHEN T.option1 THEN -1
ELSE
CASE WHEN T.option2 THEN 0
ELSE 1
END
END
FROM Table1 AS T
The point is I need to validate two different options from the table for a single field in the select statement..
I have tried to do somthing with an IF statement in pl/sql, but it just doesnt work for me:
SELECT IF T.option1 THEN -1
ELSE IF T.option2 THEN 0
ELSE 1
END
FROM Table1 AS T
I am not actually sure how to write IF statement inside the SELECT statement..
And also, I need to do it INSIDE the select statement because I am constructing a view.
Use:
SELECT CASE
WHEN T.option1 = ? THEN -1
WHEN T.option2 = ? THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
I can't get your original TSQL to work - I get:
Msg 4145, Level 15, State 1, Line 4
An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
...because there's no value evaluation. If you're checking if the columns are null, you'll need to use:
SELECT CASE
WHEN T.option1 IS NULL THEN -1
WHEN T.option2 IS NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
...or if you need when they are not null:
SELECT CASE
WHEN T.option1 IS NOT NULL THEN -1
WHEN T.option2 IS NOT NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
CASE expressions shortcircuit - if the first WHEN matches, it returns the value & exits handling for that row - so the options afterwards aren't considered.
If I remember correctly, PL/SQL also supports the case. You just would have to move the column alias from "field1=" before the expression to "AS filed1" after the expression.
I have a huge query which uses case/when often. Now I have this SQL here, which does not work.
(select case when xyz.something = 1
then
'SOMETEXT'
else
(select case when xyz.somethingelse = 1)
then
'SOMEOTHERTEXT'
end)
(select case when xyz.somethingelseagain = 2)
then
'SOMEOTHERTEXTGOESHERE'
end)
end) [ColumnName],
Whats causing trouble is xyz.somethingelseagain = 2, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.
SELECT
CASE
WHEN xyz.something = 1 THEN 'SOMETEXT'
WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
ELSE 'SOMETHING UNKNOWN'
END AS ColumnName;
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
declare #n int = 7,
#m int = 3;
select
case
when #n = 1 then
'SOMETEXT'
else
case
when #m = 1 then
'SOMEOTHERTEXT'
when #m = 2 then
'SOMEOTHERTEXTGOESHERE'
end
end as col1
-- n=1 => returns SOMETEXT regardless of #m
-- n=2 and m=1 => returns SOMEOTHERTEXT
-- n=2 and m=2 => returns SOMEOTHERTEXTGOESHERE
-- n=2 and m>2 => returns null (no else defined for inner case)
If logical test is against a single column then you could use something like
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
More information - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017