MySQL IF() Function

SQL IF function

IF(condition, value_if_true, value_if_false) returns one value when a condition is true and another when it is false. For more complex branching, see CASE.


SELECT id, name, mark, IF(mark >= 60, 'PASS', 'FAIL') AS result
FROM student
LIMIT 10;

Output:

id name mark Result
1 John Deo 75 PASS
2 Max Ruin 85 PASS
3 Arnold 55 FAIL
4 Krish Star 60 PASS
5 John Mike 60 PASS
6 Alex John 55 FAIL
7 My John Rob 78 PASS
8 Asruid 85 PASS
9 Tes Qry 78 PASS
10 Big John 55 FAIL

Download the student table SQL dump

Syntax

IF(condition, value_if_true, value_if_false)

SQLite IIF() equivalent

Pass or fail from multiple marks

SELECT id, name, social + math + science AS total,
       IF(social + math + science > 200, 'Pass', 'Fail') AS result
FROM student3;

Output:

idnametotalResult
2Max Ruin226Pass
3Arnold170Fail
4Krish Star180Fail
5John Mike230Pass
6Alex John225Pass
7My John Rob208Pass
8Asruid255Pass
9Tes Qry208Pass
10Big John150Fail

Download the student3 table SQL dump

The old version of this example wrapped the row expression in SUM() and grouped by a unique id. That aggregation is unnecessary when the goal is to calculate one row's total.

SELECT id, name, social + math + science AS total
FROM student3;

The earlier examples combine naturally with LIMIT and BETWEEN. Conditional totals also connect to SUM() and COUNT().

Conditional aggregation with IF()

SUM(IF(...)) can count rows that satisfy each condition.

SELECT
  SUM(IF(class = 'Three', 1, 0)) AS three,
  SUM(IF(class = 'Four', 1, 0)) AS four,
  SUM(IF(class = 'Five', 1, 0)) AS five,
  SUM(IF(class = 'Six', 1, 0)) AS six,
  SUM(IF(class = 'Seven', 1, 0)) AS seven
FROM student;

Output:

THREE FOUR FIVE SIX SEVEN EIGHT NINIE
3 9 3 7 10 1 2

COUNT(IF(condition,1,NULL)) is another common pattern because COUNT(expr) ignores NULL.

SELECT
  COUNT(IF(class = 'Three', 1, NULL)) AS three,
  COUNT(IF(class = 'Four', 1, NULL)) AS four,
  COUNT(IF(class = 'Five', 1, NULL)) AS five
FROM student;

Output:

THREE FOUR FIVE SIX SEVEN EIGHT NINIE
3 9 3 7 10 1 2

Grade totals by class

SELECT class,
  SUM(IF(mark < 50, 1, 0)) AS grade_C,
  SUM(IF(mark BETWEEN 50 AND 69, 1, 0)) AS grade_B,
  SUM(IF(mark >= 70, 1, 0)) AS grade_A
FROM student
GROUP BY class;

Output:

classgrade_Cgrade_Bgrade_A
Eight001
Five003
Four054
Nine110
Seven037
Six016
Three012
MySQL IF function return data based on True or False condition matching with GROUP BY and BETWEEN SQL



Subscribe to our YouTube Channel here



plus2net.com
Rajnit Baldaniya

10-02-2018

SELECT id,Mark, CASE WHEN Mark > 35 THEN 'PASS' ELSE 'FAIL' END AS Result FROM marks




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer