SQL using If Not Null on a Concatenation

后端 未结 8 1762
孤独总比滥情好
孤独总比滥情好 2021-01-01 15:22

If I have the table

SELECT (Firstname || \'-\' || Middlename || \'-\' || Surname)  AS example_column
FROM example_table

This will

8条回答
  •  星月不相逢
    2021-01-01 15:51

    This approach works:

    select first_name || coalesce('-' || middle_name, '') || '-' || last_name 
    from t;
    

    Output:

    |        ?column? |
    |-----------------|
    |      john-smith |
    | jane-anne-smith |
    

    UPDATE

    Live code: http://sqlfiddle.com/#!15/d5a1f/1

    Just as my inkling, someone will give a scenario that is not in the question. So to make it work with empty middle name. Just add a nullif for empty string:

    select first_name || coalesce('-' || nullif(middle_name,'') , '') || '-' || last_name 
    from t;
    

    Output:

    |        ?column? |
    |-----------------|
    |      john-smith |
    |      obi-kinobi |
    | jane-anne-smith |
    

提交回复
热议问题