{"id":581,"date":"2016-04-15T15:31:36","date_gmt":"2016-04-15T15:31:36","guid":{"rendered":"https:\/\/sqltutorial.org\/?page_id=581"},"modified":"2025-03-16T20:07:56","modified_gmt":"2025-03-17T03:07:56","slug":"sql-foreign-key","status":"publish","type":"page","link":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/","title":{"rendered":"SQL Foreign Key Constraint"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: In this tutorial, you&#8217;ll learn about the SQL foreign key and how to define a foreign key using the <code>FOREIGN KEY<\/code> constraint.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"introduction-to-sql-foreign-key\" id='introduction-to-sql-foreign-key'>Introduction to SQL Foreign Key <a href=\"#introduction-to-sql-foreign-key\" class=\"anchor\" id=\"introduction-to-sql-foreign-key\" title=\"Anchor for Introduction to SQL Foreign Key\">#<\/a><\/h2>\n\n\n\n<p>In SQL, a foreign key is a column or a set of columns in a table that references the <a href=\"https:\/\/www.sqltutorial.org\/sql-primary-key\/\">primary key<\/a> of another table.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A table with a foreign key is called a&nbsp;<strong>child<\/strong>&nbsp;or&nbsp;<strong>foreign key<\/strong>, or&nbsp;<strong>referencing<\/strong>&nbsp;table.<\/li>\n\n\n\n<li>A table with primary key columns referenced by a foreign key is called a&nbsp;<strong>parent<\/strong> or&nbsp;<strong>reference table<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>The primary purpose of a foreign key is to set up the relationship between the child and parent tables.<\/p>\n\n\n\n<p>For example, for a value in a foreign key in the child table, you can always find the corresponding values in the primary key in the parent table.<\/p>\n\n\n\n<p>Suppose we have two tables:&nbsp;<code>projects<\/code>&nbsp;and&nbsp;<code>project_milestones<\/code>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The&nbsp;<code>project_milestones<\/code>&nbsp;table has a foreign key&nbsp;<code>project_id<\/code>&nbsp;that references the&nbsp;<code>project_id<\/code>&nbsp;in the&nbsp;<code>projects<\/code>&nbsp;table.<\/li>\n\n\n\n<li>The&nbsp;<code>project_milestones<\/code>&nbsp;table is called a&nbsp;<strong>child<\/strong>&nbsp;or&nbsp;<strong>foreign key table<\/strong>, and the&nbsp;<code>projects<\/code>&nbsp;table is the&nbsp;<strong>parent<\/strong>&nbsp;or&nbsp;<strong>reference table<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>For each row in the&nbsp;<code>project_milestones<\/code>&nbsp;table, you can find the&nbsp;<code>project_id<\/code>&nbsp;value in the&nbsp;<code>projects<\/code>&nbsp;table. This rule is called a&nbsp;<strong>referential integrity constraint<\/strong>&nbsp;between the two tables.<\/p>\n\n\n\n<p>A table can have multiple foreign keys but only one primary key.<\/p>\n\n\n\n<p>In SQL, you use a <strong>foreign key constraint<\/strong> to create a foreign key.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"syntax\" id='sql-foreign-key-constraints'>SQL Foreign Key Constraints <a href=\"#sql-foreign-key-constraints\" class=\"anchor\" id=\"sql-foreign-key-constraints\" title=\"Anchor for SQL Foreign Key Constraints\">#<\/a><\/h2>\n\n\n\n<p>Here&#8217;s the syntax for defining a foreign key constraint in the child table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">CONSTRAINT constraint_name\nFOREIGN KEY (column1, column2)\nREFERENCES parent_table(column1, column2)\nON <span class=\"hljs-keyword\">DELETE<\/span> delete_action\n<span class=\"hljs-keyword\">ON<\/span> <span class=\"hljs-keyword\">UPDATE<\/span> update_action;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, specify the constraint name of the foreign key in the <code>CONSTRAINT<\/code> clause. Most database systems automatically assign a name if you don&#8217;t name the foreign key.<\/li>\n\n\n\n<li>Second, provide one or more columns to include in the foreign key.-<\/li>\n\n\n\n<li>Third, specify the parent table (reference table) with one or more columns.<\/li>\n\n\n\n<li>Finally, define the action when the values in the parent table&#8217;s primary key are updated or deleted.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"defining-a-foreign-key-constraint-example\" id='defining-a-foreign-key-constraint-example'>Defining a Foreign Key Constraint Example <a href=\"#defining-a-foreign-key-constraint-example\" class=\"anchor\" id=\"defining-a-foreign-key-constraint-example\" title=\"Anchor for Defining a Foreign Key Constraint Example\">#<\/a><\/h2>\n\n\n\n<p>Step 1: <a href=\"https:\/\/www.sqltutorial.org\/sql-create-table\/\">Create a new table<\/a> called&nbsp;<code>projects<\/code>&nbsp;to store project data:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> projects (\n    project_id <span class=\"hljs-built_in\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> PRIMARY <span class=\"hljs-keyword\">KEY<\/span>,\n    project_name <span class=\"hljs-built_in\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n    start_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n    end_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>\n);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=Q1JFQVRFIFRBQkxFIHByb2plY3RzICggcHJvamVjdF9pZCBJTlQgR0VORVJBVEVEIEFMV0FZUyBBUyBJREVOVElUWSBQUklNQVJZIEtFWSwgcHJvamVjdF9uYW1lIFZBUkNIQVIoMjU1KSBOT1QgTlVMTCwgc3RhcnRfZGF0ZSBEQVRFIE5PVCBOVUxMLCBlbmRfZGF0ZSBEQVRFIE5PVCBOVUxMICk7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Step 2: Create a new table called&nbsp;<code>project_milestones<\/code>&nbsp;to store project milestones:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> project_milestones (\n  milestone_id <span class=\"hljs-built_in\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> PRIMARY <span class=\"hljs-keyword\">KEY<\/span>,\n  milestone <span class=\"hljs-built_in\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>),\n  start_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  end_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  project_id <span class=\"hljs-built_in\">INT<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  <span class=\"hljs-keyword\">FOREIGN<\/span> <span class=\"hljs-keyword\">KEY<\/span> (project_id) <span class=\"hljs-keyword\">REFERENCES<\/span> projects (project_id)\n);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=Q1JFQVRFIFRBQkxFIHByb2plY3RfbWlsZXN0b25lcyAoIG1pbGVzdG9uZV9pZCBJTlQgR0VORVJBVEVEIEFMV0FZUyBBUyBJREVOVElUWSBQUklNQVJZIEtFWSwgbWlsZXN0b25lIFZBUkNIQVIoMjU1KSwgc3RhcnRfZGF0ZSBEQVRFIE5PVCBOVUxMLCBlbmRfZGF0ZSBEQVRFIE5PVCBOVUxMLCBwcm9qZWN0X2lkIElOVCBOT1QgTlVMTCwgRk9SRUlHTiBLRVkgKHByb2plY3RfaWQpIFJFRkVSRU5DRVMgcHJvamVjdHMgKHByb2plY3RfaWQpICk7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>In the&nbsp;<code>project_milestones<\/code>&nbsp;table, we define a foreign key constraint that includes the&nbsp;<code>project_id<\/code>&nbsp;and reference it to the&nbsp;<code>project_id<\/code>&nbsp;columns of the&nbsp;<code>projects<\/code>&nbsp;table.<\/p>\n\n\n\n<p>Since we don&#8217;t explicitly specify the name of the foreign key constraint, the database system automatically generates one with the name&nbsp;<code>project_milestones_project_id_fkey<\/code>.<\/p>\n\n\n\n<p class=\"note\">Note that the generated name may vary depending on the database system.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"inserting-data-with-foreign-key-constraint\" id='inserting-data-with-foreign-key-constraint'>Inserting Data with Foreign Key Constraint <a href=\"#inserting-data-with-foreign-key-constraint\" class=\"anchor\" id=\"inserting-data-with-foreign-key-constraint\" title=\"Anchor for Inserting Data with Foreign Key Constraint\">#<\/a><\/h2>\n\n\n\n<p>Step 1: <a href=\"https:\/\/www.sqltutorial.org\/sql-insert\/\">Insert a new row<\/a> into the&nbsp;<code>projects<\/code>&nbsp;table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span>\n  projects (project_name, start_date, end_date)\n<span class=\"hljs-keyword\">VALUES<\/span>\n  (<span class=\"hljs-string\">'Super App'<\/span>, <span class=\"hljs-string\">'2025-01-01'<\/span>, <span class=\"hljs-string\">'2025-12-31'<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=SU5TRVJUIElOVE8gcHJvamVjdHMgKHByb2plY3RfbmFtZSwgc3RhcnRfZGF0ZSwgZW5kX2RhdGUpIFZBTFVFUyAoJ1N1cGVyIEFwcCcsICcyMDI1LTAxLTAxJywgJzIwMjUtMTItMzEnKTs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Step 2: Attempt to insert a new row into the&nbsp;<code>project_milestones<\/code>&nbsp;table with a&nbsp;<code>project_id<\/code>&nbsp;value that does not exist in the&nbsp;<code>projects<\/code>&nbsp;table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span>\n  project_milestones (milestone, start_date, end_date, project_id)\n<span class=\"hljs-keyword\">VALUES<\/span>\n  (<span class=\"hljs-string\">'Initiation'<\/span>, <span class=\"hljs-string\">'2025-01-01'<\/span>, <span class=\"hljs-string\">'2025-01-31'<\/span>, <span class=\"hljs-number\">0<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=SU5TRVJUIElOVE8gcHJvamVjdF9taWxlc3RvbmVzIChtaWxlc3RvbmUsIHN0YXJ0X2RhdGUsIGVuZF9kYXRlLCBwcm9qZWN0X2lkKSBWQUxVRVMgKCdJbml0aWF0aW9uJywgJzIwMjUtMDEtMDEnLCAnMjAyNS0wMS0zMScsIDApOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>The database system will issue an error message like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">ERROR:  <span class=\"hljs-keyword\">insert<\/span> <span class=\"hljs-keyword\">or<\/span> <span class=\"hljs-keyword\">update<\/span> <span class=\"hljs-keyword\">on<\/span> <span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-string\">\"project_milestones\"<\/span> violates <span class=\"hljs-keyword\">foreign<\/span> <span class=\"hljs-keyword\">key<\/span> <span class=\"hljs-keyword\">constraint<\/span> <span class=\"hljs-string\">\"project_milestones_project_id_fkey\"<\/span>\nDETAIL:  <span class=\"hljs-keyword\">Key<\/span> (project_id)=(<span class=\"hljs-number\">0<\/span>) <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-keyword\">not<\/span> <span class=\"hljs-keyword\">present<\/span> <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-keyword\">table<\/span> <span class=\"hljs-string\">\"projects\"<\/span>.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The error message indicated that the <code>project_id<\/code> 0 is not present in the <code>projects<\/code> table.<\/p>\n\n\n\n<p>Step 3: Insert a new row into the&nbsp;<code>project_milestones<\/code>&nbsp;table with a valid&nbsp;<code>project_id<\/code>&nbsp;value<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span>\n  project_milestones (milestone, start_date, end_date, project_id)\n<span class=\"hljs-keyword\">VALUES<\/span>\n  (<span class=\"hljs-string\">'Initiation'<\/span>, <span class=\"hljs-string\">'2025-01-01'<\/span>, <span class=\"hljs-string\">'2025-01-31'<\/span>, <span class=\"hljs-number\">1<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=SU5TRVJUIElOVE8gcHJvamVjdF9taWxlc3RvbmVzIChtaWxlc3RvbmUsIHN0YXJ0X2RhdGUsIGVuZF9kYXRlLCBwcm9qZWN0X2lkKSBWQUxVRVMgKCdJbml0aWF0aW9uJywgJzIwMjUtMDEtMDEnLCAnMjAyNS0wMS0zMScsIDEpOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"adding-foreign-key-constraints-to-existing-tables\" id='adding-foreign-key-constraints-to-existing-tables'>Adding FOREIGN KEY Constraints to Existing Tables <a href=\"#adding-foreign-key-constraints-to-existing-tables\" class=\"anchor\" id=\"adding-foreign-key-constraints-to-existing-tables\" title=\"Anchor for Adding FOREIGN KEY Constraints to Existing Tables\">#<\/a><\/h2>\n\n\n\n<p>To add a foreign key constraint to a table, you use the&nbsp;<code>ALTER TABLE ... ADD CONSTRAINT<\/code>&nbsp;statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">ALTER<\/span> <span class=\"hljs-keyword\">TABLE<\/span> foreign_key_table\n<span class=\"hljs-keyword\">ADD<\/span> <span class=\"hljs-keyword\">CONSTRAINT<\/span> constraint_name\n<span class=\"hljs-keyword\">FOREIGN<\/span> <span class=\"hljs-keyword\">KEY<\/span> (column1, column2)\n     <span class=\"hljs-keyword\">REFERENCES<\/span> parent_table(column1, column2)\n     <span class=\"hljs-keyword\">ON<\/span> <span class=\"hljs-keyword\">UPDATE<\/span> update_action\n     <span class=\"hljs-keyword\">ON<\/span> <span class=\"hljs-keyword\">DELETE<\/span> delete_action;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If the tables have data, you must ensure that it is valid before adding a foreign key constraint to the foreign key table. Otherwise, you&#8217;ll encounter a constraint violation error.<\/p>\n\n\n\n<p><strong>Step 1<\/strong>: <a href=\"https:\/\/www.sqltutorial.org\/sql-create-table\/\">Create a table<\/a> called<code>project_tasks<\/code> :<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> project_tasks (\n  task_id <span class=\"hljs-built_in\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> PRIMARY <span class=\"hljs-keyword\">KEY<\/span>,\n  title <span class=\"hljs-built_in\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  completed <span class=\"hljs-built_in\">BOOL<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span> <span class=\"hljs-keyword\">DEFAULT<\/span> <span class=\"hljs-literal\">FALSE<\/span>,\n  start_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  end_date <span class=\"hljs-built_in\">DATE<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>,\n  milestone_id <span class=\"hljs-built_in\">INT<\/span>\n);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=Q1JFQVRFIFRBQkxFIHByb2plY3RfdGFza3MgKCB0YXNrX2lkIElOVCBHRU5FUkFURUQgQUxXQVlTIEFTIElERU5USVRZIFBSSU1BUlkgS0VZLCB0aXRsZSBWQVJDSEFSKDI1NSkgTk9UIE5VTEwsIGNvbXBsZXRlZCBCT09MIE5PVCBOVUxMIERFRkFVTFQgRkFMU0UsIHN0YXJ0X2RhdGUgREFURSBOT1QgTlVMTCwgZW5kX2RhdGUgREFURSBOT1QgTlVMTCwgbWlsZXN0b25lX2lkIElOVCApOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p><strong>Step 2<\/strong>: Add a foreign key constraint to the <code>project_tasks<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">ALTER<\/span> <span class=\"hljs-keyword\">TABLE<\/span> project_tasks\n<span class=\"hljs-keyword\">ADD<\/span> <span class=\"hljs-keyword\">CONSTRAINT<\/span> project_tasks_milestone_id_fkey \n<span class=\"hljs-keyword\">FOREIGN<\/span> <span class=\"hljs-keyword\">KEY<\/span> (milestone_id) \n<span class=\"hljs-keyword\">REFERENCES<\/span> project_milestones (milestone_id);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=QUxURVIgVEFCTEUgcHJvamVjdF90YXNrcyBBREQgQ09OU1RSQUlOVCBwcm9qZWN0X3Rhc2tzX21pbGVzdG9uZV9pZF9ma2V5IEZPUkVJR04gS0VZIChtaWxlc3RvbmVfaWQpIFJFRkVSRU5DRVMgcHJvamVjdF9taWxlc3RvbmVzIChtaWxlc3RvbmVfaWQpOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dropping-foreign-key-constraints\" id='dropping-foreign-key-constraints'>Dropping Foreign Key Constraints <a href=\"#dropping-foreign-key-constraints\" class=\"anchor\" id=\"dropping-foreign-key-constraints\" title=\"Anchor for Dropping Foreign Key Constraints\">#<\/a><\/h2>\n\n\n\n<p>To drop a foreign key constraint, you use the&nbsp;<code>ALTER TABLE<\/code>&nbsp;statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">ALTER<\/span> <span class=\"hljs-keyword\">TABLE<\/span> foreign_key_table\n<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">CONSTRAINT<\/span> fk_name;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>For example, the following statement removes the <code>project_tasks_milestone_id_fkey<\/code> foreign key constraint:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">ALTER<\/span> <span class=\"hljs-keyword\">TABLE<\/span> project_tasks\n<span class=\"hljs-keyword\">DROP<\/span> <span class=\"hljs-keyword\">CONSTRAINT<\/span> project_tasks_milestone_id_fkey;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.sqltutorial.org\/playground\/?q=QUxURVIgVEFCTEUgcHJvamVjdF90YXNrcyBEUk9QIENPTlNUUkFJTlQgcHJvamVjdF90YXNrc19taWxlc3RvbmVfaWRfZmtleTs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"delete-actions\" id='delete-actions'>Delete Actions <a href=\"#delete-actions\" class=\"anchor\" id=\"delete-actions\" title=\"Anchor for Delete Actions\">#<\/a><\/h2>\n\n\n\n<p>When you delete a row in the parent table, the database system needs to decide what to do with the row in the child table.<\/p>\n\n\n\n<p>For example, if you delete a row from the&nbsp;<code>projects<\/code>&nbsp;table, the database system must know what to do with the rows whose&nbsp;<code>project_id<\/code>&nbsp;is related to the deleted project.<\/p>\n\n\n\n<p>By default, the database system does not allow you to delete a row in the parent table if its related rows in the child table exist. If you attempt to do so, the database system rejects the deletion and issues an error.<\/p>\n\n\n\n<p>SQL Deletion Actions for a Foreign Key:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>RESTRICT<\/strong>: You cannot delete a row in the parent table when a row in the child table references the value in the parent table.<\/li>\n\n\n\n<li><strong>SET NULL<\/strong>: When you delete a related row from the parent table, the database system sets the values in the foreign key columns to&nbsp;<code>NULL<\/code>.<\/li>\n\n\n\n<li><strong>SET DEFAULT<\/strong>: When you delete a related row from the parent table, the database system updates the foreign key columns with their default values.<\/li>\n\n\n\n<li><strong>CASCADE<\/strong>: The database system deletes the related rows in the child table when you delete a related row from the parent table.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"update-actions\" id='update-actions'>Update Actions <a href=\"#update-actions\" class=\"anchor\" id=\"update-actions\" title=\"Anchor for Update Actions\">#<\/a><\/h2>\n\n\n\n<p>The update action instructs the database system to handle the rows in the child table when you update related rows in the parent table.<\/p>\n\n\n\n<p>SQL defines the following deletion action for a foreign key:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>RESTRICT<\/strong>: The database system prevents updating the primary key if dependent rows exist in the child table. This is the default behavior.<\/li>\n\n\n\n<li><strong>SET NULL<\/strong>: When you update the primary key values of the parent table, the database system sets the values in the foreign key columns of the related rows to&nbsp;<code>NULL<\/code>.<\/li>\n\n\n\n<li><strong>SET DEFAULT<\/strong>: When you update the primary key values of the parent table, the database system sets the values in the foreign key columns of the related rows to their default values.<\/li>\n\n\n\n<li><strong>CASCADE<\/strong>: When you update the primary key values of the parent table, the database system automatically updates the values in the foreign key columns.<\/li>\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>In practice, you rarely update the primary key values. Therefore, you rarely need the&nbsp;<code>ON UPDATE<\/code>&nbsp;action.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"summary\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the SQL foreign key constraint to enforce referential integrity between two tables.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=foreign-key\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n\n\n\n\n<h2 class=\"wp-block-heading\" id='databases'>Databases <a href=\"#databases\" class=\"anchor\" id=\"databases\" title=\"Anchor for Databases\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">PostgreSQL Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">MySQL Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.mariadbtutorial.com\/mariadb-basics\/mariadb-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">MariaDB Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.oracletutorial.com\/oracle-basics\/oracle-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">Oracle Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-basics\/sql-server-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">SQL Server Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.db2tutorial.com\/db2-basics\/db2-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">Db2 Foreign Key constraint<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.sqlitetutorial.net\/sqlite-foreign-key\/\" target=\"_blank\" rel=\"noreferrer noopener\">SQLite Foreign Key constraint<\/a><\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"581\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\"\n\t\t\t\tdata-post-title=\"SQL Foreign Key Constraint\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"581\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\"\n\t\t\t\tdata-post-title=\"SQL Foreign Key Constraint\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: In this tutorial, you&#8217;ll learn about the SQL foreign key and how to define a foreign key using the FOREIGN KEY constraint. Introduction to SQL Foreign Key # In SQL, a foreign key is a column or a set of columns in a table that references the primary key of another table. The primary [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":43,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-581","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.2 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>The Essential Guide To SQL Foreign Key Constraint<\/title>\n<meta name=\"description\" content=\"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"The Essential Guide To SQL Foreign Key Constraint\" \/>\n<meta property=\"og:description\" content=\"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\" \/>\n<meta property=\"og:site_name\" content=\"SQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-03-17T03:07:56+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\",\"url\":\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\",\"name\":\"The Essential Guide To SQL Foreign Key Constraint\",\"isPartOf\":{\"@id\":\"https:\/\/www.sqltutorial.org\/#website\"},\"datePublished\":\"2016-04-15T15:31:36+00:00\",\"dateModified\":\"2025-03-17T03:07:56+00:00\",\"description\":\"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.sqltutorial.org\/sql-foreign-key\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.sqltutorial.org\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Foreign Key Constraint\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.sqltutorial.org\/#website\",\"url\":\"https:\/\/www.sqltutorial.org\/\",\"name\":\"SQL Tutorial\",\"description\":\"An Interactive SQL Tutorial\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.sqltutorial.org\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"The Essential Guide To SQL Foreign Key Constraint","description":"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/","og_locale":"en_US","og_type":"article","og_title":"The Essential Guide To SQL Foreign Key Constraint","og_description":"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.","og_url":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/","og_site_name":"SQL Tutorial","article_modified_time":"2025-03-17T03:07:56+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/","url":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/","name":"The Essential Guide To SQL Foreign Key Constraint","isPartOf":{"@id":"https:\/\/www.sqltutorial.org\/#website"},"datePublished":"2016-04-15T15:31:36+00:00","dateModified":"2025-03-17T03:07:56+00:00","description":"This tutorial helps you understand SQL foreign key and show you how to define a foreign key using the FOREIGN KEY constraints.","breadcrumb":{"@id":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.sqltutorial.org\/sql-foreign-key\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.sqltutorial.org\/sql-foreign-key\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.sqltutorial.org\/"},{"@type":"ListItem","position":2,"name":"SQL Foreign Key Constraint"}]},{"@type":"WebSite","@id":"https:\/\/www.sqltutorial.org\/#website","url":"https:\/\/www.sqltutorial.org\/","name":"SQL Tutorial","description":"An Interactive SQL Tutorial","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.sqltutorial.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/pages\/581","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/comments?post=581"}],"version-history":[{"count":0,"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/pages\/581\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.sqltutorial.org\/wp-json\/wp\/v2\/media?parent=581"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}