More sql optimization