Skip to content
Advertisement

Postgresql – Compare a string with a null value

I’m a bit puzzled because I believe the answer to this question is fairly simple but I’ve searched and tried several options and couldn’t find the right answer.

The database is a PostgreSQL 13.1

I am using an API which sends a JSON object to a stored function in the database as follows:

The function queries a table with the following structure:

Inside the function is a query like this:

Everything works as expected until one of the values of “variant” or “subname” is passed as NULL. These two are the $3 and $4 in the query. The table accepts null values for these two columns. If the value of “variant” or “subname” passed by the JSON object is null the query doesn’t return any result even if the row exists in the table. I must be missing something really simple or basic. But I can’t find it.

EDIT TO ADD A MINIMUM REPRODUCIBLE EXAMPLE:

Advertisement

Answer

Postgres supports standard null-safe equality operator is distinct from, which does exactly what you ask for:

Demo on DB Fiddle:

| count |
| ----: |
|     1 |

Side note: do you really need lower() here? It is not obvious from your sample data. Note that using this function prevents the database from taking advantage of an index (unless you do create an index on this specific expression).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement