select ev.* from "EMD"."EMDVersion" ev inner join "EMD"."EMDRegistry" er ON ev."EMDRegistry_id" = er."EMDRegistry_id"
  INNER JOIN lateral (
   select ex_ev."EMDVersion_id" from "EMD"."EMDVersion" ex_ev
   	where ex_ev."EMDVersion_IsReady" = $1 and ex_ev."EMDRegistry_id" = ev."EMDRegistry_id" 
   	and ex_ev."EMDVersion_VersionNum" is not null  
   	order by ex_ev."EMDVersion_VersionNum"  desc limit 1
  ) ev_top_one on true
                                    where ev."EMDVersion_IsReady" = $2
                                     and ev."EMDVersion_id" = ev_top_one."EMDVersion_id"
                                     and ev."EMDVersion_VersionNum" is not null
                                     and (er."EMDRegistry_deleted" is null or er."EMDRegistry_deleted" = 1 )
                                     order by ev."EMDRegistry_id" asc, ev."EMDVersion_VersionNum" desc  
