0

I have 3 tables in my postgreSQL

item_table:

id  item_id
------------
1   1234
2   5678

account_table:

item_id     account_id
----------------------
2       abcd

payment_table:

account_id  payment_status
--------------------------
abcd        good    

Description

  1. item_id in the account_table is the id of item_table
  2. account_id of the payment_table is the account_id of account_table

I want to delete the entry from all tables associated with item_id from the item_table

Example : If my item_id is 5678 then I want to delete entries from all tables in which the ids are connected to each other.

How to achieve this in PostgreSQL?

2 Answers 2

2

If account.item_id is declared as a foreign key to item.id, you might declare that foreign key as 'ON DELETE CASCADE'. Then deleting a row from 'item' would cascade the deletion 'account'.

Repeat as needed for other tables.

It could be I've misunderstood you, but it's easy enough for you to test.

Sign up to request clarification or add additional context in comments.

3 Comments

None of these tables are connected to each other using foreign key. Is there a solution in that case?
@SravanJS: Worst case, run one DELETE statement per table, probably wrapped in a transaction. Wrap that in a function.
Tables are not connected by FK. Is there a solution in this case? Yes, add the missing FKs. Without them you have data integrity issues - meaning bad data. After all with the values posted what the value of a row in payment table with account_id =' xyz', or an account table row with item_id = 42? They are just wrong and can generate correct but invalid/misleading results. FK would prevent them from being in the database.
1

If you need to delete from three tables then you need to run three DELETE statements:

delete from payment_table
where account_id in (select account_id
                     from account_table
                     where item_id in (select id 
                                       from item_table
                                       where item_id = 5678));

delete from account_table
where item_id in (select id 
                  from item_table
                  where item_id = 5678);

delete from item_table
where item_id = 5678;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.