EN
PostgreSQL - Create table with FOREIGN KEY
0 points
In this article, we would like to show you how to create a table with FOREIGN KEY
in PostgreSQL.
Quick solution:
xxxxxxxxxx
1
CREATE TABLE "table1_name" (
2
"column1" DATA_TYPE,
3
"column2" DATA_TYPE,
4
"columnN" DATA_TYPE,
5
PRIMARY KEY ("column_name"),
6
FOREIGN KEY ("column_name") REFERENCES "table2_name"("reference_column")
7
);
Note:
Go to the official documentation to see available
DATA_TYPES
.
In this example, we will create two tables:
groups
table with two columns:id
- withPRIMARY KEY
constraintgroup_name
and users table with three columns:
id
- withPRIMARY KEY
constraintusername
group_id
- which will be ourFOREIGN KEY
withgroups.id
column reference
Query:
xxxxxxxxxx
1
CREATE TABLE "groups" (
2
"id" SERIAL,
3
"group_name" VARCHAR(50) NOT NULL,
4
PRIMARY KEY ("id")
5
);
6
7
CREATE TABLE "users" (
8
"id" SERIAL,
9
"username" VARCHAR(50) NOT NULL,
10
"group_id" INTEGER,
11
PRIMARY KEY ("id"),
12
FOREIGN KEY ("group_id") REFERENCES "groups"("id")
13
);
Result:


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.