How to perform IF statement in SQL?

Last updated on Sep 19,2019 44.6K Views

How to perform IF statement in SQL?

edureka.co

SQL Server allows you to execute real-time programmatic logic on the values within your query. Based on these logical evaluations, you can generate values as part of the returned data set. In this blog, you will learn how to implement if statement in SQL with examples. Below are the topics covered in this blog –

IF condition in SQL

IF() function is passed with two parameters, one for true and other for false. The function returns one value if a condition is TRUE, and another value if the condition is FALSE.

Syntax for IF statement in SQL:

IF(condition, value_if_true, value_if_false)

 Parameter Values

condition

Required. The value to test

value_if_true

Optional. The value to return if condition is TRUE

value_if_false

Optional. The value to return if condition is FALSE

If Condition Integer Examples 

Example 1:

Return 0 if the condition is TRUE, or 1 if the condition is FALSE:

SELECT IF(100<500, 0, 1);

 

Output:

Example 2:

SELECT IF(900<500, 0, 1);

Output:

Moving ahead with IF Statement in SQL, let’s see some String examples.

 

 

 

If condition string examples

Example 3:

Test If condition using Strings

If the two strings are same, the query returns “YES” else it returns “NO”

SELECT IF(STRCMP(“hello”,“learner”) = 0, “YES”, “NO”);

 Output:

Example 4:

SELECT IF(STRCMP(“hello”,“hello”) = 0, “YES”, “NO”);

Output:

With this, we come to an end of this blog on “If statement in SQL”. I hope it added to your knowledge. If you wish to learn more about MySQL and get to know this open-source relational database, then check out our MySQL DBA Certification Training which comes with instructor-led live training and real-life project experience. This training will help you understand MySQL in-depth and help you achieve mastery over the subject.

BROWSE COURSES
REGISTER FOR FREE WEBINAR Analyzing Customer-Product Relationships for Business Growth with Tableau