0

Is it possible to select different fields inside a SELECT conditionally?

Pseudocode:

CREATE VIE myview AS SELECT
  id,
  IF(signal_field == 1)
     firstname as first,
     lastname as last
  ELSE
     concat(firstname + lastname) as firstlast
  FROM mytable;
  • 1
    you can select different fields but you can't select different number of fields, you can use stored procedure with dynamic sql code of run different selects based on input conditions – Nikita Feb 12 at 11:41
  • The output recordset structure in a view must be static (definite, deterministic). The number of fields and their types cannot be altered. – Akina Feb 12 at 12:05
  • @Akina, yes, there is a mistype in my comment - "dynamic sql code OR run different selects" .. based on flow control :) I propose to use one of these solutions. Dynamic SQL may be easier if you have many parameters. – Nikita Feb 12 at 12:27
1
SELECT
  id,(CASE WHEN signal_field =1 THEN firstname END) as first,
     (CASE WHEN signal_field =1 THEN lastname  END) lastname as last,
     (CASE WHEN signal_field!=1 THEN concat(firstname,lastname) END) as firstlast
FROM mytable;
New contributor
Koteswara Rao is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.