CASE statement equivalent to if or else-if - sql

In this sql CASE statement:
CASE WHEN col1 = 'X' then 'A'
CASE when col2 = 'Y' then 'B'
else 'C' as result ...
if col1=X, and col2 = Y, will the output be 'A' or 'B' ? i.e. is the CASE statement functioning as an if or an else-if?

The evaluation of cases will terminate on the first one that evaluates to TRUE.

Related

How to update the following multiple columns scenario using Case?

I have seen case being used for updating one column when conditions are different. My requirement is I have to update 2 columns based on same condition.
Conditions are same for both columns but I want to avoid repetitive query condition.
update t1 set col1= case when col3='A' and col4='AA' then 'A1' else 'B1' end
,col2= case when col3='A' and col4='AA' then 'A2' else 'B2' end
In the above query the conditions for update of the col1 and col2 is same but I have to write it fully write case statement for both columns.
Is there any way to combine the case conditions only one time for two columns?
If your case is long and complicated you could do something like this merge, shorten it in source part to a single value:
merge into t1 t
using (select rowid rwd, case when (col3, col4) in (('A', 'AA')) then 1 else 0 end val from t1) s
on (t.rowid = s.rwd)
when matched then update set
col1 = case val when 1 then 'A1' else 'B1' end,
col2 = case val when 1 then 'A2' else 'B2' end
dbfiddle demo

Oracle: CASE conditional STATEMENT in the WHERE Clause is not working?

I have below query with CASE statement and this is trowing "missing keyword error"
Can you please help.
select *
from podConfigKey_Tab PCK
WHERE
CASE WHEN (PCK.Keyid = 'TLMAPIConfigMgr.UseDB'
and PCK.DEFAULTKEYIDVALUE = 'FALSE')
THEN PCK.Keyid = 'TLMAPIConfigMgr.UseDB'
ELSE PCK.Keyid != 'TLMAPIConfigMgr.UseDB'
END;
A case expression returns a single value, not a syntactic construct like a=b. You could, however, emulate this behavior with a series of logical operators:
SELECT *
FROM podConfigKey_Tab PCK
WHERE PCK.DEFAULTKEYIDVALUE = 'FALSE' OR
PCK.Keyid != 'TLMAPIConfigMgr.UseDB'
your query should be something more like as mentioned below (removed the else portion to make the below query work), you need to have predicate after the WHERE clause so that you can match value that is return by the CASE statment
select * from podConfigKey_Tab PCK
WHERE PCK.Keyid =
CASE WHEN (PCK.Keyid = 'TLMAPIConfigMgr.UseDB' and PCK.DEFAULTKEYIDVALUE = 'FALSE') THEN 'TLMAPIConfigMgr.UseDB'
END ;
The Oracle CASE expression (like DECODE) returns a value, but by itself it is not a predicate which can evaluate to TRUE or FALSE. You need to establish some condition such that the value returned by the CASE statement can be evaluated. For example:
with sample_data as
(select 'dog' pet, 'y' has_fur from dual union all
select 'cat', 'y' from dual union all
select 'bird', 'n' from dual)
select *
from sample_data
where (case when has_fur = 'y' then 1 else 0 end) = 1;
SQL Fiddle Example

Select two columns based on the same conditional statement SQL

