Some SQL bug fixes