Foreign key syntax in PostgreSQL
In our article, we mainly work on the PostgreSQL application called pgAdmin [app. number]
, which can be downloaded from the PostgreSQL website. Therefore, we hope that you already have the application installed or another alternative where you can run the queries we provide as a solution.
Today, we will learn how to use it in PostgreSQL FOREIGN KEYS
.
References
To enforce a foreign key relationship
in PostgreSQL, use
So let's start by creating our two tables. The first one is going to be a identity_number
table with all the people in it id
.
create table identity_number(
id int not null,
PRIMARY KEY (id)
);
The second table is person_details
table which stores the information of all persons along with their ids referenced from the first table.
create table person_details(
identity int not null references identity_number,
name varchar(50) not null,
dob date not null
);
You will see in this query that the references the table identity_number
. identity
Therefore, the constraint person_details
in identity
now uses identity_number
the in table .id
foreign_key
But how does our database know which key in the table it is referencing?
In the first table, we have id
defined as PRIMARY KEY
. Therefore, when we reference identity_number
the table, it automatically references the existing PRIMARY KEY
.
And since a table cannot have more than one primary key, it makes perfect sense.
We do hope you know why only the parent table's PRIMARY
key can be FOREIGN
the key, right? If it is not unique, 多对多
the relationship will violate data integrity.
Therefore, we always choose PRIMARY KEY
as FOREIGN KEY
.
However, if you want to be more specific, you can use this.
identity int not null references identity_number(id),
or
FOREIGN KEY(identity) references identity_number(id)
);
Now let's test this. So we will go ahead and insert some values into both tables.
insert into identity_number values(1), (2), (3);
insert into person_details values(1, 'John', '2001-04-04'), (4, 'Mack', '2001-05-05');
What happens if you run this? Because there is no value for in the first 4
table id
.
So when we insert the dataset (4, 'Mack', '2001-05-05')
into the child table:, person_details
it throws an error.
Output:
ERROR: insert or update on table "person_details" violates foreign key constraint "person_details_identity_fkey"
DETAIL: Key (identity)=(4) is not present in table "identity_number".
Reference
Possible enhancements to methods
in PostgreSQL
Even though the above method works fine in almost all cases, you may encounter errors due to app version issues or other situations.
In this case, you can try the following code.
create table person_details(
identity int not null,
constraint fk_identity foreign key (identity) references identity_number (id),
name varchar(50) not null,
dob date not null
);
This explicitly mentions the with FOREIGN KEY RELATIONSHIP
the name CONSTRAINT
and establishes the connection.
If you have already created the tables you may be able ALTER
to add relations later using the statement.
alter table person_details
add constraint fk_identity
foreign key (identity)
references identity_number (id);
多对多
Foreign key constraints on relations
in PostgreSQL
Now let's make three different tables, one for cat
which friends are a specific one dog
and another for which have them person
.
people:
create table person(
id int not null PRIMARY KEY,
name varchar(50) not null
);
dog:
create table dog(
tag int PRIMARY KEY,
owner_id int references person(id)
);
cat:
create table cat(
animal_friend_tag int references dog on delete cascade,
owner_id int references person,
PRIMARY KEY(animal_friend_tag, owner_id)
);
Now let us insert some values into these three tables.
insert into person values(1, 'Mack'), (2, 'John'), (3, 'Anthony');
insert into dog values(11, 1), (12, 2), (13, 3);
insert into cat values(11, 1), (12, 3);
So, there are three dogs; 11
belongs Mack
, 12
belongs John
, and 13
belongs Anthony
.
Also, there are two cats, the first cat has a friend 11
and an owner Mack
, and the second cat has a friend 12
and an owner Anthony
.
If we tend to remove the dog 11
, we will get an error. Why? Because the cat also has 11
as a friend, so removing the dog will make this row become null
.
Output:
ERROR: update or delete on table "dog" violates foreign key constraint "cat_animal_friend_tag_fkey" on table "cat"
DETAIL: Key (tag)=(11) is still referenced from table "cat".
So to avoid this error and remove dependencies on this dog
, cat
we can add the following statement.
animal_friend_tag int references dog on delete cascade
ON DELETE CASCADE
will also delete cat. If you use:
animal_friend_tag int references dog on delete restrict
It will throw again EXCEPTION VIOLATION ERROR
.
You can also use:
animal_friend_tag int references dog on delete set null;
or
animal_friend_tag int references dog on delete set default;
But this will only work if the variable being declared is not set to NOT NULL
. Since our variable is set to NOT NULL
, this will throw a Violation Exception.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Terminate the PostgreSQL connection
Publish Date:2025/04/11 Views:199 Category:PostgreSQL
-
In this article, we will learn how to terminate a PostgreSQL session. Any open connections are run by background processes or tasks, PSQL which may no longer exist despite exiting the user interface or command line tool. Use ps -ef or grep
Single query to rename and change column type in PostgreSQL
Publish Date:2025/04/11 Views:166 Category:PostgreSQL
-
This article describes how to rename a column and change its type in PostgreSQL using only a single query. Renaming and changing column types in MySQL In MySQL , if you want to change the column type and rename it, you can use a simple stat
Joining columns using Select in PostgreSQL
Publish Date:2025/04/11 Views:176 Category:PostgreSQL
-
MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi
Using CASE in PostgreSQL
Publish Date:2025/04/11 Views:124 Category:PostgreSQL
-
This article shows how to use the statement in PostgreSQL CASE . CASE How to use the statement in PostgreSQL case Statements are similar to those in general-purpose programming languages if-else . But in SQL, if you want to write IF-ELSE ,
Using NOT IN with subqueries in PostgreSQL
Publish Date:2025/04/11 Views:93 Category:PostgreSQL
-
NOT IN The inverts the result of NOT simply using IN the operator. NOT IN The right side of the operator must have a subquery in which multiple columns are returned to check whether the expression matches the data. NOT IN Tends to return tr
Using variables in PostgreSQL
Publish Date:2025/04/11 Views:171 Category:PostgreSQL
-
This article will demonstrate how we can declare and assign values to variables in PostgreSQL. In PostgreSQL, DECLARE variables are declared using Often you will need variables in your PL/SQL scripts. In DECLARE the section called , y
Connect to PostgreSQL using a password
Publish Date:2025/04/11 Views:171 Category:PostgreSQL
-
This article shows various ways to connect to PostgreSQL using a password. It can be through the command line, pgpass a file, PGPASSWORD an environment variable or a connection string. Connecting to PostgreSQL with a password using the comm
Deleting a database in PostgreSQL via PSQL
Publish Date:2025/04/11 Views:166 Category:PostgreSQL
-
There are two ways to access PostgreSQL objects and databases on your system. One is through an interface, such as a graphical interface like PGADMIN, and the other is the basic command line tool psql. Today, we will look at DROP DATABASE t
Using the database in PostgreSQL
Publish Date:2025/04/11 Views:132 Category:PostgreSQL
-
This article demonstrates connecting to a database, creating a new database, and creating a table in PostgreSQL. Available databases in PostgreSQL You can run the following command after opening the Postgres command line to view all availab