Fixed bugs with SQL query