9

Within a plpgsql-function I have a simple insert statememt:

insert into table_Y (column1       ,
                     column2       ,
                     //more columns
                     int_date      , -- example: '20190714'
                     //more columns
                    )
select value1              ,
       value2              ,
       //more values
       date_value::integer ,
       //more values   
  from table_X

Column "date_value" in table table_X is of type date. Column int_date in table table_Y is of type integer ... so with the following expression:

date_value::integer

... I want to convert the value from column "date_value" to an integer (e.g. from 14. July 2019 to '20190714').

However, I'm getting the following error message:

ERROR:  cannot cast type date to integer   

How can I convert the date to an integer instead?

P.S.: the solution to this question: convert date to integer in postgresql does not help in my case becasue I don't want the number of days.

2 Answers 2

23

The direct conversion is not allowed, because usually has not sense - but you can use auxiliary conversion to text, and it should to work:

postgres=# SELECT to_char(CURRENT_DATE, 'YYYYMMDD')::integer;
┌──────────┐
│ to_char  │
╞══════════╡
│ 20190718 │
└──────────┘
(1 row)

But I have to say, so working with this representation of date is strange and unhappy.

Sign up to request clarification or add additional context in comments.

Comments

1

Try using int rather than integer, as following query worked for me:

SELECT * date_part('year/month/day', age(CURRENT_DATE,your date))::int
       as age
       from xyz_table
       where date_part('year/month/day', age(CURRENT_DATE,your date))::int > comparsion value ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.