Languages
[Edit]
EN

MS SQL Server - Create table with FOREIGN KEY

0 points
Created by:
Huzaifa-Ball
475

In this article, we would like to show you how to create a table with FOREIGN KEY in MS SQL Server.

Quick solution:

CREATE TABLE [table1_name] (
    [column1] DATA_TYPE,
    [column2] DATA_TYPE,
    [columnN] DATA_TYPE,
    PRIMARY KEY ([column_name]),
    FOREIGN KEY ([column_name]) REFERENCES [table2_name]([reference_column])
);

Note:

Go to the official documentation to see available DATA_TYPES.

Practical example

In this example, we will create two tables:

  • groups table with two columns:
    • id- with PRIMARY KEY constraint
    • group_name

and users table with three columns:

  • id - with PRIMARY KEY constraint
  • username
  • group_id - which will be our FOREIGN KEY with groups.id column reference

Query:

CREATE TABLE [groups] (
	[id] INT IDENTITY(1,1),
	[group_name] VARCHAR(50) NOT NULL,
	PRIMARY KEY ([id])
);

CREATE TABLE [users] (
	[id] INT IDENTITY(1,1),
	[username] VARCHAR(50) NOT NULL,
	[group_id] INT,
	PRIMARY KEY ([id]),
	FOREIGN KEY ([group_id]) REFERENCES [groups]([id])
);

Result:

MS SQL Server - create a table with PRIMARY KEY
MS SQL Server - create a table with PRIMARY KEY - HeidiSQL
MS SQL Server - create a table with FOREIGN KEY
MS SQL Server - create a table with FOREIGN KEY - HeidiSQL

As we see in the second picture, the group_id column from users table has FOREIGN KEY constraint which refers to the id column from groups table with PRIMARY KEY constraint.

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MS SQL Server - problems

MS SQL Server - Create table with FOREIGN KEY
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join