select
hp.id as invest_profile_id,
hp.name as invest_profile_name
from prod_line.pens_product_param_pl p_i
join prod_line.param_pl def_i
on def_i.id = p_i.param_pl_id
join prod_line.table_param_pl_invest_profile ip
on ip.pens_product_param_pl_id = p_i.id
join prod_line.hb_invest_profile hp
on hp.id = ip.hb_invest_profile_id
where p_i.pens_product_id = 8977
and def_i.brief = 'ИнвестПрофиль'
and (
ip.validity_period_from is null
or current_date >= ip.validity_period_from
)
and (
ip.validity_period_to is null
or current_date <= ip.validity_period_to
)
order by ip.validity_period_from desc nulls last
limit 1;