Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sql
mysql
if
communitycreator

What is IF() in SQL?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The IF() function is a conditional statement. This function returns a value given as a parameter if the condition is true; otherwise, it returns another value given as a parameter.

Figure 1 shows a visual representation of the IF() function.

Figure 1: Visual representation of IF() function

Syntax

IF(condition, valueIfTrue, valueIfFalse)

Parameter

The IF() function takes three parameters:

  • Condition or expression one needs to validate.
  • Value if the expression is true. This can be string or number.
  • Value if the expression is false. This can be string or number.

Return value

The IF() function returns a specified value if the condition is true; otherwise, it returns a different specified value.

Example

-- true value and output string
SELECT IF(2>1,'First value > Second Value', 'First value < Second Value');
-- False value and output string
SELECT IF(1>2,'First value > Second Value', 'First value < Second Value');
-- true value and output number 1:true 0:false
SELECT IF(2>1,1,0);
-- False value and output number 1:true 0:false
SELECT IF(2<1,1,0);

RELATED TAGS

sql
mysql
if
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring