I am trying to create table with division possibilities and i want that the sum of all the cells in one row will be 1. For example:
0.1, 0.2, 0.3, 0.3, 0.1
You can create a constraint on the table that requires each row to meet some condition, in this case that total of columns be 1:
create table my_table (
col1 number,
col2 number,
col3 number,
col4 number,
constraint assert_sum_is_one check (col1 + col2 + col3 + col4 = 1)
)
Any attempt to insert or update rows to not total 1 will cause a constraint violation exception.
If you are on 11g you can use an Oracle Virtual Column:
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
in conjunction with a check constraint.
CREATE TABLE myTable (
id NUMBER,
col1 NUMBER(3),
col1 NUMBER(3),
col3 NUMBER(3),
colsum NUMBER GENERATED ALWAYS AS (col1 + col2 + col3) VIRTUAL,
CONSTRAINT pk_mytable PRIMARY KEY (id)
);
and then add a constraint to check that colsum is always exactly 1.
EDIT: Bohemian's answer is simpler and better. The only advantage in this case with a virtual column is that the sum is always persisted/visible, but if a constraint prevents the sum from being anything other than 1, then that isn't necessary. I'll leave this answer in just for the sake of the completion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With