Fixed some bugs on SQL queries.