10

I have this .sql script:

DO $$
  DECLARE 
    user_list integer[] = (select user_id from user where state = 'ACTIVE');
BEGIN
    CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    select * from accounts where user_account IN (user_list);
    ...

    CREATE CREATE MATERIALIZED VIEW accounts_without_active_users AS
    select * from accounts where user_account NOT IN (user_list);
    ...
END $$;

However I always have this error:

ERROR: cannot cast type integer to integer[]

Also I have tried with the word array before with the same result:

user_list integer[] = array(...)

1 Answer 1

8

You're trying to assign a row set to an array. You can use array_agg() instead.

user_list integer[] = (select array_agg(user_id) from users where state = 'ACTIVE');

That being said this IMHO doesn't really help you with creating your materialized views. Just inline your select

CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    SELECT * FROM accounts WHERE user_account IN (
        SELECT user_id FROM users WHERE state = 'ACTIVE'
    );

or create an active_users view

CREATE VIEW active_users AS SELECT * FROM users WHERE state = 'ACTIVE';

and use it instead

CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    SELECT * FROM accounts WHERE user_account IN (
        SELECT user_id FROM active_users;
    );
1
  • You might get a better plan with WHERE [NOT] EXISTS (SELECT 1 FROM users WHERE users.user_id = accounts.user_account AND user.state = 'ACTIVE'). Try both and see what's better. May 31, 2017 at 6:52

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.