Function Reference

IF

PostgreSQL equivalent:

Returns one of two values depending on whether the condition is true.

MySQL 8.1
IF(condition, value_if_true, value_if_false)

Parameters

conditionBOOLEAN
Condition to check
value_if_true
Value if the condition is true
value_if_false
Value if the condition is false or NULL

Return value

value_if_true or value_if_false; a condition equal to NULL or 0 counts as false

Examples

Choosing by a condition

MySQL 8.1
SELECT IF(10 > 20, 'yes', 'no') AS result;
result
no

Label by birth year

MySQL 8.1
SELECT member_name,
	birthday,
	IF(
		YEAR(birthday) < 1980,
		'before 1980',
		'since 1980'
	) AS born
FROM FamilyMembers;
member_namebirthdayborn
Headley Quincey1960-05-13before 1980
Flavia Quincey1963-02-16before 1980
Andie Quincey1983-06-05since 1980
Lela Quincey1985-06-07since 1980
Annie Quincey1988-04-10since 1980
Ernest Forrest1961-09-11before 1980
Constance Forrest1968-09-06before 1980
Wednesday Addams2005-01-13since 1980

NULL condition counts as false

MySQL 8.1
SELECT IF(NULL, 'yes', 'no') AS result;
result
no

Details

The condition is true if it is not 0 and not NULL. A string in the condition is converted to a number: IF('abc', 'yes', 'no') returns no. PostgreSQL has no IF function — the same is written as CASE WHEN condition THEN a ELSE b END.

See also

Where to learn