Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent column b containing the same value as any column a in Oracle?

What is a good way to prevent a table with 2 columns, a (unique) and b, from having any record where column b is equal to any value in column a? This would be used for a table of corrections like this,

MR   -> Mr
Prf. -> Prof.
MRs  -> Mrs

I can see how it could be done with a trigger and a subquery assuming no concurrent activity but a more declarative approach would be preferable.

This is an example of what should be prevented,

Wing Commdr. -> Wing Cdr.
Wing Cdr.    -> Wing Commander

Ideally the solution would work with concurrent inserts and updates.

like image 714
Janek Bogucki Avatar asked Nov 05 '22 14:11

Janek Bogucki


1 Answers

You could use a materialized view to enforce your requirements (tested with 10.2.0.1).

SQL> CREATE TABLE t (a VARCHAR2(20) NOT NULL PRIMARY KEY,
  2                  b VARCHAR2(20) NOT NULL);
Table created

SQL> CREATE MATERIALIZED VIEW LOG ON t WITH (b), ROWID INCLUDING NEW VALUES;     
Materialized view log created

SQL> CREATE MATERIALIZED VIEW mv
  2     REFRESH FAST ON COMMIT
  3  AS
  4  SELECT 1 umarker, COUNT(*) c, count(a) cc, a val_col
  5    FROM t
  6   GROUP BY a
  7  UNION ALL
  8  SELECT 2 umarker, COUNT(*), COUNT(b), b
  9    FROM t
 10    GROUP BY b;     
Materialized view created

SQL> CREATE UNIQUE INDEX idx ON mv (val_col);     
Index created 

The unique index will ensure that you can not have the same value in both columns (on two rows).

SQL> INSERT INTO t VALUES ('Wing Commdr.', 'Wing Cdr.');     
1 row inserted

SQL> COMMIT;     
Commit complete

SQL> INSERT INTO t VALUES ('Wing Cdr.', 'Wing Commander');     
1 row inserted

SQL> COMMIT;     

ORA-12008: erreur dans le chemin de régénération de la vue matérialisée
ORA-00001: violation de contrainte unique (VNZ.IDX)

SQL> INSERT INTO t VALUES ('X', 'Wing Commdr.');     
1 row inserted

SQL> COMMIT;

ORA-12008: erreur dans le chemin de régénération de la vue matérialisée
ORA-00001: violation de contrainte unique (VNZ.IDX)

It will serialize during commit but only on the values of columns A and B (ie: in general it should not prevent concurrent disjoint activity).

The unicity will only be checked at COMMIT time and some tools don't expect commit to fail and may behave inappropriately. Also when the COMMIT fails, the entire transaction is rolled back and you lose any uncommited changes (you can not "retry").

like image 122
Vincent Malgrat Avatar answered Nov 14 '22 14:11

Vincent Malgrat