Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print postgres table output so it can distinguish between empty string and null

is there a way to configure psql or to pass in some parameter when doing query, to print out different value for null and for empty string? Currently it shows empty for both.

For example, i have a table with this content:

adventure=# select * from account
adventure-# ;
 user_id | username | password | email |         created_on         |         last_login         
---------+----------+----------+-------+----------------------------+----------------------------
       1 |          |          |       | 2020-04-07 10:30:08.836098 | 2020-04-07 10:30:08.836098
(1 row)

With this, I cannot tell if username is empty string or a null. In this case, username is null, but password is empty string.

I tried using \x on, but it's the same thing.

Of course, i could do some coalescing, but that's a bit too much if i need to do it for every column.

like image 865
Kristijan Avatar asked Apr 07 '20 10:04

Kristijan


People also ask

Is empty string NULL in PostgreSQL?

Oracle reads empty strings as NULLs, while PostgreSQL treats them as empty. Concatenating NULL values with non-NULL characters results in that character in Oracle, but NULL in PostgreSQL.

Is empty string different than NULL?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

How check if PostgreSQL is empty?

If you just need to check only empty values, then try this -> where length(stringexpression) = 0; . This works for me. I like this solution, just note that is some cases calculating exact length may be relatively expensive operation. In postgres, length(NULL) > 0 return NULL , not False .

How do you check for is not null and is not empty string in SQL Server?

Description. The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

In psql you can do that with the configuration option null which can be changed using \pset

postgres=# \pset null '<null>'
Null display is "<null>".
postgres=# select null as c1, '' as c2;
   c1   | c2
--------+----
 <null> |

If you want that option permanently, you can put the \pset command into .psqlrc

like image 189
a_horse_with_no_name Avatar answered Oct 10 '22 02:10

a_horse_with_no_name