Search code examples
sqlpostgresqlplpgsql

How to use array variable in my sql statement in plpgsql


total nube in PL/PGSQL. I would like to define an array of strings and then used that in my SELECT... WHERE In statement but can't seem to get it to work, help appreciated.

DO $$
DECLARE 
    testArray varchar[] := array['john','lisa'];    
    ids integer[];
BEGIN
    ids = array(select id from tableA where name in (testArray));
    -- this works
    ids = array(select id from tableA where name in ('john','lisa'));
END $$;

Solution

  • You can use any near of testarray.

    DO $$
    DECLARE 
        testArray varchar[] := array['john','lisa'];    
        ids integer[];
    BEGIN
        ids = array(select id from tableA where name = any(testArray));
        -- this works
        ids = array(select id from tableA where name in ('john','lisa'));
    END $$;