Fixed bugs with SQL