Cleaned up SQL query generation.