1

I'd like to use an array as a filter in the query, but also, I need to return all values if no values were provided (by preparedStatement - java).

Something like this:

AND column = any(coalesce(?, column_example::text[]))

The problem is that column_example is a varchar column. How to achieve this need with sql (postgres) ?

Version:

PostgreSQL 11.9 (Ubuntu 11.9-1.pgdg20.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0, 64-bit

2 Answers 2

2

I need to return all values if no values were provided

You could just do:

AND ( ? is null or column = any(?::text[]) )

The casting of the parameter to an array might not be necessary, depending on whether your driver is able to properly pass such datatype. If so:

AND ( ? is null or column = any(?) )
Sign up to request clarification or add additional context in comments.

1 Comment

With this small change -> AND ( ?::text[] is null or column = any(?::text[]) ) the query worked. I am using org.postgresql.Driver from Jdbc.
0

Hmmm . . . how about two separate comparisons?

AND
(column = ? OR ? IS NULL AND column = any(column_example::text[]))

You need to pass the parameter in twice or use a named parameter.

1 Comment

This did not work for me because the column is a varchar, but I'd like to pass an array argument. Also, this gave me the error: ERROR: malformed array literal: "test" DETAIL: Array value must start with "{" or dimension information. SQL state: 22P02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.