Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select date (timestamp) from PostgreSQL as string (char), beware of NULL value

I want to select a date (my column is a timestamp type). But when in column is a NULL date, I want to return an empty string. How to do this? I wrote this:

SELECT
   CASE WHEN to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') IS NULL THEN ''
      ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post END
   to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post, content
FROM topic;

But it shows me some errors, dont really know why:

ERROR:  syntax error at or near "as"
LINE 1: ...ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_po...
                                                            ^
like image 999
Katie Avatar asked Apr 13 '13 16:04

Katie


People also ask

Can date be null in Postgres?

The error message indicates that your "date" column (which apparently isn't actually a date column) contains the string constant 'NULL' rather than a real null value (because there is no problem casting a real null value to date value). But the correct fix for this problem is to store date values in DATE columns.

How do I convert a date to a string in PostgreSQL?

Postgresql date to string yyymmdd In Postgresql, dates can be converted in specific string formats like yyymmdd, where yyyy for a year, mm for a month, and dd for the date. For that conversion, we will use the to_char function to format the date as a string. Syntax: TO_CHAR(date_value, string_format);

How do you handle null values in PostgreSQL?

nullif also used with the coalesce function to handle the null values. PostgreSQL nullif function returns a null value if provided expressions are equal. If two expressions provided are equal, then it provides a null value; as a result, otherwise, it will return the first expression as a result.

What is the format of timestamp in PostgreSQL?

Postgres DATE data type Postgres uses the DATE data type for storing different dates in YYYY-MM-DD format. It uses 4 bytes for storing a date value in a column. You can design a Postgres table with a DATE column and use the keyword DEFAULT CURRENT_DATE to use the current system date as the default value in this column.


1 Answers

Using the COALESCE() function is the nicest approach, as it simply swaps in a substitute value in the case of a NULL. Readability is improved greatly too. :)

SELECT COALESCE(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') AS last_post, content FROM topic;
like image 182
Nerdwood Avatar answered Sep 24 '22 06:09

Nerdwood