Mahbub Rashid Tonoy
Mahbub Rashid Tonoy

Reputation: 95

How To Set MySQL unique row?

I want to run this SQL in MySQL database.

INSERT INTO
  colors (red, blue)
VALUES
  ('value1', 'value2');

but I want that it will insert data only when value1 !== value2 . is there any way to do that? Thanks for your attention.

Upvotes: 2

Views: 37

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269603

You can use a check constraint to return an error:

ALTER TABLE colors ADD CONSTRAINT (red <> blue);

Or, for this particular insert, you can use INSERT . . . SELECT:

INSERT INTO colors (red, blue)
    SELECT red, blue
    FROM (SELECT 'value1' as red, 'value2' as blue) v
    WHERE red <> blue;

Upvotes: 2

Related Questions