Search code examples
postgresqlcalculated-columnspostgresql-9.6

Can (aggregate) functions be used to define a column?


Assume a table like this one:

a | b | total
--|---|------
1 | 2 |  3
4 | 7 | 11
…

CREATE TEMPORARY TABLE summedup (
    a double precision DEFAULT 0
  , b double precision DEFAULT 0
  --, total double precision
);
INSERT INTO summedup (a, b) VALUES (1, 2);
INSERT INTO summedup (a, b) VALUES (4, 7);

SELECT a, b, a + b as total FROM summedup;

It's easy to sum up the first two columns on SELECT.

But does Postgres (9.6) also support the ability to define total as the sum of the other two columns? If so:

  • What is the syntax?
  • What is this type of operation called (aggregates typically sum up cells over multiple rows, not columns.)

Solution

  • What you are looking for is typically called a "computed column".

    Postgres 9.6 does not support that (Postgres 12 - to be released in Q4 2019 - will).

    But for such a simple sum, I wouldn't bother storing redundant information.

    If you don't want to repeat the expression, create a view.