Inserting Null to PostgreSQL in Golang

Golang gopher and PostgreSQL elephant

I have this use case where I want to insert timestamp value to the database, but the value can be null.

If you insert an empty time.Time variable to PostgreSQL, the inserted value won’t be `NULL` but `0001–01–01 00:00:00`. Let’s see an example where my “orders” table looks like this:

The golang query

The value of paid_at where order_id is ‘8’ is `0001–01–01 00:00:00`. This is illogical because the order has not been paid, and I want it to stay nulled. None of our orders are paid at `0001–01–01 00:00:00` which is equivalent to January 1, 1970 12:00:00 AM, so we will treat that value as an empty time.

The easiest way to implement this is to use NULLIF. Let’s update the SQL query.

The NULLIF function checks if the paid_at (as $1) is equal to ‘0001–01–01 00:00:00’, the assumed empty time. If it’s empty, NULLIF will return NULL. Perform that query, then we will get NULL as a value in the paid_at.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store