Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql IF Else Statement

Not sure how far a sql query can go with if/else statements.

I have a simple SELECT statement:

SELECT amount, transtype FROM transactions

The transtype column is going to be a number.

For example, 1 = sale, 2 = refund, 3 = error, 4 = canceled, 5 = something else.... and so on.

So, nothing complicated. But the list tends to grow for reporting reasons. Which is fine.

For a specific query I'm working on, is there a way to extract that column as one of 2 or three specified numbers or text?

For example, some transtype numbers are a 'loss', while others are a 'gain', and maybe others are 'neutral'.

I'd like to extract that column with only those 3, without using php inside the html table I'm throwing the rows into.

If my explanation is not clear, my apologies. It was hard to spit out.

like image 686
coffeemonitor Avatar asked Nov 14 '10 23:11

coffeemonitor


People also ask

Can I use if else in MySQL?

In MySQL, the IF-THEN-ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.

Can we use if else in query?

Unlike other programming languages, you cannot add an ELSE IF statement within an IF ELSE condition in SQL. This is why you can nest IF ELSE in SQL query statements.

How do you write if/then else in SQL?

IF color = red THEN dbms_output. put_line('You have chosen a red car') ELSE dbms_output. put_line('Please choose a color for your car'); END IF; If the Boolean expression condition evaluates to true, then the if-then block of code will be executed otherwise the else block of code will be executed.


1 Answers

Use the MySQL CASE() function for a fixed number of arguments. If the list is getting big, you should use a second table and join them.

Example:

SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
like image 84
Konerak Avatar answered Oct 14 '22 07:10

Konerak