I am trying check if a value is null if so the select null else cast to numeric, but it throws an error. This is actually part of an insert statement
INSERT into someTable(name,created,power)
SELECT 'xyz',now(),
case when :power ='null' then NULL else cast(:power as numeric) end from abc
error that I get is
Error: ERROR: invalid input syntax for type numeric: "null"
:power is a variable that can be given any value using java code. If I give a value of null it give an error.
In code I get the following error from the java stack trace
org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to numeric
Error
No error
Explanation
If you build a query string, the expression
cast('null' AS numeric)or simply'null'::numericalways raises an exception, even in anELSEblock that is never executed, because it isinvalid input syntaxand the exception is raised during the syntax check (like the error message implies), not during execution.A
CASEstatement like you display only makes sense with a parameter or variable not with literals. The second instance of the literal has no connection to the first instance whatsoever after the query string has been assembled.For dynamic SQL like that, you need to check the value before you build the query string. Or you use a function or prepared statement and pass the value as parameter. That would work, too.
More advice after comment:
In your particular case you could check the value in the app and build a query string like this:
You may be interested in a different approach to
INSERTdata from a file conditionally.Use
COPYfor files local to the server or psql’s meta-command\copyfor files local to the client.