fixed: sql logic bugs