SQL Server Create Table With Foreign Key Example Tutorial

In the dynamic world of database management, efficiency and integrity are key. One way to ensure this is through the use of foreign keys, which serve to impose referential integrity between tables in a SQL Server database. In this article, we'll explore how to create a table with a foreign key constraint in SQL Server, with a practical example to illustrate the process.

SQL Server Create table command
SQL Server Create table command

Understanding foreign keys is fundamental to mastering SQL Server's relational model. They not only ensure data consistency but also enhance the performance and security of your database.

Create Tables in SQL Server with T-SQL
Create Tables in SQL Server with T-SQL

Defining the Tables: A Prerequisite

Before creating a table with a foreign key constraint, you need to understand the tables involved. Typically, a foreign key relationship exists between two tables, the parent table and the child table. The parent table contains the primary key or unique index that the foreign key will reference.

Remodel Poorly Designed SQL Server Database Tables
Remodel Poorly Designed SQL Server Database Tables

Let's consider a simple example involving two hypothetical tables, 'School' and 'Student'. Here, 'School' is the parent table, with 'SchoolID' as the primary key, and 'Student' is the child table with 'SchoolID' as the foreign key.

Creating the Parent Table ('School')

SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial

First, we'll create the 'School' table. This table will store information about various schools, with 'SchoolID' serving as the primary key. Here's the SQL command to create this table:

```sql CREATE TABLE School ( SchoolID INT PRIMARY KEY, SchoolName NVARCHAR(50), Principal NVARCHAR(50), Location NVARCHAR(50) ); ```

In this command, 'SchoolID' is defined as the primary key, signifying that it must contain unique values and cannot be null.

Creating the Child Table ('Student')

How To Insert Results From Stored Procedure To A Temp Table In SQL Server?
How To Insert Results From Stored Procedure To A Temp Table In SQL Server?

Next, we'll create the 'Student' table. This table will store student details, with a 'SchoolID' column referencing the 'SchoolID' in the 'School' table.

Here's the SQL command to create this table:

```sql CREATE TABLE Student ( StudentID INT IDENTITY(1,1) PRIMARY KEY, StudentName NVARCHAR(50), SchoolID INT, FOREIGN KEY(SchoolID) REFERENCES School(SchoolID) ); ```

In this command, 'SchoolID' is defined as a foreign key, referencing the 'SchoolID' in the 'School' table. This means that every 'SchoolID' in the 'Student' table must match an 'SchoolID' in the 'School' table, ensuring referential integrity.

Free Microsoft SQL Server Book
Free Microsoft SQL Server Book

The final step in creating a table with a foreign key constraint is to insert data into the tables. This, along with updating and deleting records, is where you'll really see the benefits of foreign key constraints in action.

Inserting Data: Testing Referential Integrity

Difference between Primary and Foreign keys in SQL [Answer]
Difference between Primary and Foreign keys in SQL [Answer]
SQL Primary Key - SQL Made Easy
SQL Primary Key - SQL Made Easy
SQL - Using where, like and underscore operators
SQL - Using where, like and underscore operators
SQL Server: Crear una tabla
SQL Server: Crear una tabla
SQL TRUNCATE Table
SQL TRUNCATE Table
Free SQL Database Book
Free SQL Database Book
SQL Cheatsheet Diagram
SQL Cheatsheet Diagram
Check If Column Exists In Table Of SQL Server | My Tec Bits
Check If Column Exists In Table Of SQL Server | My Tec Bits
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
SQL Table Structure Explained for Beginners 📊
SQL Table Structure Explained for Beginners 📊
SQL String Functions Archives
SQL String Functions Archives
SQL in 60 days
SQL in 60 days
a table with different types of text on it
a table with different types of text on it
SQL - Find salesman commission details of given customer
SQL - Find salesman commission details of given customer
an image of a table with the names and numbers for different types of data sources
an image of a table with the names and numbers for different types of data sources
SQL Table Queries | Create, Select, Insert & Update Tables
SQL Table Queries | Create, Select, Insert & Update Tables
an image of the server list for windows and mac oss servers, with different types of
an image of the server list for windows and mac oss servers, with different types of
an image of the server list
an image of the server list
Get The List Of Temporal Tables In SQL Server DB
Get The List Of Temporal Tables In SQL Server DB
a table that has some words on it
a table that has some words on it

Before inserting data into the 'Student' table, ensure that the corresponding 'SchoolID' exists in the 'School' table. If not, SQL Server will raise an error.

Let's insert some data into the 'School' and 'Student' tables and observe how SQL Server enforces referential integrity:

Inserting Data into the 'School' Table

Here's how you can insert data into the 'School' table:

```sql INSERT INTO School (SchoolID, SchoolName, Principal, Location) VALUES (1, 'JFK High', 'Ms. Thompson', 'New York'), (2, 'Lincoln Middle', 'Mr. Davis', 'Chicago'), (3, 'Washington Elementary', 'Mrs. Smith', 'Los Angeles'); ```

In this command, we're inserting three records into the 'School' table.

Inserting Data into the 'Student' Table

Now, let's try to insert data into the 'Student' table with a 'SchoolID' that does not exist in the 'School' table:

```sql INSERT INTO Student (StudentName, SchoolID) VALUES ('John Doe', 4); ```

This command will raise an error because 'SchoolID' 4 does not exist in the 'School' table. This is how foreign key constraints ensure data integrity in your SQL Server database.

In conclusion, understanding and utilizing foreign keys in SQL Server is crucial for maintaining data consistency and accuracy in your database. By creating tables with foreign key constraints, you can enhance the reliability and performance of your database operations. So, start experimenting with foreign keys today to improve your SQL Server database management skills!"

Related Articles

Trigger Sql Server Inserted What Is Sql Academy Sql Set Variable Example Pl Sql Trigger Before Insert Example Create Trigger Pl Sql Example Create Table If Not Exists Sql Server Example Trigger Sql Script Trigger In Sql Server With Example Wc3 Sql Tutorial How Long To Learn Sql To Get A Job Reddit