2

Is it possible to create a table with a column that combines two column values? something like this:

create table test1 ( number1 decimal(6,2), number2 decimal(6,2), total decimal(6,2) DEFAULT (number1+number2) );

1
  • do you need the possibility to assign a different value to that column as well? or is it enough to have it always computed that way? Commented Sep 24, 2010 at 13:05

3 Answers 3

5

Yes, in 11G. It is called a "virtual" column. The syntax is:

create table test1
 ( number1 number(6,2),
   number2 number(6,2),
   total number(6,2) generated always as (number1+number2) );

(There isn't a DECIMAL datatype in Oracle AFAIK, so I used NUMBER instead.)

See also: documentation

NB The "generated always" keywords are optional.

The types of expression allowed after "as" are described here.

Sign up to request clarification or add additional context in comments.

4 Comments

Just an aside - DECIMAL works fine in Oracle, but I believe it's translated to NUMBER internally.
Is it also possible to use the "generated always as" to use an inner select?
like generat always as (select sum(*) from table) or something like that?
No, you would need to calculate via a trigger in that scenario - see Bob Jarvis's answer.
0

You can do this using a trigger:

create table test1
  (number1 decimal(6,2),
   number2 decimal(6,2),
   total decimal(6,2));

CREATE TRIGGER test1_bi
  BEFORE INSERT ON test1
  FOR EACH ROW
BEGIN
  IF :new.total is NULL THEN
    :NEW.TOTAL := :new.number1 + :new.number2;
  END IF;
END test1_bi;

INSERT INTO test1(number1, number2) VALUES(1, 2);

SELECT * FROM test1;

After the SELECT you'll find that TOTAL has a value of 3, as expected.

Share and enjoy.

Comments

0

You need to use computed columns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.