2

I have a table that has two columns to store id from another table. Column1 gets id from ABC table and Column2 also gets id from that table but letter is called parent ID, so with this information I know who is parent of who.

Now I want to create a constraint not to ever let both columns to get same id. The following did not work:

ALTER TABLE id_parent_table
ADD CHECK (parent_id != main_id)

This is still allowing to insert two identical numbers.

Wolfone
  • 1,276
  • 3
  • 11
  • 31
Jamol
  • 3,768
  • 8
  • 45
  • 68

2 Answers2

2

This is now supported as of MySQL 8.0.16.

See https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

mysql> create table id_parent_table (
    -> main_id bigint unsigned not null,
    -> parent_id bigint unsigned not null,
    -> constraint columns_cannot_equal check (main_id <> parent_id)
    -> );
Query OK, 0 rows affected (0.38 sec)

mysql> insert into id_parent_table (main_id, parent_id) values (1, 1);
ERROR 3819 (HY000): Check constraint 'columns_cannot_equal' is violated.
0

Apparently, MySQL does not support check constraints. To quote the online reference:

The CHECK clause is parsed but ignored by all storage engines.

You could, alternatively, use a trigger to fail such an insert or update:

EDIT: MySQL doesn't support a single trigger on two events, so you'd have to have two different triggers:

delimiter //
CREATE TRIGGER id_parent_table_check_insert_trg
BEFORE INSERT ON id_parent_table
FOR EACH ROW
BEGIN
    DECLARE msg varchar(255);
    IF new.parent_id = new.main_id THEN
        SET msg = 'parent_id and main_id should be different';
        SIGNAL SQLSTATE '45000' SET message_text = msg;
    END IF;
END
//

CREATE TRIGGER id_parent_table_check_update_trg
BEFORE UPDATE ON id_parent_table
FOR EACH ROW
BEGIN
    DECLARE msg varchar(255);
    IF new.parent_id = new.main_id THEN
        SET msg = 'parent_id and main_id should be different';
        SIGNAL SQLSTATE '45000' SET message_text = msg;
    END IF;
END
//
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • You are right. It seems we cannot use check constraint in MySQL. Nevertheless your code to create a trigger is not working too. It has syntax errors, and it seems MySQL does not support BEFORE INSERT OR UPDATE too – Jamol Apr 17 '14 at 11:27
  • @jCloud forgot MySQL does support triggers on multiple events. See edit. – Mureinik Apr 17 '14 at 11:29
  • 1
    OK. Now please edit your answer to correct syntax errors like ENF ID; Please run it on your machine first. So then I can accept your answer as Correct one. Thanks – Jamol Apr 17 '14 at 11:36