Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create row in a table with the sum of 1 sql

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  
like image 726
Ofer Avatar asked Dec 15 '22 20:12

Ofer


2 Answers

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.

like image 61
Bohemian Avatar answered Dec 28 '22 08:12

Bohemian


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.

like image 22
davek Avatar answered Dec 28 '22 07:12

davek