官术网_书友最值得收藏!

  • Mastering PostgreSQL 12
  • Hans Jürgen Sch?nig
  • 264字
  • 2021-08-20 10:00:19

Storing the result of a computation

PostgreSQL 12 has more features that can simplify development. In many cases, the content of a column has to be derived from some other column. Traditionally, this has been implemented using a trigger. However, writing a trigger needs some coding and manual work. PostgreSQL has a better solution to the problem.

Suppose we want to store data in kilometers and nautical miles. One nautical mile translates to 1.852 km. 

For those of you who know nothing about nautical miles: A nautical mile is 1/60 th of a degree on the equator. 

To make sure that nautical miles are always generated, the following syntax can be used:

test=# CREATE TABLE t_measurement (
t timestamp,
km numeric,
nm numeric GENERATED ALWAYS AS (km * 1.852) STORED
);
CREATE TABLE

GENERATED ALWAYS AS is an elegant way to pre-calculate the content of a column. As you can see, the definition does exactly what we expect: 

test=# INSERT INTO t_measurement (t, km) VALUES (now(), 100) RETURNING *;
t | km | nm
----------------------------+-----+---------
2019-09-30 15:02:31.004481 | 100 | 185.200
(1 row)

INSERT 0 1

However, there is more than instantly meets the eye—GENERATED ALWAYS AS also ensures that the content of the column cannot be changed to ensure that the value is always correct:

test=# INSERT INTO t_measurement (t, km, nm) VALUES (now(), 100, 1000) RETURNING *;
ERROR: cannot insert into column "nm"
DETAIL: Column "nm" is a generated column.

Performance-wise, the new feature is also faster than the traditional method of using a trigger.

主站蜘蛛池模板: 普格县| 娄底市| 新安县| 静宁县| 姚安县| 南宫市| 方山县| 兴海县| 龙山县| 大兴区| 阳江市| 朔州市| 兰州市| 团风县| 乌恰县| 金华市| 桐梓县| 镇平县| 呈贡县| 潼关县| 明溪县| 平山县| 洛隆县| 元江| 宕昌县| 嘉峪关市| 怀柔区| 连平县| 玉山县| 阿拉善右旗| 烟台市| 晋中市| 岳阳县| 伊春市| 武宣县| 拜泉县| 四川省| 定远县| 米易县| 柯坪县| 武宁县|