0

I have the following table, I am trying to create a constraint on the table that states that the Ter_ID column can have the same Ter_ID repeating however the corresponding Status cannot be the same at anytime, so if for example one is trying to update Ter_ID 100P Status from U to A it wouldn't go through seeing that there is already a row with the corresponding data.

Ter_ID  Status  Address
100P    A   Road1
100P    U   Road2
200R    A   Road2

1 Answer 1

1

You need to add a composed unique index using the two columns.

Example:

ALTER TABLE `tablename` ADD UNIQUE `unique_index`(`Ter_ID`, `Status`);

Be aware of the different NULL behaviour depending of the MySQL engine that you are using. From the official MySQL documentation:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.