modified raw sql to keep highest id; separate query for null target