Seaquel
PostgreSQL error code

PostgreSQL error 22004

22004 is the SQLSTATE PostgreSQL reports for null value not allowed, in class 22, Data Exception.

SQLSTATE22004
Condition namenull_value_not_allowed
Class22 — Data Exception

Reproduce it, then fix it

sum() over no rows returns NULL, not 0, and a variable declared NOT NULL refuses it. Wrap the aggregate in coalesce. Run the broken query to see the error, then switch to the fixed one. Edit either freely; every run is rolled back.

DO $$
DECLARE
  total numeric NOT NULL := 0;
BEGIN
  total := (SELECT sum(price) FROM products WHERE id > 1000);
END $$;
DO $$
DECLARE
  total numeric NOT NULL := 0;
BEGIN
  total := (SELECT coalesce(sum(price), 0) FROM products WHERE id > 1000);
END $$;

Source: PostgreSQL documentation, Appendix A