473,854 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use COALESCE SQL function

13,262 MVP
This is a short tip describing the sql coalesce function.


COALESCE accepts a comma separated list of parameters and returns
the first value that is not null in that list or null if all the arguments are null.
Expand|Select|Wrap|Line Numbers
  1. COALESCE (a1, a2, a3, ..., an)
will return a1 if a1 is not null, a2 if a1 is null but a2 is not null,
a3 if a1, a2 are null but a3 is not null and so on.

The same thing can be achieved by using a CASE. For the snippet above the CASE would be

Expand|Select|Wrap|Line Numbers
  2. WHEN (a2 IS NOT NULL) THEN a2
  3. WHEN (a3 IS NOT NULL) THEN a3
  4. ...
  6. WHEN (an IS NOT NULL) THEN an
Notice that the ELSE NULL at the end ensures that NULL is returned
when all the arguments are null to conform to the coalesce behaviour.
Clearly the coalesce version is much more compact.

Common uses

Preferential selection

  • Usually used when many columns can be used to represent a value but only one should be used at a time.
In this case the parameters are normally specified starting with the most specific or detailed representation.
Expand|Select|Wrap|Line Numbers
  1. SELECT  COALESCE (name, description) as Product FROM Products 
will show the description only if the name is null.
Optional parameters

  • Coalesce can also be used to provide a way of passing optional parameters.
Normally for a parameter say $P you would do
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM Products WHERE (name = '$P' OR $P IS NULL)
If the parameter $P is passed as NULL all the products will be selected otherwise only
the product with name $P is selected. With coalesce, this can be done as:
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM Products WHERE (name  LIKE COALESCE($P, '%' ))

This function is an ANSI standard function and so is available in most
RDBMs and generally more advisable to use than RDMS specific
functions (e.g SQL Server's ISNULL) .

Hope this was useful.
Jul 24 '08 #1
1 28826
533 Recognized Expert Contributor
Another good use of COALESCE is in UPDATE statements. To prevent having to resubmit an entire record, you can add a listener for which fields have changed from the underlying data source, and then your update procedure would be similar to the following:
Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE updatemyrecord
  2.     @myparam1 nvarchar(255),
  3.     @myparam2 nvarchar(255),
  4.     @myparam3 nvarchar(255),
  5.     @myparam4 nvarchar(255),
  6.     @recordid int
  7. AS
  8. BEGIN
  9.     UPDATE mytable SET
  10.     MyColumn1 = COALESCE(@myparam1, MyColumn1),
  11.     MyColumn2 = COALESCE(@myparam2, MyColumn2),
  12.     MyColumn3 = COALESCE(@myparam3, MyColumn3),
  13.     MyColumn4 = COALESCE(@myparam4, MyColumn4)
  14. WHERE RecordId = @recordid
  15. END
This prevents the need for submitting every value to the database, just the ones that have changed, and thus helping to prevent accidental loss of data.

Oct 3 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

by: AzGhanv/. | last post by:
Hi, I m searching for some Script / Function ... to find difference in data b/w 2 similar tables (exactly same fields structure) in sql 2000. plz update me asap ! thanks in advance !
by: Edmund Dengler | last post by:
Hi all! I am doing some trigger functions that need to find a tuple in another table. The problem is that this second table is doing some summarization work, and I need nulls to equal each other. Basically, in the trigger I do a: SELECT INTO ... x FROM table1
by: John Greve | last post by:
Any ideas on why my the result 'green' row column DELTA does not yield -1 for? That is not how I expected COALESCE( ... ) to work. Every other row for DELTA (including 'black') comes out the way I expected. Thanks for considering this, John G.
by: Bruno BAGUETTE | last post by:
Hello, I'm trying to build a PL/PGSQL function that will be called by a trigger which will update a table named 'mview_contacts'. That table plays the role of a materialized view. The 'plpgsql' language is installed on that database (there are already several functions inside) but I don't understand why I can't store that function in the database.
by: Simon Windsor | last post by:
Hi Is there a standard postgres method of replacing empty strings. In Oracle, nvl handles nulls and empty strings, as does ifnull() in MySQL, but with postgres coalesce only handles null strings. If, not is the best solution to create a plpgsql function, ie CREATE FUNCTION isEmpty (character varying, character varying) RETURNS
by: Don | last post by:
If I have an SQL query which returns an aggregate of several decimal fields like so: (sum(COALESCE(myDecimal1, 0)+ sum(COALESCE(myDecimal2, 0)+ sum(COALESCE(myDecimal3, 0)) as MyTotal I get an rounded integer in MyTotal. However, if I do the following:
by: db2group88 | last post by:
hi, we are using db2 v8.2 EE on windows, with jcc driver. try to create a join view, after that i check the syscat.columns table, for those decimal field use COALESCE method, all the length become 11 instead of the actual length of the field inside table, can anyone explain this to me ? thank you create view ML101PD.ARJMBAL1 (ARNM05, ARNO01, ARNM01, ARNO07, ARNO08, ARNO09, ARFL17, ARFL03, ARMO12, ARDY12, ARCC12, ARYR12, ARNO15,...
by: davidsavill | last post by:
Hi All, I am migrating a database from Firebird/Interbase to DB2 and have having issues with the stored procedures/functions. I have a number of functions that loop over a FOR loop, each pass it performs some logic on the row and inserts the output data into a temp table. The only point of the insert is so that I can select the data in a RETURN statement at the end of the UDF. In Firebird we could put these results directly into...
by: =?Utf-8?B?R1ROMTcwNzc3?= | last post by:
Hi All, is this the correct way to Coalesce a session var - <%Session("EMPLOYETOKENS") = tokens.Fields.Item(COALESCE(SUM("JBCLTokens"),0)).Value%? Thank you
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.