Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Created September 6, 2018 08:05
Show Gist options
  • Save abelcallejo/bf53ed6644f63f86a3ae2db9d3ce095c to your computer and use it in GitHub Desktop.
Save abelcallejo/bf53ed6644f63f86a3ae2db9d3ce095c to your computer and use it in GitHub Desktop.
PostgreSQL function that returns zero for a zero divisor
CREATE FUNCTION safe_divide(numeric, numeric) RETURNS numeric AS $$
SELECT
CASE
WHEN $2 = 0 THEN 0
ELSE $1/$2
END AS quotient; $$
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
/**
Usage
SELECT safe_divide(1,0);
Output: 0
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment