Change sql query, and other fixes.