If I have the table
SELECT (Firstname || '-' || Middlename || '-' || Surname) AS example_column
FROM example_table
This will display Firstname-Middlename-Surname e.g.
John--Smith
Jane-Anne-Smith
The second one (Jane’s) displays correct, however since John doesn’t have a middlename, I want it to ignore the second dash.
How could I put a sort of IF Middlename = NULL statement in so that it would just display John-Smith
Here would be my suggestions:
PostgreSQL and other SQL databases where
'a' || NULL IS NULL
:Oracle and other SQL databases where
'a' || NULL = 'a'
: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 aNULL
yields aNULL
or not.Generally
COALESCE
is most concise for PostgreSQL-style empty string handling, andDECODE (*VALUE*, NULL, ''...
for Oracle-style empty string handling.If you use Postgres,
concat_ws()
is what you are looking for:SQLFiddle: http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8812
To treat empty strings or strings that only contain spaces like
NULL
usenullif()
:This may be a viable option:
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.
One solution could be using
case statement
You can use
CASE
statementAs per your sample data I have check for
empty string
. To checkNULL
useMiddlename IS NOT NULL
instead ofMiddlename <> ''
NULLIF
expression reduces blankMiddlename
toNULL
'-'
with aNULL
will always returnNULL
VALUE
expression replacesNULL
s with an empty string_