Explain Codes LogoExplain Codes Logo

Avoid division by zero in PostgreSQL

sql
division
nullif
coalesce
Nikita BarsukovbyNikita Barsukov·Aug 17, 2024
TLDR

Avert division by zero with a NULLIF construct in PostgreSQL. This construct changes zeros into NULL:

SELECT numerator / NULLIF(denominator, 0) FROM your_table;

This pattern ensures a resilient division, transforming denominator to NULL whenever it is zero, averting errors.

Crafting precise solution for zero and NULL values

A PostgreSQL database has a diverse set of operations, among which division plays a significant role. While dealing with JOIN operations and aggregate functions, encountering a zero divisor can pose unique challenges. Thus, the NULLIF function, COALESCE and CASE are proficient constructs to handle zeros and NULLs in divisions with sophistication and precision.

Mastery in aggregate functions

While working with aggregates like COUNT, a zero-value can disrupt the results. Hence, consider using the following template to drive error-free outcomes:

/* Here, an attempted division by zero would turn the world into a blackhole. Kidding! It's handled. */ SELECT SUM(revenue) / NULLIF(COUNT(column_name), 0) AS average_revenue FROM sales;

CASE for the rescue

Apply CASE statement as an efficient blueprint for handling possible zero denominator, avoiding division by zero without significantly impacting the outcomes:

/* Division by zero isn't fun, unless you're a mathematician studying singularities */ SELECT numerator / CASE WHEN denominator = 0 THEN 1 ELSE denominator END FROM your_table;

Handle NULL with COALESCE

Complications arise when you are expecting numeric outcomes and encounter potential nulls. Here's where COALESCE steps in for your rescue:

/* Because life gives you NULLs, make it COALESCE! */ SELECT numerator / COALESCE(NULLIF(denominator, 0), 1) FROM your_table;

Practical patterns and edge cases solutions

The tale of avoiding division by zero in PostgreSQL doesn't end with NULLIF, CASE, and COALESCE. There are some other patterns and solutions for tackling edge cases.

Use of "greatest" function

A seamless method to avoid both zero and NULL values as denominators is to use the greatest function:

/* Using 'greatest' to avoid zero, because zero ruins everything */ SELECT numerator / GREATEST(denominator, 1) FROM your_table;

Division inside aggregate functions

In an aggregate function like SUM, you can turn zero divisors into 1:

/* We promote zero to one, because everyone deserves a second chance */ SELECT SUM(CASE WHEN divisor = 0 THEN 1 ELSE amount END) FROM your_table;

PostgreSQL specific patterns

For those who fancy boolean expressions, PostgreSQL provides a unique trick:

/* What's the count of zero? ZERO! (clever, right?) */ SELECT SUM(amount) / (count(divisor) + 1 * (count(divisor = 0)::integer)) FROM your_table;

This ensures a safe division by proficiently handling a zero divisor.