19

I am trying to add a generated column to an existing table with this script.

alter table Asset_Store add column

md5_hash VARCHAR(100) GENERATED ALWAYS AS 

(CAST(UPPER(    
        case
             when OR_ID is not null then MD5(cast(OR_ID as varchar(100)))
             when Asset_ID is not null then MD5(Asset_ID)
             else null
        end 
) as VARCHAR(100)))

STORED

;

but I am getting an error:

SQL Error [42601]: ERROR: syntax error at or near "("
 Position: 88
 ERROR: syntax error at or near "("
 Position: 88
 ERROR: syntax error at or near "("
 Position: 88

What is the issue? I don't get it.

In the schema of my Asset_Store table the column
OR_ID is int and Asset_ID is varchar(100).

I guess it expects a slightly different syntax... but what is the right syntax?

3
  • 2
    Version of PostgreSQL? It was introduced in 12. Commented Mar 17, 2020 at 18:58
  • 1
    What does select version(); give you? Commented Mar 17, 2020 at 20:00
  • Thanks. Yes, I realized later that I was on PG 11. Commented Mar 18, 2020 at 0:01

2 Answers 2

19

Your syntax is correct. Your version of PostgreSQL apparently is not.

In version 12:

create table asset_store(or_id text, asset_id text);

alter table Asset_Store add column
md5_hash VARCHAR(100) GENERATED ALWAYS AS 
(CAST(UPPER(    
        case
             when OR_ID is not null then MD5(cast(OR_ID as varchar(100)))
             when Asset_ID is not null then MD5(Asset_ID)
             else null
        end 
) as VARCHAR(100)))
STORED
;
ALTER TABLE
Time: 17.678 ms
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Yes, I realized later that I was on PG 11.
For future copy-pasters, neither of the CAST (... as VARCHAR(100)) expressions were necessary for me in my different SQL.
7

More general, simplified command

ALTER TABLE "items"
ADD COLUMN "revenue" numeric 
GENERATED ALWAYS AS ("price" * (1-"discount")) STORED;

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.