SQL fixes and testing