Adding column to table & adding data right away to column in PostgreSQL

人走茶凉 提交于 2019-12-03 08:04:00

In general it's not a good idea to add calculated data to a table. You sometimes need to do it when re-normalizing tables, but usually it's not done.

As Gordon says, the appropriate thing to do here would be to create a view. See the tutorial.

There is no ALTER TABLE ... ADD COLUMN ... AS. You can't just make up syntax, you need to look at the documentation for the command you're interested in to find out how to use it. The \h command in psql is also useful, eg \h alter table.

If you do need to set values in a new column based on calculations from other columns, use ALTER TABLE ... ADD COLUMN ... DEFAULT ... then DROP the DEFAULT term after you create the column. It's often better to create the column blank and nullable, then fill it with an UPDATE statement.

E.g. untested examples:

BEGIN;

ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2);

UPDATE mn2012ct_geom2  SET romney_pct = CAST (romney AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2);

COMMIT;

or, somewhat uglier:

BEGIN;

ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2) NOT NULL DEFAULT (CAST (obama AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2));

ALTER TABLE mn2012ct_geom2 ALTER COLUMN obama_pct DROP DEFAULT;

COMMIT;

I think you are looking for the update statement. For example:

ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2);

update mn2012ct_geom2
    set obama_pct = CAST(obama AS DECIMAL) / CAST(uspres_total AS DECIMAL);

You might also consider just creating a view to do the calculation:

create view v_mn2012ct_geom2 as
    select g.*, CAST(obama AS DECIMAL) / CAST(uspres_total AS DECIMAL) as mn2012ct_geom2
    from mn2012ct_geom2;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!