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.

COALESCE SQL returns the first non-NULL value

18 June 2020

COALESCE SQL

SQL COALESCE – a function that returns the first defined, i.e. non-NULL value from its argument list. Usually one or more COALESCE function arguments is the column of the table the query is addressed to. Often a subquery is also an argument for a function. This is done when it is impossible to say with certainty that the subquery will return a certain value, for example, 5, “string”, ‘2018-12-09’, etc., rather than a value of NULL. Then this NULL value will be replaced by the next value immediately after it.

Let’s give simple examples without column names or subqueries.

COALESCE (NULL, 7, 9) // Return 7
COALESCE (NULL, 'Not Found') // Return 'Not Found'
COALESCE ('2017-10-20', NULL, '2018-03-08') // Return '2018-03-08'

COALESCE for easy replacement of NULL value

When creating a database table, you can provide default NULL values for a number of columns. Then, if you insert a new row in such a column without inserting any value, its value will be undefined (NULL). However, when outputting data, an undefined value (it can still be called empty) is not always suitable. In such cases the function COALESCE is used.

In the first examples we work with the database of the library and its table “Book in issue” (BOOKINUSE). The operations will refer to the Author (author of the book) and Title (title of the book) columns.

If you want to execute queries to a database from this lesson on MS SQL Server, but this DBMS is not installed on your computer, you can install it using the instruction on this link.

The script for creating a library database, its tables and filling tables with data – in the file by this link.

Example 1. There is a library database and a BOOKINUSE (Book in Issue) table. The table looks like this:

AuthorTitlePubyearInv_NoCustomer_ID
TolstoyWar and Peace20052865
ChekhovCherry Orchard20001731
ChekhovSelected stories201119120
ChekhovCherry Orchard1991565
Ilf and PetrovTwelve chairs1985331
MayakovskyPoems19832120
PasternakDr. Zhivago200669120
TolstoySunday20067747
TolstoyAnna Karenina19897205
PushkinCaptain’s daughter20042547
GogolPlays20078147
ChekhovSelected stories19874205
PushkinEssays, t.11984647
PasternakFavorites200013718
PushkinEssays, t.219848205
NULLScience and Life 9,2018201912718
ChekhovEarly Stories200117131

As you can see, the last line does not contain a certain value of the Author column, since the issued edition is a journal. Let the authors of issued editions with certain inventory numbers be displayed, and none of the fields should be empty. For this purpose, we write a query using the function COALESCE:

SELECT COALESCE (Author, 'Magazine')
AS InUse
FROM Bookinuse
WHERE inv_no IN (25, 81, 127)

For an edition with inventory number 127, the first non-NULL value will be returned – ‘Log’ and the resulting table will look like this:

InUse
Pushkin
Gogol
Magazine

Information systems almost never allow blank lines as a result of a query. If something that was specified in the query fails, the result line should contain 0 if it is a quantity, or “None” if a text response is required, or another suitable result for the data type.

Example 2. Once again we are working with the BOOKINUSE table of the library database. It is necessary to print the number of publications of a certain author that are in issue. In the table we see that there is one book by Pushkin. Checking. Write the following query using the COALESCE function:

SELECT COALESCE ((SELECT COUNT(*))
FROM Bookinuse
WHERE Author="Pushkin"), 0)
AS InUse

The result of this query:

InUse
3

But among the issued publications there are no books by Bulgakov. Checking. We write a similar request, we only change the author:

SELECT COALESCE ((SELECT COUNT(*))
FROM Bookinuse
WHERE Author='Bulgakov'), 0).
AS InUse

The result of this query:

InUse
0

Thus, the function COALESCE returned the first non-NULL value: 0 and instead of an empty string we got a string with the value 0.

COALESCE for alternative selection

Often, some resultant value is based on the values of different columns of the table, depending on the case. Then, as a rule, the column values that do not take part in forming the resulting value are empty. The function COALESCE is used to select the desired column.

Example 3. The company’s database contains a table STAFF, which can be used to calculate the annual income of an employee.

IDLNameSalaryCommSales
1Johnson12300NULLNULL
2BrownNULL60024
3MacGregor1420NULLNULL
4CalvinNULL78018
5Levy11400NULLNULL
6RightNULL800NULL

If the employee receives a fixed salary (Salary), the values of the Comm and Sales columns are empty (NULL). In such a case, the salary should be multiplied by 12 in order to earn annual income.
If an employee receives commissions, the Salary column value is empty (NULL). There may also be cases when an employee has been assigned a commission, but he has not made any transactions. Then the Sales column value is empty (NULL).
In the first case, the COALESCE function returns Salary*12, in the second – Comm*Sales, in the third – 0.
So, to calculate the annual income of employees, we write the following query using the function COALESCE:

SELECT LName,
COALESCE (Salary*12, Comm*Sales, 0)
AS Income
FROM STAFF

The result of the query is the following table:

LNameIncome
Johnson147600
Brown14400
MacGregor170400
Calvin14040
Levy136800
Right0

COALESCE helps avoid computational uncertainty

In table connections, it is often impossible to guess in advance whether all values of a column from one table correspond to a certain value from another table. In case of discrepancy, the value is undefined (NULL). But it is based on this value that additional calculations must be made. Another reason why COALESCE is often used in complex calculations is that it is prohibited to use aggregate functions from an aggregate function, such as SUM(COUNT(*)).

We work with the database “Theatre”. The Play table contains data on productions. Team table – about the roles of actors. The Actor table is about actors. Director’s table is about directors. The table fields, primary and external keys can be seen in the figure below.

COALESCE SQL

COALESCE SQL

Example 4. There is a MainTeam column in the Team table that contains information about whether the role is the main one. If it is, the column value is Y, if it is not, the column value is N. We need a list of actors with names and number of secondary roles.

You’ll need to connect the tables. As we have already noticed, in the combination of the Play (production) and Team (role) tables, some column values may be uncertain because not all actors in each production necessarily have both main and secondary roles. In addition, the sum (SUM) of the number of rows (COUNT(*)) corresponding to a certain actor, which indicates that the role is secondary, must be calculated as the number of secondary roles. However, the use of nested aggregate functions is prohibited. In this case, a query is written using the COALESCE function, the value returned by which is no longer formally a value of the aggregate function:

SELECT a.LName AS Name,
SUM (COALESCE((SELECT COUNT(*))
FROM ACTOR a1
JOIN team t
ON a1.Actor_ID-t.ACTOR_ID
WHERE a1.Actor_ID=a.Actor_ID
AND t.MainTeam='N'.
GROUP BY a1.Actor_ID), 0)) AS NumSecRole
FROM ACTOR a
JOIN team t
ON a.Actor_ID=t.ACTOR_ID
JOIN Play p
ON t.PLAY_ID=p.Play_ID
ORDER BY a.Actor_ID

Coalesce 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...