fixes to sql logic