Januay 2005 Technical Tip – SQL Queries and Nulls: The COALESCE Function
Special care must be taken when querying a table with fields which can contain nulls, particularly if these fields are used in an arithmetic expression. Most expressions involving fields whose values are null will evaluate to null.
If a field may contain nulls, you will likely want to make use of the coalesce function. Coalesce returns the first argument that is not null. The arguments are evaluated in the order in which they are specified, and the result of the function is the first argument that is not null. The results can be null only if all the arguments can be null, and the result is null only if all the arguments are null. The following example should serve to illustrate and is given without additional comment:
I used MySQL for the examples in this article. For information on getting started with MySQL, see our January 2004 article.
Want to know more about SQL? Give us a call! You can count on Caliber Data Training for top quality mainframe and/or internet programming education.