Postgresql – How to print text in select query instead of NULL value in DATE field in postgresql

casepostgresql

I have a table test as follows :

create table test (id int, enroll date)

I have inserted some rows as follows :

insert into test values (1,'2012-01-02');
insert into test(id) values (2);  

Now I want to select all rows and want to print 'Error' where the enroll field that has date datatype has NULL values.
I wrote the following query which gives me error :

select case when enroll is null then 'Error' else enroll end as Enroll from test;  

My desired output is :

2012-01-02
Error  

Thanks in advance for help.

Best Answer

You need to cast it to string first. Check the below query;

select coalesce(to_char(enroll, 'YYYY-MM-DD'),'Error') as formatted from test;