Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do write IF ELSE statement in a MySQL query

How do I write an IF ELSE statement in a MySQL query?

Something like this:

mysql_query("...(irrelevant code).. IF(action==2&&state==0){state=1}"); 

Then down in my array I should be able to do this:

 $row['state']  //this should equal 1, the query should not change anything in the database,  //just the variable for returning the information 
like image 212
Dylan Cross Avatar asked Jan 06 '12 19:01

Dylan Cross


People also ask

Can we use if condition in MySQL query?

The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.

Can you put an if statement in a query?

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query: SELECT IF(JQ.

Can we write if else in SQL?

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. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.


1 Answers

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0)   THEN       1   ELSE       0   END)  as state from tbl1; 
like image 66
Jack Edmonds Avatar answered Oct 03 '22 00:10

Jack Edmonds