Skip to content
Advertisement

Calculating Datediff from nested json sql query

I am trying to use datediff() to find the age of a person in a postgres db (from their date of birth(. I know I can run datediff() like this

The query i use to get date of birth is (its in json)

This gives me output like

I tried using

It doesn’t work. I tried several permutations but i can’t get it to work. How should I edit my query to calculate the user age?

Advertisement

Answer

This query:

Returns the row rather than a column, (the column expression for the extracted date value has no defined alias). It’s like using select users from users. You need to make `date_of_birth_ a column alias (not a table alias) and use that in the outer query.

To get the difference between two dates, just subtract them but you need to cast the valued to a date to be able to do that.

Or without a derived table:

Apparently your dates are stored in a non-standard format. In that case you can’t use as cast, but you need to use the to_date() function:


If you are storing JSON in the attrs column you should convert it from a text (or varchar column to a proper json (or better jsonb) so you don’t need to cast it all the time.

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