How to use IF function in SELECT statement in MySQL?

The MySQL IF function returns one value if a condition evaluates to TRUE, or another value if it evaluates to FALSE.

Here is the generic syntax for the IF function:

IF( condition, [value_if_true], [value_if_false] )

For example, we have table class with the score column:

score
1
-1
4
6
-6
-9
0
-4
8

Now you want to get the absolute values of score column

If the score >= 0, then absolute value = score

If the score < 0, then the absolute value = score * -1

SELECT
	IF(score >= 0, score, score * - 1) AS abs_value
	FROM
		class;

The result is:

abs_value
1
1
4
6
6
9
0
4
8

Need a good GUI Tool for MySQL? TablePlus is a modern, native tool with an elegant UI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.


Download TablePlus for Mac.

Not on Mac? Download TablePlus for Windows.

On Linux? Download TablePlus for Linux

Need a quick edit on the go? Download TablePlus for iOS.

TablePlus GUI Tool MySQL