skip to Main Content

I have a table with 2 columns:

CREATE TABLE Numbers(
    col1 float,
    col2 float
);
INSERT INTO Numbers(col1, col2)
VALUES('0.6', '1.5'),('2.7', '1.8');

How can I create a third column with the sum of col1 and col2?

3

Answers


  1. First, create col3 using the ALTER TABLE command.

    Then update it with the sums.

    UPDATE numbers SET col3 = col1 + col2;
    
    Login or Signup to reply.
  2. I would suggest a calculated column – that way if col1 or col2 are updated, col3 will automatically reflect the correct value; storing mutable data is gnerally not a good idea as it easily leads to inconsistencies.

    alter table Numbers add column col3 float as (col1 + col2) stored;
    

    Side note – float is rarely the correct choice of data type, probably you should be using a decimal.

    Login or Signup to reply.

  3. Select *, col1 +col2 as col3 from numbers


    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search