fix sql logic