2

I'm trying to add a generated column in existing table. I've a transaction table, in that table I've one column named as dateTime(containing date and time in timestamp format). I want to create a virtual column named as transactionDate which will contain a date and time derived from dateTime column.

Below is the query which I created

ALTER TABLE public.transaction ADD COLUMN "transactionDate" timestamp without time zone GENERATED ALWAYS AS (timestamp("dateTime")::date) STORED;

and I'm getting below error:

ERROR: syntax error at or near ""dateTime"" LINE 2: ... without time zone GENERATED ALWAYS AS (timestamp("dateTime"... ^ SQL state: 42601 Character: 121

Please help me out.

2 Answers 2

1

What are you using timestamp() for?

For generated column, it should be like -

ALTER TABLE transaction ADD COLUMN "transactionDate" timestamp without time zone GENERATED ALWAYS AS ("dateTime"::date) STORED;

OR

ALTER TABLE transaction ADD COLUMN "transactionDate" timestamp without time zone GENERATED ALWAYS AS ("dateTime"::timestamp) STORED;

Fiddle here.

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

1 Comment

Will this give me a output in MM-DD-YYYY HH:MM format?
0

The column dateTime is already a timestamp so you do not need to create a timestamp from it. So just: ( see demo)

alter table transaction  
      add column "transactionDate" date
         generated always as ("dateTime"::date) stored;

4 Comments

I run this query in pgadmin and it's giving error ERROR: unterminated quoted identifier at or near ""dateTime::date) STORED;" LINE 3: GENERATED ALWAYS AS ("dateTime::date) STORED; ^ SQL state: 42601 Character: 87
I did change ALTER TABLE public.transaction ADD COLUMN "transactionDate" DATE GENERATED ALWAYS AS ("dateTime"::date) STORED; and it's giving ERROR: generation expression is not immutable SQL state: 42P17
There is a missing double quote after dateTime. Line should read generated always as ("dateTime"::date) stored; Think this comes from the fact that I never use double quoted column names unless they are already there.
@Belayer What kept you from fixing it?

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.