When to Use "ON UPDATE CASCADE" in PostgreSQL?
Last Updated :
04 Apr, 2024
In PostgreSQL, the ON UPDATE CASCADE clause in a foreign key constraint allows for a cascading update behavior between linked tables. This feature automatically updates all matching values in the referencing columns of child tables when a value is changed in the referenced column of the parent table.
In this article, We will explore about ON UPDATE CASCADE in maintaining referential integrity and ensuring consistency in relational databases.
What is ON UPDATE CASCADE in PostgreSQL?
- To specify a cascading update behavior between linked tables in PostgreSQL use the ON UPDATE CASCADE clause in a foreign key constraint.
- When this clause is used PostgreSQL automatically updates all matching values in the referencing columns of the child tables whenever a value is changed in the referenced column of the parent table.
- This helps preserve referential integrity in the database and guarantees that the relationships between the tables stay consistent.
- One of PostgreSQL's most useful features is the ON UPDATE CASCADE clause which makes managing related data easier.
- When a referenced value in the parent table changes there is no longer a need to manually update linked records in the child tables, which lowers the possibility of inconsistent data.
Let's consider several situations in which ON UPDATE CASCADE may be useful:
1. Update Primary Key
- Suppose We want the matching foreign key values in child tables to be updated when changes are made to a parent table's main key.
- To update the user_id in the orders table when the id in the users table is modified, for example if we have a users table with a primary key called id and an orders table with a foreign key called user_id that references the id column in the users table. This may be achieved by using ON UPDATE CASCADE.
Example:
Before updating the changes
--Create Table--
CREATE TABLE parent (
id SERIAL PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id SERIAL PRIMARY KEY,
parent_id INT REFERENCES parent(id) ON UPDATE CASCADE,
child_name VARCHAR(255)
);
-- Insert values--
INSERT INTO parent (name) VALUES ('Parent 1');
INSERT INTO child (parent_id, child_name) VALUES (1, 'Child 1');
-- Check child table--
SELECT * FROM child;
Output:
Before updating the changesAfter Updating the changes
-- Update parent primary key--
UPDATE parent SET id = 100 WHERE id = 1;
--Check child table--
SELECT *FROM child;
Output:
After Updating the changesExplanation: If we update the id of the parent table, the parent_id in the child table will be automatically updated to maintain the referential integrity.
2. By Upholding Relationships
Making sure that the rows in the child table continue to be associated to the appropriate rows in the parent table.
Example:
-- Create parent table--
CREATE TABLE parent (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
-- Create child table with foreign key referencing parent table--
CREATE TABLE child (
id SERIAL PRIMARY KEY,
parent_id INT REFERENCES parent(id) ON UPDATE CASCADE,
child_name VARCHAR(255) NOT NULL
);
-- Insert values--
INSERT INTO parent (name) VALUES ('Parent 1');
INSERT INTO child (parent_id, child_name) VALUES (1, 'Child 1');
INSERT INTO child (parent_id, child_name) VALUES (1, 'Child 2');
-- Check the child table--
SELECT * FROM child;
Output:
Before updating the changesAfter Updating Parent's Table
-- Update the parent table's primary key--
UPDATE parent SET id = 100 WHERE id = 1;
-- Check the child table--
SELECT * FROM child;
Output:
After Updating Parent's Table Explanation: In this example, both rows in the child table that were associated to the parent table's row are updated to reflect the new id when the parent table's id is changed from 1 to 100.
3. Update Foreign Key
Suppose We want to update the corresponding foreign key values in child tables when a foreign key value in the parent table is updated. This comes in handy when there's a requirement to dynamically adjust the relationship between tables.
Example:
--Create Parent table--
CREATE TABLE parent (
id SERIAL PRIMARY KEY,
name VARCHAR(255)
);
--Create Child table--
CREATE TABLE child (
id SERIAL PRIMARY KEY,
parent_id INT REFERENCES parent(id) ON UPDATE CASCADE,
child_name VARCHAR(255)
);
-- Insert values--
INSERT INTO parent (name) VALUES ('Parent 1');
INSERT INTO child (parent_id, child_name) VALUES (1, 'Child 1');
-- Check child table--
SELECT * FROM child;
Output:
Before updating After Updating Changes
-- Update parent foreign key--
UPDATE parent SET id = 100 WHERE id = 1;
-- Check child table--
SELECT * FROM child;
Output:
After Updating Changes Explanation: Referential integrity will be preserved by automatically updating the parent_id in the child_table from 1 to 100Â following the update.
Conclusion
Overall, The ON UPDATE CASCADE feature in PostgreSQL is a powerful tool for managing related data in relational databases. By automatically updating referencing columns in child tables when changes occur in the parent table, ON UPDATE CASCADE helps maintain referential integrity and data consistency.
Similar Reads
When to Use ON UPDATE CASCADE in PL/SQL?
In Oracle PL/SQL, managing the update of related records in child tables can be challenging, especially when dealing with complex data relationships. The ON UPDATE CASCADE option in Oracle provides a powerful solution to automate the update of child records whenever the corresponding parent record i
4 min read
When to Use ON UPDATE CASCADE in SQLite
"ON UPDATE CASCADE" is an important feature in SQLite that simplifies data management and ensures data integrity by automatically propagating changes from a parent table to its related child tables. This feature plays a crucial role in maintaining consistency and reducing the need for manual updates
4 min read
When to Use "ON UPDATE CASCADE" in MySQL
In MySQL, the ON UPDATE CASCADE option in foreign key constraints indicates that anytime an update is made to a row in the parent table, matching rows in child tables are correspondingly updated. This feature provides assurance for referential integrity and consistency of related data in a related s
7 min read
How UPDATE JOIN Works in PostgreSQL?
In PostgreSQL, updating records in one table based on values in another is a common scenario in relational databases. While PostgreSQL does not have a direct UPDATE JOIN syntax like other databases (e.g., MySQL). Hence, it provides a powerful alternative by using the FROM clause in the UPDATE statem
6 min read
PostgreSQL Python - Update Data in Table
In this article, we are going to see how to update existing data in PostgreSQL tables using the pyscopg2 module in Python. In PostgreSQL, the UPDATE TABLE with where clause is used to update the data in the existing table from the database. Syntax: UPDATE <table_name> SET column1 = value1, c
2 min read
PostgreSQL - Creating Updatable Views Using WITH CHECK OPTION Clause
PostgreSQL is the most advanced general purpose open source database in the world. pgAdmin is the most popular management tool or development platform for PostgreSQL. It is also an open source development platform. It can be used in any Operating Systems and can be run either as a desktop applicatio
4 min read
PostgreSQL - Create updatable Views
Views in PostgreSQL provide a way to represent a subset of a real table, selecting certain columns or rows from an ordinary table. They are particularly useful for restricting access to the original table, allowing users to see only a specific portion of it. The table from which a view is created is
3 min read
Subqueries in the WHERE Clause of UPDATE in SQL
In SQL, an UPDATE statement modifies existing records in a table. When updating records, we can use a subquery within the WHERE clause to conditionally update only specific rows based on results from another query. In this article, we will learn how to write Subqueries in the WHERE Clause to Update
4 min read
Bulk update of rows in Postgres DB using psycopg2
PostgreSQL or Postgres is an open-source, relational, SQL complaint, database management system. It allows, the developers, to create complex applications, supporting SQL and JSON querying. It safely stores, and, scales workloads. Psycopg2 is a driver, that is used, for interacting, with Postgres da
6 min read
PostgreSQL - Create table using Python
Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of
3 min read