bug fix + sql optimization