Best Way to Check For "Empty or Null Value"

Best way to check for empty or null value

The expression stringexpression = '' yields:

TRUE   .. for '' (or for any string consisting of only spaces with the data type char(n))

NULL   .. for NULL

FALSE .. for anything else

So to check for: "stringexpression is either NULL or empty":

(stringexpression = '') IS NOT FALSE

Or the reverse approach (may be easier to read):

(stringexpression <> '') IS NOT TRUE

Works for any character type including char(n). The manual about comparison operators.

Or use your original expression without trim(), which is costly noise for char(n) (see below), or incorrect for other character types: strings consisting of only spaces would pass as empty string.

coalesce(stringexpression, '') = ''

But the expressions at the top are faster.

Asserting the opposite is even simpler: "stringexpression is neither NULL nor empty":

stringexpression <> ''

About char(n)

This is about the data type char(n), short for: character(n). (char / character are short for char(1) / character(1).) Its use is discouraged in Postgres:

In most situations text or character varying should be used instead.

Do not confuse char(n) with other, useful, character types varchar(n), varchar, text or "char" (with double-quotes).

In char(n) an empty string is not different from any other string consisting of only spaces. All of these are folded to n spaces in char(n) per definition of the type. It follows logically that the above expressions work for char(n) as well - just as much as these (which wouldn't work for other character types):

coalesce(stringexpression, '  ') = '  '
coalesce(stringexpression, '') = ' '

Demo

Empty string equals any string of spaces when cast to char(n):

SELECT ''::char(5) = ''::char(5)     AS eq1
, ''::char(5) = ' '::char(5) AS eq2
, ''::char(5) = ' '::char(5) AS eq3;

Result:

 eq1 | eq2 | eq3
----+-----+----
t | t | t

Test for "null or empty string" with char(n):

SELECT stringexpression 
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::char(5))
, ('')
, (' ') -- not different from '' in char(n)
, (NULL)
) sub(stringexpression);

Result:


stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3
------------------+-----------+-------+-------+-----------+-----------+-----------
foo | f | f | f | f | f | f
| t | t | t | t | t | t
| t | t | t | t | t | t
null | null | t | t | t | t | t

Test for "null or empty string" with text:

SELECT stringexpression 
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::text)
, ('')
, (' ') -- different from '' in a sane character types
, (NULL)
) sub(stringexpression);

Result:


stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3
------------------+-----------+-------+-------+-----------+-----------+-----------
foo | f | f | f | f | f | f
| t | t | t | t | f | f
| f | f | f | f | f | f
null | null | t | t | t | t | f

db<>fiddle here

Old sqlfiddle

Related:

  • Any downsides of using data type "text" for storing strings?

Easiest way to check for null and empty string on a TypeScript number

You can simply use typeof. It will check undefined, null, 0 and "" also.

if(typeof RetailPrice!='undefined' && RetailPrice){
return this.RetailPrice;
}

How do I check for an empty/undefined/null string in JavaScript?

Empty string, undefined, null, ...

To check for a truthy value:

if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}

To check for a falsy value:

if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}


Empty string (only!)

To check for exactly an empty string, compare for strict equality against "" using the === operator:

if (strValue === "") {
// strValue was empty string
}

To check for not an empty string strictly, use the !== operator:

if (strValue !== "") {
// strValue was not an empty string
}

Best way to verify string is empty or null

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

Or, to be really optimal (but hecka ugly):

int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;

One thing I like to do:

Optional notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}

...

notBlank(myStr).orElse("some default")

Better way to check variable for null or empty string?

// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

Checking for empty or null List string

Try the following code:

 if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}

A late EDIT because for these checks I now like to use the following solution.
First, add a small reusable extension method called Safe():

public static class IEnumerableExtension
{
public static IEnumerable Safe(this IEnumerable source)
{
if (source == null)
{
yield break;
}

foreach (var item in source)
{
yield return item;
}
}
}

And then, you can do the same like:

 if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}

I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.

And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):

if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}

Check whether a string is not null and not empty

What about isEmpty() ?

if(str != null && !str.isEmpty())

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.


To ignore whitespace as well:

if(str != null && !str.trim().isEmpty())

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

Wrapped in a handy function:

public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}

Becomes:

if( !empty( str ) )


Related Topics



Leave a reply



Submit