2

I have a table in which I have to define a column as the sum of the two previous ones. Is there a way to do it in the definition (POSTGRESQL) ? If no, can you tell me how to do it with triggers please ?

Assume we have this :

Table Foo
+---+---+---------+
| A | B | Sum_A_B |
+---+---+---------+
| 2 | 3 | 5       |
| ...             |
Mourad Qqch
  • 373
  • 1
  • 5
  • 16
  • 1
    see https://stackoverflow.com/questions/8250389/computed-calculated-columns-in-postgresql – etsa Sep 26 '17 at 10:24
  • 1
    You can create a view; `create view fooview as select a, b, a + b as Sum_A_B from foo`. – jarlh Sep 26 '17 at 10:24
  • But why are you want to define it as a sum of 2 cols. You can do the same through query at run time. – Ankit Bajpai Sep 26 '17 at 10:32
  • I do not decide of the schema of the database, however I'll discuss with the chief in order to propose him implementing a view instead of more columns (or a trigger). Thank you for redirecting my to the possible duplicate, it helps me ! (sorry for my bad english) – Mourad Qqch Sep 26 '17 at 10:40

1 Answers1

1

I don't think you can use computed columns in Postgres, a view would be a better option than a trigger:

CREATE VIEW viewname
AS
     SELECT a,
            b,
            (a + b) AS Sum_A_B
     FROM foo;

Or can you not just query it directly? does it need to be stored in the table:

 SELECT a,
        b,
        (a + b) AS Sum_A_B
 FROM foo;
dbajtr
  • 2,024
  • 2
  • 14
  • 22