scribase
SQLSTATE 22012division_by_zeroHTTP 400

Postgres error 22012: division by zero

division by zero

An expression divided by zero.

Common causes

  • Ratios computed over groups where the denominator can be zero, such as conversion rate with zero visits.

How to fix it

  • Wrap the divisor with nullif(divisor, 0) so the result is null instead of an error.
sql
select signups::numeric / nullif(visits, 0) as conversion from daily_stats;

Through a REST API

PostgREST, the REST layer behind supabase-js and Scribase, answers HTTP 400 for this error and returns the SQLSTATE in the code field of the JSON error body.

Questions

What does Postgres error 22012 mean?

22012 is division_by_zero in class 22 (Data Exception). An expression divided by zero.

How do I fix 22012?

Wrap the divisor with nullif(divisor, 0) so the result is null instead of an error.

What HTTP status does a REST API return for 22012?

PostgREST, the REST layer behind supabase-js, answers 400.

Other class 22 errors

  • 22001 value too long for type character varying(n)
  • 22003 integer out of range / numeric field overflow
  • 22007 invalid input syntax for type timestamp / date
  • 22008 date/time field value out of range
  • 22P02 invalid input syntax for type uuid / integer