Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create mutually exclusive table columns

I have a table Transactions where I am saving two records for one transaction, one for debiting and other crediting.

So I have two columns in table creditAmount(Money) and debitAmount(Money).

I want a table level constraint that either of the column is not null in each row. i.e. If row #3 creditAmount is null then debitAmount must hold some value and Vice Versa.

How to ensure the same when inserting a record in a row?

like image 945
MaxRecursion Avatar asked Dec 22 '12 12:12

MaxRecursion


1 Answers

You can add a CHECK constraint to the table:

ALTER TABLE Transactions ADD CONSTRAINT CK_Transactions_DebitOrCreditExists
CHECK ((creditAmount IS NULL AND debitAmount IS NOT NULL) 
   OR (creditAmount IS NOT NULL AND debitAmount IS NULL))
like image 62
Chris Van Opstal Avatar answered Oct 06 '22 10:10

Chris Van Opstal