fixed sql code to avoid duplicates