Select column, if blank select from another
To select the first non-blank column value, pair COALESCE with NULLIF targeting empty strings, or opt for a CASE statement for scenarios requiring more complex condition handling.
In cases requiring more layered logic, deploy a CASE:
Deep Dive: COALESCE and NULLIF
COALESCE, a SQL standard function, gives the first non-null argument. Married with NULLIF, which offers NULL when two expressions are identical, we effectively interpret a blank string as NULL.
Smart Handling: CASE Statement for Whitespace
In situations where there are more complex conditions involving multiple columns, the CASE statement flexes its muscles. For instance, you might want to replace a field only when it's blank or containing whitespace:
SQL Behavior: ANSI_NULLS and QUOTED_IDENTIFIER
The combination of COALESCE and NULLIF is elegant, but do remember certain database settings can impact results. If you're toying with custom functions in SQL Server, check ANSI_NULLS and QUOTED_IDENTIFIER settings.
Performance vs Readability: Custom Functions
Developing custom functions for checking blank fields can improve code readability, but beware the potential performance impact - each function call adds a little overhead. Remember to balance benefits and potential performance costs.
Was this article helpful?