I have a select statement which resembles something like this
SELECT
CASE WHEN <SOME-CONDN_1> THEN 'value1' ELSE '' ||
CASE WHEN <SOME-CONDN_2> THEN 'value2' ELSE '' ||
CASE WHEN <SOME-CONDN_3> THEN 'value3' ELSE '' AS value_column,
CASE WHEN <SOME-CONDN_1> THEN 'name1' ELSE '' ||
CASE WHEN <SOME-CONDN_2> THEN 'name2' ELSE '' ||
CASE WHEN <SOME-CONDN_3> THEN 'name3' ELSE '' AS name_column
FROM data_table
--<REST OF THE QUERY>
The conditional statement is something like data_table.data_column ILIKE value1 and so on.
Since I'm doing the same conditioning statement twice (and it involves some string matching using ILIKE) I was wondering if I could club them and make it more efficient.
Would the same be possible using SQL statements?
Option 1: not quite sure if this variant of CASE works for PostgreSQL...
select case cond_num when
1 then 'value1'
when 2 then 'value2',
when 3 then 'value3' else null end as value_column,
case cond_num when
1 then 'name1'
when 2 then 'name2',
when 3 then 'name3' else null end as name_column
from (
select data_table.*,
case when <some_condition_1> then 1
when <some_condition_2> then 2
when <some_condition_3> then 3 else 0 end as cond_num
from data_table
) screened_table
;
Option 2:
select case when
cond1 = 1 then 'value1'
when cond2 = 1 then 'value2',
when cond3 = 1 then 'value3' else null end as value_column,
case when
cond1 = 1 then 'name1'
when cond2 = 1 then 'name2',
when cond3 = 1 then 'name3' else null end as name_column
from (
select data_table.*,
case when <some_condition_1> then 1 else 0 as cond1,
case when <some_condition_2> then 1 else 0 as cond2,
case when <some_condition_3> then 1 else 0 as cond3
from data_table
) screened_table
;
Option 3 - note if the conditions are not exclusive may return multiple rows. Will not return rows from data_table in which no conditions are true.
select rslt.name, rslt.value
from data_table, (
select 1 as cond, 'value1' as value, 'name1' as name
union all
select 2 as cond, 'value2' as value, 'name2' as name
union all
select 3 as cond, 'value3' as value, 'name3' as name
) rslt
WHERE (<some_condition_1> and rslt.cond = 1) OR
(<some_condition_2> and rslt.cond = 2) OR
(<some_condition_3> and rslt.cond = 3)
;
Assuming the results are both strings you can use an array to make things simpler.
SELECT a[1],a[2], ...
FROM (SELECT CASE
WHEN <SOME-CONDN_1> THEN ARRAY['value1','name1']
WHEN <SOME-CONDN_2> THEN ARRAY['value2','name2']
WHEN <SOME-CONDN_3> THEN ARRAY['value3','name3']
ELSE '' AS a
FROM ...
);
If the result values are not all the same type you can do the same thing using a ROW() constructor, but you will need to define a type in order to get the values individually "back out of the row".

Quick SQL Syntax Question

I have a standard insert into / select statement that is formatted similar to this:
insert into Table
( ...,
...)
select
field1,
field2,
field3,
field4,
fieldetc
from .... etc
There are three specific fields in the select statement that will need different values selected depending on another field, let's call it checker and the three fields are field2, field3, and field 4. The values will either be a 0 or in the other situation will need a case when. My question is, how do I format an if/else statement so it will work within the select statement? How I have it now is like this:
select
field1data,
if checker = 'A' or checker is null
begin
0,
0,
0,
end
else
begin
case when ... then ... else ... end,
case when ... then ... else ... end,
case when ... then ... else ... end,
end
fieldetcdata
from... etc
This is returning errors. How can I format this so it will work correctly, either selecting zeroes for these three fields or running through my case when statements in the other situation. Thanks!
You'll need to specify case statement for each field separately.
Select field1data,
Case When IsNull(Checker,'A') = 'A' Then 0
When Cond1 Then Whatever1
...
Else ...
End,
Case When IsNull(Checker,'A') = 'A' Then 0
When Cond2 Then Whatever1
...
Else ...
End,
Case When IsNull(Checker,'A') = 'A' Then 0
When Cond2 Then Whatever1
...
ELSE ...
End,
fieldetcdata
From ETC
Take out the IF and the BEGIN/END stuff and it should work. All you need to use is the
CASE COALESCE(checker,'A') WHEN 'A' THEN 0 ELSE alternate_value END
for each conditional value you want to SELECT
EDIT: Using your example:
SELECT
field1data,
CASE WHEN ISNULL(checker) THEN alternate_value1
WHEN checker = 'B' THEN alternate_value11 END,
CASE WHEN ISNULL(checker) THEN alternate_value2
WHEN checker = 'B' THEN alternate_value22 END,
CASE WHEN ISNULL(checker) THEN alternate_value3
WHEN checker = 'B' THEN alternate_value3 END,
fieldetcdata
FROM
TABLE
EDIT2: For multiple conditions, you simply add WHEN clauses.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
Edited based on comments below.
You need to use a CASE statement with multiple WHEN conditions.
SELECT
field1data,
CASE COALESCE(checker, 'A') WHEN 'A' THEN 0 WHEN condition2 THEN ... ELSE ... END,
CASE COALESCE(checker, 'A') WHEN 'A' THEN 0 WHEN condition2 THEN ... ELSE ... END,
CASE COALESCE(checker, 'A') WHEN 'A' THEN 0 WHEN condition2 THEN ... ELSE ... END,
CASE COALESCE(checker, 'A') WHEN 'A' THEN 0 WHEN condition2 THEN ... ELSE ... END,
CASE COALESCE(checker, 'A') WHEN 'A' THEN 0 WHEN condition2 THEN ... ELSE ... END
FROM ...

