Fixing SQL generation