# Foreign Key

+ v6.6 and later
  + TiDB supports MySQL-compatible foreign key behaviors
+ v6.5 and earlier
  + TiDB supports foreign key syntax to avoid syntax errors when migrating data from other databases to TiDB
  + TiDB does not perform constraint checks on foreign keys
```7
~!@// Example: v6.5 and earlier@!~
tidb> CREATE TABLE test.p (id INT PRIMARY KEY, name CHAR(30));
tidb> CREATE TABLE test.c (
   ->  id INT PRIMARY KEY, 
   ->  pid INT NOT NULL, 
   ->  ~!@FOREIGN KEY (pid) REFERENCES test.p (id)@!~);
tidb> INSERT INTO test.p VALUES (~!@1@!~,'A');
tidb> INSERT INTO test.c VALUES (1,~!@100@!~);

SELECT ~!@'p', id@!~ FROM test.p 
UNION ALL 
SELECT ~!@'c', pid@!~ FROM test.c;
+------+------+
| p    | id   |
+------+------+
| c    |  100 |
| p    |    1 |
+------+------+
```

```7
~!@// Example: v6.6 and later@!~
tidb> CREATE TABLE test.p (id INT PRIMARY KEY, name CHAR(30));
tidb> CREATE TABLE test.c (
    -> id INT PRIMARY KEY,
    -> pid INT NOT NULL,
    -> ~!@FOREIGN KEY (pid) REFERENCES test.p (id)@!~);
tidb> INSERT INTO test.p VALUES (~!@1@!~,'A');
tidb> INSERT INTO test.c VALUES (1,~!@100@!~);
~!@ERROR 1452 (23000):@!~ Cannot add or update a child row: 
~!@a foreign key constraint fails@!~ 
(`test`.`c`, CONSTRAINT `fk_1` FOREIGN KEY (`pid`) REFERENCES `p` (`id`))
tidb> SELECT ~!@'p', id@!~ FROM test.p
    -> UNION ALL
    -> SELECT ~!@'c', pid@!~ FROM test.c;
+------+------+
| p    | id   |
+------+------+
| p    |    1 |
+------+------+
```
------------------------------------------------------------
[no notes]