SQL Server INLINE IF ELSE - sql-server

In my table I got a column whose value is whether 0 or 1. If that column is 0 I output the value as 'no'; if 1 I should output as 'yes' for all rows. How can I do this only using SQL statement. Thanks

I understand that this question (which shows up at the top of google results for "sql server inline if") is 2 years old, but with SQL Server 2012, the answers are somewhat outdated. It also appears to be a duplicate of SQL inline if statement type question, but that question (being an even older one), doesn't have an up to date answer either.
In SQL Server 2012 you can use the IIF function:
IIF ( boolean_expression, true_value, false_value )
Example:
SELECT IIF(someColumn = 1, 'yes', 'no')

SQL Server does not have an inline if statement, but it does have an inline case that can be use to accomplish the same.
Case has two forms, one is:
select
case MyFlag
when 1 then 'YES'
when 0 then 'NO'
else 'OOPS'
end
from MyTable
where it's used just like a switch in C-like languages and the other is:
select
case
when MyFlag = 1 then 'YES'
when MyFlag = 0 then 'NO'
-- when some unrelated condition...
else 'OOPS'
end
from MyTable
where it senquentially evaluates a list of conditions and returns the first that is fulfiled.
P.S. The end part is mandatory, and I usually forget that.
It's also usual for a simple case stament to be completely inlined, like
select (case MyFlag when 1 then 'Yes' else 'No' end) as MyFlagDesc

Two possibilities:
(CASE WHEN condition1 THEN Value1 ELSE Value2 END)
or, the most complete solution:
(CASE value_to_check WHEN Value1 THEN Result1 [WHEN ... THEN ...] ELSE OtherResult END)

Something like this:
SELECT
CASE YourColumn
WHEN 0 THEN 'no'
WHEN 1 THEN 'yes'
ELSE 'nothing'
END
FROM dbo.YourTable

