I'm trying to select the first name and last name and ONLY select the middle name when there is one. The logic of my query makes sense. Every time I am extracting the first name, last name, and birth. Only when the middle is not null I want the middle name to be extracted as well. I get a syntax error when I run this query.

enter image description here

SELECT first, last, birth
    WHEN middle IS NOT NULL THEN (SELECT middle FROM students)
FROM students   

1 Answer 1


The CASE is the fourth column in the select, so it needs a , after birth. That will fix the syntax error. It may not, however, give you the result you are looking for :)

The number of columns returned by a query is fixed. A column cannot be optionally selected. Assuming this is for the roster problem, a different approach would be to select middle in the query, and make the decision in the python code on how to output it.

It can be done in the sql using a combination of the concatenation operator

The || operator is "concatenate" - it joins together the two strings of its operands.
the || concatenation operator [always] evaluates to either NULL or a text value.

and a CASE statement. I leave it to you to experiment with that approach.

  • Could I get a hint for getting the result I want? @DinoCoderSaurus
    – Bob
    Jul 25, 2020 at 2:15
  • more info added to answer. Jul 25, 2020 at 16:22
  • Thank you so much!
    – Bob
    Jul 26, 2020 at 17:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .