0

I'm trying to create table with computed boolean values

CREATE TABLE parts
(
    Id SERIAL PRIMARY KEY,
    Weight INTEGER NOT NULL CHECK(Weight > 0),
    Color VARCHAR(10),
    Price INTEGER NOT NULL CHECK(Price > 0),
    IsCheap BOOL AS (CASE WHEN Price <= 1000 THEN True ELSE False END),
    Name VARCHAR(30)
);

But getting this error

ERROR:  syntax error at or near "AS"
LINE 7:  IsCheap BOOL AS (CASE WHEN Price <= 1000 THEN True ELSE Fal...

Also I've tried with BIT instead BOOL - same error. Have no idea why it doesn't work.

1
  • You need Postgres 12 for that. Commented Oct 14, 2019 at 9:09

1 Answer 1

4

You need Postgres 12 (released 2019-10-03) if you want to use computed columns.

And as on its own is not enough. The syntax requires to use generated always as ... as documented in the manual:

create table parts
(
  id       serial primary key,
  weight   integer not null check (weight > 0),
  color    varchar(10),
  price    integer not null check (price > 0),
  is_cheap boolean generated always as (price <= 1000) stored,
  name     varchar(30)
);

If you are not using Postgres 12, then I would recommend to create a view that simply includes price <= 1000 as is_cheap as the calculation of that attribute is really cheap and there is no need to store it.

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

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.