0

i want to use parameters for my dynamic queries. I have a statements like so:

RETURN QUERY EXECUTE 'SELECT * FROM boards AS b WHERE b.slug = $1 AND $2'
USING filter_slug, parent_id_query;

I get a ERROR: argument of AND must be type boolean, not type text

if i do it like this:

RETURN QUERY EXECUTE 'SELECT * FROM boards AS b WHERE b.slug = ''' || filter_slug || ''' AND ' || parent_id_query;

it works though.

I feel like i am missing something / not understanding something. Please help.

2
  • 1
    "x and y" means both x and y must render to some form of boolean expression -- they need to yield either a true or a false. b.slug = $1 is definitely either true or false, but $2 would only do this if it were a boolean. I get the idea parent_id_query is not a boolean... is it a query? If so, you can only pass values to parameters. Parameters don't just do string substitutions. Commented Feb 4, 2019 at 10:48
  • Ah okay. That was helpful. I think i could fix it by only replacing the filter_slug with a parameter and leaving parent_id_query as it was. Thanks. Commented Feb 4, 2019 at 10:53

1 Answer 1

1

What you are missing is how parameters are used. Parameters are not macros that replace arbitrary text inside a SQL statement. Instead, they are literal values assigned to "variables" inside the code. These values are typically numbers, strings, or dates.

In particular, parameters cannot be used for:

  • identifiers (columns names and table names)
  • function names
  • operators
  • SQL keywords
  • general expressions

So, unfortunately, you have to construct that part of the query without a generic parameter (although you can have $2 = $3)

Sign up to request clarification or add additional context in comments.

1 Comment

Or, to put it shorter, you can use a parameter almost anywhere in a SELECT, INSERT, UPDATE` or DELETE statement where you could use a constant (literal).

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.