Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

SQL IIF – function in T-SQL language

25 June 2020

SQL IIF function of T-SQL language

SQL IIF function of T-SQL language, which is designed to simplify the writing of conditional constructions using the well-known expression CASE or operators IF…ELSE…THEN.

IIF is a logical function of T-SQL language, which returns one of two values depending on the result of a logical expression. This function appeared in 2012 version of SQL Server.

IIF syntax

IIF ( boolean_expression, true_value, false_value )

where,

  • boolean_expression is a logical expression. If a non-logic expression is specified, a syntax error will occur;
  • true_value – value which will be returned if boolean_expression has value TRUE;
  • false_value – value which will be returned if boolean_expression has value FALSE.

Thus, the IIF function has 3 parameters, the first parameter specifies a logical expression, the second parameter we write the value to be returned if the logical expression returns TRUE, the third parameter is the value to be returned if the logical expression returns FALSE.

Features of the IIF function

true_value and false_value may have different data types, and the IIF function will return the result with the data type that has the highest priority.

If we consider the internal work of the IIF function, all actions in it are referred to the CASE expression and, thus, the IIF function is the absolute equivalent of the CASE expression, and it is created and applied for faster and easier writing of logical expressions using CASE.

Parameters true_value and false_value can not simultaneously contain values NULL, at least one of these values must be different from NULL, otherwise, ie if you specify NULL for both of these parameters, we get approximately the following error:

Message 8133, level 16, state 1, line 1

At least one of the resulting expressions in the CASE specification must differ from the NULL constant.

Examples of using IIF function in T-SQL

Let us now look at some examples of how IIF works.

Example 1 – Easy to use IIF function

In this example we will specify 1 < 2 as a logical expression, i.e. we will ask 1 less than two, as a result we will get the value of the second parameter, in our case TRUE, as it is obvious that our logical expression returns the truth, i.e. 1 is really less than 2.

 SELECT IIF(1 < 2, 'TRUE', 'FALSE') AS Result;

However, if we only change the logical expression, for example, we specify 1 > 2, then the result will be the value of the third parameter, ie FALSE, as 1 can not be more than 2.

   SELECT IIF(1 > 2, 'TRUE', 'FALSE') AS Result;

Example 2 – Using IIF function with variables

Variables can be used in all parameters of IIF function, in the following example integer variables are substituted in IIF function.

DECLARE @A INT = 5,
           @B INT = 3,
           @true_value INT = 1,
           @false_value INT = 0;

   SELECT IIF ( @A >= @B, @true_value, @false_value ) AS Result;

And in this query we are substituting already text values.

DECLARE @A INT = 5,
           @B INT = 3,
           @true_value VARCHAR(10) = 'A A more than B',
           @false_value VARCHAR(10) = 'A less than B';

   SELECT IIF ( @A > @B, @true_value, @false_value ) AS Result;

Example 3 – Using IIF function with more complex logical expression

As the first parameter, i.e. a logical expression, you can specify more complex expressions that will contain different calculations. For example, in the following example we are not just checking the values of two variables, but the result of their multiplication, in this case we ask if it will be more than 10.

DECLARE @A INT = 5,
           @B INT = 3,
           @true_value INT = 1,
           @false_value INT = 0;
   SELECT IIF ( @A * @B > 10, @true_value, @false_value ) AS Result;

Example 4 – Nested IIF

The IIF function can be used in an expression within another IIF function. For example, in the following SQL query we want to know which category the product belongs to by its name. For this purpose, we first compare the value of the product name with one text value, and then, depending on the result, continue to compare, but only with another text value.

 DECLARE @ProductName VARCHAR(100) = 'Monitor';
   SELECT IIF ( @ProductName = 'Smartphone',
               'Mobile devices',
               IIF( @ProductName = 'Monitor', 'PC Accessories', 'No category')
              ) AS Result;

In this case, the first IIF we have returned FALSE, so we moved to the third parameter, where we have another IIF, and he in turn returned TRUE, so the result is “PC Accessories”.

However, if we specify a value in a variable that doesn’t match the category we need, we get a value of “Without Category”.

 DECLARE @ProductName VARCHAR(100) = 'Desk';
   SELECT IIF ( @ProductName = ''Smartphone',
                'Mobile devices,
                IIF( @ProductName = 'Monitor', 'PC Accessories', 'No category')
              ) AS Result;

Example 5 – Using an IIF function in a table query

The IIF function, like other functions, can be used in a regular SQL query to a table or any other table expression. In other words, you can pass column names to the IIF function as parameters.

In this example, based on the product category, we increase its price.

   SELECT Category,
          ProductName,
          Price,
          Price + IIF(Category = 1, 10, 15) AS TotalPrice
   FROM Goods;

That’s all for today, we have considered the IIF function of T-SQL language, which simplifies the writing of various conditional constructions using CASE.

IIF function in SQL Server

 
Tags: , , , , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...

5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...

The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...

Preamble​​MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...

First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...

Preamble​​Atom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...

Preamble​​MongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...

FlexibilityOne of the most advertised features of MongoDB is its flexibility.  Flexibility, however, is a double-edged sword. More flexibility means more...

Preamble​​SQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...

Preamble​​Writing an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...

  What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....

Preamble​​If you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...