SQL using If Not Null on a Concatenation

后端 未结 8 1697
孤独总比滥情好
孤独总比滥情好 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:53

    Here would be my suggestions:

    PostgreSQL and other SQL databases where 'a' || NULL IS NULL, then use COALESCE:

    SELECT firstname || COALESCE('-' || middlename, '') || '-' || surname ...
    

    Oracle and other SQL databases where 'a' || NULL = 'a':

    SELECT first name || DECODE(middlename, NULL, '', '-' || middlename) || '-' || surname...
    

    I like to go for conciseness. Here it is not very interesting to any maintenance programmer whether the middle name is empty or not. CASE switches are perfectly fine, but they are bulky. I'd like to avoid repeating the same column name ("middle name") where possible.

    As @Prdp noted, the answer is RDBMS-specific. What is specific is whether the server treats a zero-length string as being equivalent to NULL, which determines whether concatenating a NULL yields a NULL or not.

    Generally COALESCE is most concise for PostgreSQL-style empty string handling, and DECODE (*VALUE*, NULL, ''... for Oracle-style empty string handling.

    0 讨论(0)
  • 2021-01-01 15:56

    This may be a viable option:

    SELECT FirstName || '-' || ISNULL(MiddleName + '-', '') || Surname
    

    Since a NULL concatenated with a string yields a NULL, we can attempt to build our sub-string and replace a NULL with an empty string, which is then concatenated to the next part of the name.

    This assumes that FirstName and Surname are always NOT NULL, but you could apply the same logic to then as well.

    0 讨论(0)
提交回复
热议问题