Improved SQL a little. Untested