1

How to use CASE appropriately for executing SELECT query based on user input ?

On executing following query :

SELECT 
    CASE WHEN user_input_variable = 'y' THEN        
    (SELECT * FROM table_foo WHERE bar = '6f322766-0ec0-4d24-840f-c857a82a6efe')        

    ELSE
    (SELECT 0)
     END

If the user has selected 'y' then it should return records from the table, else it should return an empty result set.

I am getting error:

Operand should contain 1 column(s)

7
  • 2
    The sub-query must return not more than 1 column. Do a UNION ALL instead of using a case expression. Commented Apr 16, 2019 at 13:25
  • 3
    Please explain the logic behind your query. In terms of pseudo code, it appears that you would always just be executing the SELECT * FROM table_foo. Commented Apr 16, 2019 at 13:27
  • What's the parameter? What's the expected output when the parameter has one value and the other value(s)? Commented Apr 16, 2019 at 13:28
  • The second query SELECT 0 returns a different number of columns than the fist one. Commented Apr 16, 2019 at 13:29
  • @TimBiegeleisen : I have updated the question. If the user has selected 'y' then it should return records from the table, else it should return an empty result set. Commented Apr 16, 2019 at 13:35

2 Answers 2

4

The sub-query must return not more than 1 column. Do a UNION ALL instead.

Note that the number of columns must be the same, that's why you need to select null's in the second select.

SELECT * FROM table_foo WHERE bar = '6f322766-0ec0-4d24-840f-c857a82a6efe')
    and user_input_variable = 'y' 
union all     
SELECT 0, null, null... where user_input_variable <> 'y' 
Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it +1, but I think you've been sitting on this longer than I have :-)
@TimBiegeleisen, I started writing this minutes ago, but had to do some other stuff before finishing it.
I have been using this query (MySQL 5.6.2) for a while, it suddenly stopped working (MySQL 8.0), CASE WHEN '{3}' = 'y' THEN SELECT * FROM transaction_bank_allocation WHERE company_code = '{0}' AND r_trans_id = {1}; ELSE SELECT 3 AS no_bank_alloc_selected; END CASE;
Also, there are multiple when cases in real situation, where there are joins based on the user input
0

You could use the IF condition also.

IF user_input_variable = 'y'
    SELECT * FROM table_foo WHERE bar = '6f322766-0ec0-4d24-840f-c857a82a6efe')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.