2

I came into a problem in postgres sql function, I need to return all records when the array of integer is empty.

For now I am using dynamic sql to achieve it with if statement checking if the array is empty so don't concat in statement in the query. I want to know if there is another way to achieve it without dynamic sql?

eg using dynamic sql:

CREATE OR REPLACE FUNCTION testme() RETURNS TABLE(Title text) LANGUAGE plpgsql AS $$
DECLARE
one int[];
BEGIN
one:= '{}';

RAISE NOTICE 'value:%', array_length(one,1);
if array_length(one,1) > 0 THEN
RETURN QUERY EXECUTE 'SELECT  "Title" from "Tickets" where "TicketID"  
IN(SELECT(UNNEST($1)));'  USING one;
ELSE
RETURN QUERY EXECUTE 'SELECT "Title"  from "Tickets"';

END IF;
END
$$;
SELECT testme();

1 Answer 1

5
select  "Title"
from "Tickets"
where
    "TicketID" = any (one)
    or
    cardinality(one) = 0;

cardinality returns 0 for an empty array whereas array_length returns null

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

3 Comments

Hmm - never noticed that about array_length before. Presumably to do with not knowing how many dimensions any particular array could have. Thanks Clodoaldo.
thanks it worked!!! btw is it true that any have bad performance vs in i showed in my answer? also the answer works with IN(SELECT(UNNEST(one)))
@duduhayo They should behave the same.

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.