Bug Fixes to db query