Tip of the Day : Example Uses of the REVERSE String Function

SQL Server Helper - Tip of the Day

Example Uses of the IIF Logical Function

The IIF logical function introduced in SQL Server 2012 returns one of two values, depending on whether the Boolean expression evaluates to true or false.  The syntax of the IIF logical function is as follows:

IIF ( < boolean_expression >, < true_value >, < false_value > )

The < boolean_expression > parameter is any valid boolean expression.  The < true_value > parameter is the value returned if the < boolean_expression > evaluates to true.  The < false_value > is the value returned if the < boolean_expression > evaluates to false.

Here are sample uses of the IIF logical function

Usage #1 : Convert Numeric Grades to Letter Grades

SELECT [StudentNumber], IIF( [GradePoint] BETWEEN 92 AND 100, 'A',
                        IIF( [GradePoint] BETWEEN 83 AND 91,  'B',
                        IIF( [GradePoint] BETWEEN 74 AND 82,  'C',
                        IIF( [GradePoint] BETWEEN 65 AND 73,  'D',
                        IIF( [GradePoint] < 65, 'F', 'I' ))))) AS [LetterGrade]
FROM [dbo].[Student]

Usage #2 : Calculate Age

SELECT DATEDIFF(YEAR, [BirthDate], GETDATE()) - 
       IIF( MONTH([BirthDate]) > MONTH(GETDATE()) OR 
           (MONTH([BirthDate]) = MONTH(GETDATE()) AND
            DAY([BirthDate])   > DAY(GETDATE())) , 1, 0)
FROM [dbo].[Customer]

Usage #3 : Get Number of Days in a Year

SELECT 365 + IIF((YEAR(GETDATE()) % 4 = 0 AND YEAR(GETDATE()) % 100 != 0) OR
                  YEAR(GETDATE()) % 400 = 0, 1, 0) AS [Number of Days in a Year]

Usage #4 : Get Age Generation

SELECT [CustomerName], IIF(YEAR([BirthDate]) >= 1996, 'Generation Z',
                       IIF(YEAR([BirthDate]) BETWEEN 1980 AND 1985, 'Generation Y',
                       IIF(YEAR([BirthDate]) BETWEEN 1966 AND 1979, 'Generation X',
                       IIF(YEAR([BirthDate]) BETWEEN 1946 AND 1965, 'Baby Boomer Generation',
                       IIF(YEAR([BirthDate]) BETWEEN 1925 AND 1945, 'Silent Generation',
                       IIF(YEAR([BirthDate]) < 1925, 'The Greatest Generation', '')))))) AS [Generation]
FROM [dbo].[Customer]

Usage #5 : Alternating Row Colors

SELECT [ProductName], [UnitPrice], [Quantity], 
       IIF(ROW_NUMBER() OVER( ORDER BY [ProductName] ASC) % 2 = 0, 'white', 'blue')
FROM [dbo].[Product]
ORDER BY [ProductName]
Back to Tip of the Day List Next Tip