Temporarily Disable Foreign Key Constraints

A foreign key in YSQL is used to maintain the referential integrity of data between two tables: values in columns in one table equal the values in columns in another table.

Example:

				
					yugabyte=# CREATE TABLE dim (dim_id INT PRIMARY KEY, some_data VARCHAR);
CREATE TABLE

yugabyte=# CREATE TABLE fact (fact_id INT PRIMARY KEY, dim_id_some_data INT REFERENCES dim(dim_id));
CREATE TABLE

yugabyte=# INSERT INTO dim (dim_id, some_data) VALUES (1, 'A'), (2, 'B'), (3, 'C');
INSERT 0 3

yugabyte=# INSERT INTO fact (fact_id, dim_id_some_data) VALUES (1, 1);
INSERT 0 1

yugabyte=# INSERT INTO fact (fact_id, dim_id_some_data) VALUES (2, 4);
ERROR:  insert or update on table "fact" violates foreign key constraint "fact_dim_id_some_data_fkey"
				
			

There may be times when you might want to disable a foreign key constraint.

For example, during a migration or data load, you might be loading tables out of order (child table before the parent table).

You can temporaily disable foreign keys in a session while you load the data, then reanble them after the load completes.

Example:

				
					yugabyte=# SET session_replication_role = 'replica';
SET

yugabyte=# INSERT INTO fact (fact_id, dim_id_some_data) VALUES (2, 4);
INSERT 0 1

yugabyte=# INSERT INTO dim (dim_id, some_data) VALUES (4, 'D');
INSERT 0 1

yugabyte=# SET session_replication_role = 'origin';
SET
				
			

Have Fun!