• Login

DataSoft Corporation

Select IF Example

The IF system scalar function provides conditional execution based on the truth value of a condition

This expression prints the column header as “Prime1” and amount owed as 2000 where the value of the column amount_owed is 2000 or it prints a 0 if the value of the amount_owed column is not equal to 2000.

SELECT Student_ID, Amount_Owed,
IF (Amount_Owed = 2000, Amount_Owed, Convert(0, SQL_DECIMAL)) “Prime1” FROM Billing

From table Class, the following example prints the value in the Section column if the section is equal to 001, else it prints “xxx” under column header Prime1

Under column header Prime2, it prints the value in the Section column if the value of the section column is equal to 002, or else it prints “yyy.”

SELECT ID, Name, Section, 
IF (Section = '001', Section, 'xxx') “Prime1”, 
IF (Section = '002', Section, 'yyy') “Prime2” 
FROM Class

You can combine header Prime1 and header Prime2 by using nested IF functions. Under column header Prime, the following query prints the value of the Section column if the value of the Section column is equal to 001 or 002. Otherwise, it print “xxx.”

SELECT ID, Name, Section,
IF (Section = '001', Section, IF(Section = '002', Section, 'xxx')) Prime FROM Class
Thursday, 18 April 2019 Posted in Example SQL Statements