Fix potential sql bugs