0

How can I write a condition in a create table statement to say 2 columns cannot be equal?

CREATE table Example(
    sendId integer,
    recieveId integer,
    **!sendId cannot equal recieveId**

);
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843

3 Answers3

2

Use a check constraint:

CREATE table Example(
    sendId integer,
    recieveId integer,
    constraint not_equal check (sendid <> recieveId)
);

As your columns allow null values, you might want to take care of that too:

CREATE table Example(
    sendId integer,
    recieveId integer,
    constraint not_equal check (coalesce(sendid,0) <> coalesce(recieveId,0))
);

That treats NULL as 0 maybe using a different value that could never occur might be more appropriate.

Depending on your DBMS product, you could also use the standard operator is distinct from

constraint not_equal check (sendid is distinct from receiveid)
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
1

You would use a check constraint:

create table Example (
    sendId integer,
    receiveId integer,
    constraint chk_example_sendId_receiveId check (sendId <> receiveId)
);
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0

You need check constraint :

constraint chk_sendId_receiveId check (sendId <> receiveId)
Yogesh Sharma
  • 49,081
  • 5
  • 23
  • 49