Book Image

PostgreSQL Server Programming - Second Edition

Book Image

PostgreSQL Server Programming - Second Edition

Overview of this book

Table of Contents (21 chapters)
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Adding functionality to add(int, int)


While our function works, it adds nothing in the preceding code just using SELECT A + B. But functions written in C are capable of so much more. So let's start adding some more functionality to our function.

Smart handling of NULL arguments

Notice the use of a STRICT keyword in the CREATE FUNCTION add(int a, int b) in the previously mentioned code. This means that the function will not be called if any of the arguments are NULL, but instead NULL is returned straightaway. This is similar to how most PostgreSQL operators work, including the + sign when adding two integers—if any of the arguments are NULL the complete result is NULL as well.

Next, we will extend our function to be smarter about NULL inputs and act like PostgreSQL's sum() aggregate function, which ignores NULL values in inputs and still produces the sum of all non-null values.

For this, we need to do two things:

  • Make sure that the function is called when either of the arguments are NULL.

  • Handle...