totn MariaDB Functions

MariaDB: IF Function

This MariaDB tutorial explains how to use the MariaDB IF function with syntax and examples.

Description

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

Syntax

The syntax for the IF function in MariaDB is:

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

Parameters or Arguments

condition
The value that you want to test.
value_if_true
Optional. It is the value that is returned if condition evaluates to TRUE.
value_if_false
Optional. It is the value that is return if condition evaluates to FALSE.

Note

  • The MariaDB IF function can return either a string or a numeric value, depending on the context of how it is used.

Applies To

The IF function can be used in the following versions of MariaDB:

  • MariaDB 10

Example

Let's look at some MariaDB IF function examples and explore how to use the IF function in MariaDB.

MariaDB IF Function - Returns String Value

Let's look at how to use the IF function in MariaDB to return a string value.

For example:

SELECT IF(5<15, 'yes', 'no');
Result: 'yes'

In this IF function example, the condition is 5<15. If this condition is TRUE, the IF function will return 'yes'. Otherwise, the IF function will return 'no'.

The first IF function example uses a numeric condition. However, you can also use the IF function with a string condition.

For example:

SELECT IF(STRCMP('CheckYourMath.com','TechOnTheNet.com')=0, 'yes', 'no');
Result: 'no'

In this IF function example, the condition uses the STRCMP function to compare 2 strings: STRCMP('techonthenet.com','checkyourmath.com').

If the string 'CheckYourMath.com' is the same as the string 'TechOnTheNet.com', the IF function will return 'yes'. Otherwise, the IF function will return 'no'.

MariaDB IF Function - Returns Numeric Value

This next IF function example shows how you would return a numeric value.

For example:

SELECT IF(6>25, 2, 3);
Result: 3

In this IF function example, the condition is 6>25. If this condition is TRUE, the IF function will return the numeric value 2. Otherwise, if the condition is FALSE, the IF function will return 3.

MariaDB IF Function - Test Column Value

Let's look at an example that uses the IF function to test the value of a column in a table.

For example:

SELECT site_id, site_name, IF(server_name='MyServer', 'Upgrade', 'Do Nothing')
FROM sites;

In this IF function example, the IF function tests the value of the server_name field in the sites table. The IF function will evaluate the condition, server_name='MyServer', for each row in our result set.

So (for each row) if server_name='MyServer', the IF function will return 'Upgrade'. Otherwise, the IF function will return 'Do Nothing'.