Search code examples
sqlmariadbcalculated-columnsmariasql

SQL: difference of 2 columns in a new column


I have the following SQL table, with a positive column and a negative column, both ints.

positive    negative
----------------------
5           3
3           1
10          7

How can I create a third column, e.g. total that is equal to positive - negative. Also, I would like the total column to be updated every time an element of the positive or negative column changes.

How can I do this in SQL?

Edit: I am using MariaDB


Solution

  • make use of computed column as described below

    you can create table as

    create table table_name ( positive int, negitive int, difference as positive-negitive)
    

    then after creating, if you enter values as

    insert into table_name values(3,2)
    

    --no need to enter third column it is called as computed column.

    then after inserting the difference will be present in the third column "difference"