Optimized query for fetching relative IDs. #1238