-- Assign all active wallpaper products assigned to category 1279 (Children) or any of its subcategories, to collection id 246 -- Active is defined as visible = 1, no consideration taken to blacklisting. with active_products_in_children_category as ( select product_id from v_product_category_with_ancestors join "product-products" on product_id = productid and visible = 1 where category_id = 1279 ), active_print_products_in_children_category as ( -- Print products for the active products select product_id, printid, groupid from active_products_in_children_category join "product-printproducts" on product_id = productid ), values_to_insert as ( -- This will add all wallpaper print products select product_id, printid from active_print_products_in_children_category where groupid in (1,3) ) INSERT INTO editorial_collection_products (editorial_page_id, product_id, print_id) SELECT 246, product_id, printid FROM values_to_insert ON CONFLICT DO NOTHING;