SQL: Alias Column Name for Use in CASE Statement

Is it possible to alias a column name and then use that in a CASE statement? For example,
SELECT col1 as a, CASE WHEN a = 'test' THEN 'yes' END as value FROM table;
I am trying to alias the column because actually my CASE statement would be generated programmatically, and I want the column that the case statement uses to be specified in the SQL instead of having to pass another parameter to the program.
This:
SELECT col1 as a,
CASE WHEN a = 'test' THEN 'yes' END as value
FROM table;
...will not work. This will:
SELECT CASE WHEN a = 'test' THEN 'yes' END as value
FROM (SELECT col1 AS a
FROM TABLE)
Why you wouldn't use:
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
...I don't know.
I think that MySql and MsSql won't allow this because they will try to find all columns in the CASE clause as columns of the tables in the WHERE clause.
I don't know what DBMS you are talking about, but I guess you could do something like this in any DBMS:
SELECT *, CASE WHEN a = 'test' THEN 'yes' END as value FROM (
SELECT col1 as a FROM table
) q
#OMG Ponies - One of my reasons of not using the following code
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like
Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)')
as XMLTagAlias from Table
It should work. Try this
Select * from
(select col1, col2, case when 1=1 then 'ok' end as alias_col
from table)
as tmp_table
order by
case when #sortBy = 1 then tmp_table.alias_col end asc
I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.
With localView1 as (
select c1,
c2,
c3,
c4,
((c2-c4)*(3))+c1 as "complex"
from realTable1)
, localView2 as (
select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
complex * complex as formula2
from localView1)
select *
from localView2
Nor in MsSql
SELECT col1 AS o, e = CASE WHEN o < GETDATE() THEN o ELSE GETDATE() END
FROM Table1
Returns:
Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.
Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.
However if I change to CASE WHEN col1... THEN col1 it works
If you write only equal condition just:
Select Case columns1 When 0 then 'Value1'
when 1 then 'Value2' else 'Unknown' End
If you want to write greater , Less then or equal you must do like this:
Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then
'value2'
Else
'Unkownvalue' End
From tablename
Thanks
Mr.Buntha Khin
SELECT
a AS [blabla a],
b [blabla b],
CASE c
WHEN 1 THEN 'aaa'
WHEN 2 THEN 'bbb'
ELSE 'unknown'
END AS [my alias],
d AS [blabla d]
FROM mytable
Not in MySQL. I tried it and I get the following error:
ERROR 1054 (42S22): Unknown column 'a' in 'field list'
In MySql, alice name may not work, therefore put the original column name in the CASE statement
SELECT col1 as a, CASE WHEN col1 = 'test' THEN 'yes' END as value FROM table;
Sometimes above query also may return error, I don`t know why (I faced this problem in my two different development machine). Therefore put the CASE statement into the "(...)" as below:
SELECT col1 as a, (CASE WHEN col1 = 'test' THEN 'yes' END) as value FROM table;
Yes, you just need to add a parenthesis :
SELECT col1 as a, (CASE WHEN a = 'test' THEN 'yes' END) as value FROM table;
make it so easy.
select columnnameshow = (CASE tipoventa
when 'CONTADO' then 'contadito'
when 'CREDITO' then 'cred'
else 'no result'
end) from Promocion.Promocion