building sql query logic