Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using If else in SQL Select statement

Tags:

sql

sql-server

I have a select statement which will return 2 columns.

ID | IDParent 

Then in my program I have to test if IDParent is < 1 then use ID ELSE use IDParent

Is there a way to use an If Else like condition in SQL to return only single value?

like image 935
user160820 Avatar asked Nov 23 '12 09:11

user160820


People also ask

Can we use IF ELSE in SQL query?

In MS SQL, IF…ELSE is a type of Conditional statement. Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed.


2 Answers

you can use CASE

SELECT   ...,          CASE WHEN IDParent < 1 THEN ID ELSE IDPArent END AS ColumnName,          ... FROM     tableName 
like image 95
John Woo Avatar answered Sep 22 '22 15:09

John Woo


Here, using CASE Statement and find result:

select (case when condition1 then result1              when condition2 then result2              else result3              end) as columnname from tablenmae: 

For example:

select (CASE WHEN IDParent< 1 then ID               else IDParent END) as columnname from tablenmae 
like image 45
jainvikram444 Avatar answered Sep 19 '22 15:09

jainvikram444