Skip to content
Advertisement

Change empty string to NULL when column has DATE constraint

This might be impossible but I was wondering if someone more experienced knew if this is possible to do in postgresql.

I have a column in my create statement

CREATE table IF NOT EXISTS (other cols, some_date DATE, other cols);

When I extract the json object from the API, there might actually be an empty string ” instead of a empty cell. Which of course gives me the following error psycopg2.errors.InvalidDatetimeFormat: invalid input syntax for type date: ""

The solution would simply to change the constraint to VARCHAR, but i was wondering if there was some way in the CREATE TABLE or INSERT statements to say the following pseudo code: if empty string insert NULL.

Advertisement

Answer

Use NULLIF in your INSERT statement:

If you want to insert NULL if the value in question is any of a number of values, it may be easiest to use a CASE statement:

Could do the same with an array as well, if that’s easier:

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