A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/delete-postgresql-cascade.php below:

Website Navigation


DELETE CASCADE in PostgreSQL for Relational Integrity

DELETE CASCADE in PostgreSQL for Relational IntegrityLast update on December 31 2024 13:03:29 (UTC/GMT +8 hours)

PostgreSQL: DELETE with CASCADE

The DELETE ... CASCADE operation in PostgreSQL is used to remove rows from a table and automatically delete dependent rows in other related tables. This feature is beneficial when dealing with relational databases with foreign key constraints, as it maintains referential integrity by cascading deletions through related tables.

This guide provides an in-depth explanation of the CASCADE option with syntax, examples, and detailed code walkthroughs.

Syntax:

The basic syntax of the DELETE statement with cascading effects relies on the table’s foreign key constraints defined with the ON DELETE CASCADE clause:

 
DELETE FROM table_name 
WHERE condition;

Key Point: The CASCADE effect is triggered by the foreign key constraint and does not require explicit inclusion in the DELETE statement.

Example 1: Creating Tables with CASCADE

Code:

-- Create a parent table
CREATE TABLE authors (
    author_id SERIAL PRIMARY KEY, -- Unique identifier for authors
    name VARCHAR(100) NOT NULL -- Author's name
);

-- Create a child table with a foreign key referencing authors
CREATE TABLE books (
    book_id SERIAL PRIMARY KEY, -- Unique identifier for books
    title VARCHAR(200) NOT NULL, -- Title of the book
    author_id INT REFERENCES authors(author_id) ON DELETE CASCADE -- Foreign key with CASCADE
);

Explanation:

Example 2: Inserting Data

Code:

-- Insert data into the authors table
INSERT INTO authors (name) 
VALUES 
('J.K. Rowling'), 
('George R.R. Martin');

-- Insert data into the books table
INSERT INTO books (title, author_id) 
VALUES 
('Harry Potter and the Philosopher''s Stone', 1),
('A Game of Thrones', 2),
('A Clash of Kings', 2);

Explanation

Example 3: Deleting Data with CASCADE

Code:

-- Delete an author
DELETE FROM authors 
WHERE author_id = 2;

-- Query the books table to check remaining records
SELECT * FROM books;

Explanation

Output of the Books Table

After executing the above deletion:

book_id title author_id 1 Harry Potter and the Philosopher's Stone 1

Key Considerations

Common Errors

Best Practices

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4