I mixed three IIF in one line, I have three variables and I want to know which one is greater than zero but I know the order of priority PersonHomePhoneID , PersonWorkPhoneID and PersonCellPhoneID
IIF(#PersonHomePhoneID > 0 , #PersonHomePhoneID, IIF(#PersonWorkPhoneID > 0 , #PersonWorkPhoneID, IIF(#PersonCellPhoneID > 0 , #PersonCellPhoneID, 0)))
The answer of question :
IIF(column = 1 , 'yes', IIF(column = 0, 'no', ''))

Related

REPLACE NULL WITH 0 when pivot clause is used [duplicate]

I have developed a query, and in the results for the first three columns I get NULL. How can I replace it with 0?
Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
When you want to replace a possibly null column with something else, use IsNull.
SELECT ISNULL(myColumn, 0 ) FROM myTable
This will put a 0 in myColumn if it is null in the first place.
You can use both of these methods but there are differences:
SELECT ISNULL(col1, 0 ) FROM table1
SELECT COALESCE(col1, 0 ) FROM table1
Comparing COALESCE() and ISNULL():
The ISNULL function and the COALESCE expression have a similar
purpose but can behave differently.
Because ISNULL is a function, it is evaluated only once. As
described above, the input values for the COALESCE expression can be
evaluated multiple times.
Data type determination of the resulting expression is different.
ISNULL uses the data type of the first parameter, COALESCE follows
the CASE expression rules and returns the data type of value with
the highest precedence.
The NULLability of the result expression is different for ISNULL and
COALESCE. The ISNULL return value is always considered NOT NULLable
(assuming the return value is a non-nullable one) whereas COALESCE
with non-null parameters is considered to be NULL. So the
expressions ISNULL(NULL, 1) and COALESCE(NULL, 1) although
equivalent have different nullability values. This makes a
difference if you are using these expressions in computed columns,
creating key constraints or making the return value of a scalar UDF
deterministic so that it can be indexed as shown in the following
example.
-- This statement fails because the PRIMARY KEY cannot accept NULL values
-- and the nullability of the COALESCE expression for col2
-- evaluates to NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0) PRIMARY KEY,
col3 AS ISNULL(col1, 0)
);
-- This statement succeeds because the nullability of the
-- ISNULL function evaluates AS NOT NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0),
col3 AS ISNULL(col1, 0) PRIMARY KEY
);
Validations for ISNULL and COALESCE are also different. For example,
a NULL value for ISNULL is converted to int whereas for COALESCE,
you must provide a data type.
ISNULL takes only 2 parameters whereas COALESCE takes a variable
number of parameters.
if you need to know more here is the full document from msdn.
With coalesce:
coalesce(column_name,0)
Although, where summing when condition then 1, you could just as easily change sum to count - eg:
count(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
(Count(null) returns 0, while sum(null) returns null.)
When you say the first three columns, do you mean your SUM columns? If so, add ELSE 0 to your CASE statements. The SUM of a NULL value is NULL.
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
SQL Fiddle Demo
A Simple way is
UPDATE tbl_name SET fild_name = value WHERE fild_name IS NULL
If you are using Presto, AWS Athena etc, there is no ISNULL() function. Instead, use:
SELECT COALESCE(myColumn, 0 ) FROM myTable
Wrap your column in this code.
ISNULL(Yourcolumn, 0)
Maybe check why you are getting nulls
Use COALESCE, which returns the first not-null value e.g.
SELECT COALESCE(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) as Succeeded
Will set Succeeded as 0 if it is returned as NULL.
Add an else to your case statements so that they default to zero if the test condition is not found. At the moment if the test condition isn't found NULL is being passed to the SUM() function.
Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
the issue here is that without the else statement, you are bound to receive a Null when the run status isn't the stated status in the column description. Adding anything to Null will result in Null, and that is the issue with this query.
Good Luck!
by following previous answers I was losing my column name in SQL server db however following this syntax helped me to retain the ColumnName as well
ISNULL(MyColumnName, 0) MyColumnName
For regular SQL, ISNULL(item) can only take one parameter, and thus 90% of these solutions don't work.
I repurposed #Krishna Chavali's answer to make this:
(CASE WHEN (NOT ISNULL(column_name)) THEN column_name ELSE 0 END) AS ColumnName
This will return the value in column_name if it is not null, and 0 if it is null.
UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

Case statement with end = 1 in T/SQL query

I'm hoping somebody can explain the below query to me as I'm not familiar with the syntax:
#[user1] int,
#[user2] varchar(10)
delete
from [table name]
where [id] in (select [id]
from [a diff table name]
where [user1] = #[user1])
and (case
when [user2] = 'some string' then 1
when [table field] = #user2 then 1
else 0
end) = 1
and [other field] = 0
and [other field] = 0
and [other field]= 0
Firstly, I've obviously changed all variable/table names. Apologies if anything isn't clear. I get that the first part is a delete statement where it uses an in statement. That's fine. I also get the last part, with the multiple AND statements adding conditions to the WHERE clause.
It's the case statement I'm struggling with. I've two questions.
What is the else 0 for? Is that attached to the when clause above it, so that if [table field] doesn't = the user2 variable passed in it is set to 0?
What is the end = 1? I've tried googling but haven't found any examples of this form before.
ELSE 0 means that the CASE statement will return 0 if neither of the WHEN statements are matched.
End = 1 is easier to understand if you think of it as
WHERE (CASE .... END) = 1
Your CASE stmt will return either 1 or 0 depends on data in that column.
IF it return 1 then 1=1 and other conditions which specified below will also happen.
IF it return 0 then 0=1 , Remaining conditions won't be considered.

Iff condition Access to SQL syntax

I have an access query that I have recreate in SQL.
Access:
SELECT Columns ,
IIf([Col1]="X",IIf([COL2]<>"XXXX",1,0)) AS NEWCOL1,
IIf([COL2] Not In ("HHH","GGG"),1,0) AS [NEWCOL2],
IIf(([NEWCOL1]=1) Or ([NEWCOL2]=1),1,0) AS NEWCOL3
FROM [TABLE]
WHERE ((([TABLE].COL2)<>"XXXX")) OR ((([TABLE].COL2)<>"HHH" And ([TABLE].COL2)<>"GGG"));
In SQL :
SELECT Columns ,
"NEWCOL1" =
CASE WHEN ([COL1]='X' AND COL2<> 'XXXX') THEN 1
ELSE 0
END,
"NEWCOL2" =
CASE WHEN COL2 NOT IN ('HHH','GGG') THEN 1
ELSE 0
END ,
IIf(([NEWCOL1]=1) Or ([NEWCOL2]=1),1,0) AS NEWCOL3
FROM [TABLE]
WHERE ((([TABLE].COL2)<>'XXXX')) OR ((([TABLE].COL2)<>'HHH' And ([TABLE].COL2)<>'GGG'));
IIf(([NEWCOL1]=1) Or ([NEWCOL2]=1),1,0) AS NEWCOL3
When I use the Newcol1 and newcol2 it throws an error invalid column how could use them maybe in a nested case or iif statement
If you're in SQL 2012, where IIF() is valid, then it looks like the problem is that you don't have an ELSE value for the first outer case:
IIf([Col1]='X',IIf([COL2]<>'XXXX',1,0){,NEED SOME ELSE VALUE HERE}) AS NEWCOL1,
I don't know why this would work in Access. I guess Access must be more "dummy proof" than SQL Server.
To replace your original first IIF with a CASE, you would do this:
CASE WHEN [Col1]='X' THEN
CASE WHEN [COL2]<>'XXXX' THEN 1 ELSE 0 END
END
By not supplying an ELSE for the first condition, if [Col1] does not equal 'X', the statement will return NULL without raising an error.
To handle your most recent request with a CTE, you could do as below:
WITH cte AS (
SELECT
Columns,
CASE WHEN ([COL1]='X' AND COL2<> 'XXXX') THEN 1 ELSE 0 END AS NEWCOL1,
CASE WHEN COL2 NOT IN ('HHH','GGG') THEN 1 ELSE 0 END AS NEWCOL2
FROM [TABLE]
WHERE ((([TABLE].COL2)<>'XXXX')) OR ((([TABLE].COL2)<>'HHH' And ([TABLE].COL2)<>'GGG'))
)
SELECT *, IIf(([NEWCOL1]=1) Or ([NEWCOL2]=1),1,0) AS NEWCOL3
FROM cte;

How do I return a boolean value from a query during condition evaluation?

I need something like this:
select (len(someLongTextColumn)=0) as isEmpty;
The above doesn't work,
any alternatives?
If you cast to bit, then most client code can read it as boolean directly (SQL Server doesn't have a boolean type)
SELECT
CAST(
CASE
WHEN len(someLongTextColumn) = 0 THEN 1 ELSE 0
END AS bit
) as isEmpty;
if you have many in one go, use bit variables like this: Imply bit with constant 1 or 0 in SQL Server
Try this.
SELECT (CASE WHEN LEN(SomeLongTextColumn) = 0 THEN 1 ELSE 0 END) AS IsEmtpy
#gbn has good explanation about how to return boolean.
SQL Server:
SELECT CONVERT(BIT, 1) -- true
SELECT CONVERT(BIT, 0) -- false
In MS SQL 2012 and later, you can use IIF as a shorthand:
select IIF(len(someLongTextColumn) = 0, 1, 0) as isEmpty;

SQL Server 2005 Order BY with an expression

Is there a possibility to order the result by an ORDER clause that contains an expression, something like
SELECT colX0 FROM tbp_name ORDER BY (colX1 IS NOT NULL)
or also a more complex expression ?
UPDATE:
In the meanwhile I have found a possibility to solve the above problem:
ORDER BY (case WHEN colX1 IS NULL THEN 1 ELSE 0 END ) ASC
however the question remains, if there is a possibility to order direct by an expression.
No, SQL Server does not support direct conversion of an expression to true/false.
IMHO, one reason is the 3-valued logic. This has 3 outcomes, not 2, of either column is NULL. The NULL is first in SQL generally, always Server but can be specified last in other RDBMS.
ORDER BY (colX1 = colX2)
Using CASE mitigates this and removes ambiguity
ORDER BY
CASE
WHEN colX1 = colX2 THEN 1
WHEN colX1 <> colX2 THEN 2
ELSE 3 NULL case
END
You have to use CASE as per your update, as well ensuring datatypes match (or at least implicitly convertable) in WHEN clauses.
you can use
ORDER BY CASE WHEN condition= 1 THEN 1 ELSE 2 END
you can order by the ordinal position of the column, if you want to SEE the data that you're sorting by... for example, if you want to order by the 1st column, just say 'ORDER BY 1'. Here is an example where I add an expression in the select clause.. and then I order by it in the order by clause
SELECT colX0,
(case WHEN colX1 IS NULL THEN 1 ELSE 0 END )
FROM tbp_name
ORDER BY 2
You'd need to put it in your select first
SELECT
colX0,
CASE WHEN colX1 IS NOT NULL THEN 0 ELSE 1 END AS [COMPUTED1]
FROM tbp_name
ORDER BY COMPUTED1
It's something like that anyway off the top of my head.
http://www.tizag.com/sqlTutorial/sqlcase.php

Resources