JIYIK CN >

Current Location:Home > Learning > DATABASE > PostgreSQL >

Foreign Key ON DELETE CASCADE in PostgreSQL

Author:JIYIK Last Updated:2025/04/10 Views:

ON DELETE CASCADEBefore we start looking at different solutions for implementing in PostgreSQL , we will first understand ON DELETE CASCADEwhat is and what it does.

Let's assume you have two tables, one of which inherits from a parent table KEYand uses its values, also called ASSOCIATION. Now suppose the user wants to delete this row in the parent table.

But wait? What happens to the inherited rows in the child table?

You might think that this VIOLATIONwould raise an error. Correct! Fortunately, this does not work and will produce an error.

ERROR:  update or delete on table [your_table] violates foreign key constraint [f_key] on table [your_table]

But what if you don't want to restrict DELETE, but continue to get this row from both tables . This is where we come in.DELETE

Let’s see how it works.

Using in PostgreSQLON DELETE CASCADE

Let's start by creating a Vehicletable.

create table vehicle (
	id int PRIMARY KEY,
	OWNER TEXT
);

Now let's define another BUStable called that will VEHICLEinherit its keys from ID.

create table bus (
	id int PRIMARY KEY references vehicle,
	Model TEXT
);

You can IDsee REFERENCESthe tag at the end of the definition. This means that it now refers to VEHICLEa row in the table, and any operations on that table that do not match IDthe one VEHICLEin the table will be rejected.IDINSERT

Now let's assume that we have some values VEHICLE​​in the table .INSERT

Insert into vehicle values (1, 'mark'), (2, 'john');

Let's also add INSERTa value to BUSthe table.

insert into bus values (2, 'High_Van');

So now BUStable refers VEHICLEto the table KEY``2, which means High_Vanbelongs to John.

Now let's try BUSto remove this entry from .

If you call:

delete from vehicle where id = 2

An error will be returned.

ERROR:  update or delete on table "vehicle" violates foreign key constraint "bus_id_fkey" on table "bus"
DETAIL:  Key (id)=(2) is still referenced from table "bus".

This tells you BUSthat is still referenced in the table KEY``2. Therefore DELETEwill not work. Now let's define DELETEwhat happens if we call .

In BUSthe table, modify IDthe column.

create table bus (
	id int PRIMARY KEY references vehicle ON DELETE CASCADE,
	Model TEXT
);

Now, when we try DELETE, it works perfectly. Why? Because CASCADEtends to delete the rows suggested for in the child table DELETE.

Let's say you'd prefer to use the original method and want to define yours. In that case, you could try ON DELETE CASCADEchanging to ON DELETE RESTRICT, which will ultimately restrict any conflicting DELETEoperations.

You can even use these options in other ways ON UPDATE.

ON CASCADE DELETEA brief description of the problems faced in defining multiple constraints in PostgreSQL

Doing this to all inherited tables ON DELETE CASCADEcreates a problem when you delete rows that reference thousands of tables. This will create a problem, but rolling back any changes is extremely unlikely.

Always make sure to DELETEuse good practices for . If you want CASCADE, call DELETEthe function before and TRANSACTIONkeep checking if an error occurred instead of at the end.

This will keep your database safe and secure and avoid future problems.

We hope you have learned how to perform operations in PostgreSQL ON DELETE CASCADE.

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.

Article URL:

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial