0

im a newbie to PostgreSQL, is there any way that i can make some tuples not deletable if some condition holds? to be specific, suppose i have:

Table Males( Name_A, Profession)

Table Students( Names_B, Date_birth)

where Names_B references Names_A, how can i make sure that only those Names_A are "not deletable" whose Date_birth="xx/yy/zz"

sorry if i couldnt clearly explain it, havnt found anything in DDL using NOT NULL constraint to write this up.

Thanks in advance for the help!

5
  • 2
    What do you mean by "not deletable"? The NOT NULL constraint has nothing to do with the ability to delete. Jan 3, 2011 at 18:13
  • An attempt to delete a row with a specific Date_birth is rejected, while other rows with different Date_birth value can be deleted
    – Newbie123
    Jan 3, 2011 at 18:57
  • I'm sure you can do this with a trigger that grabs the deletes and just doesn't do anything if those values match up. Jan 3, 2011 at 19:02
  • Could you tell me abit how i could implement it? Thanks for the reply.
    – Newbie123
    Jan 3, 2011 at 19:08
  • can also take a look at dba.stackexchange.com/a/160346/99065
    – ritesh
    Feb 21, 2019 at 11:05

3 Answers 3

1
CREATE FUNCTION protect_delete() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    IF OLD.date_birth = 'xx/yy/zz' THEN  -- don't actually use this date format
        RETURN NULL;  -- don't delete
    ELSE
        RETURN OLD;
    END IF;
END;
$$;

CREATE TRIGGER protect_delete BEFORE DELETE ON students FOR EACH ROW
    EXECUTE PROCEDURE protect_delete();
1
  • or RAISE 'deleting this row not permitted' rather than just RETURN NULL
    – araqnid
    Jan 3, 2011 at 22:35
1

You can use a PostgreSQL rule:

create rule rule_test as 
  on delete to test 
  -- old is a reference to your table 
  where old.birth = '2011-1-1' -- or whatever condition you want 
  do instead nothing;

One a big table this may run faster since this will modify the query itself and rewrite the query with the condition instead of checking each row. (Triggers may be more powerful and easier to understand if you are planning to do a lot of this type of stuff.)

0
0

See Postgres trigger documentation for information on creating triggers. It sounds like you want a row level trigger.

"A row-level trigger fired before an operation ... can return NULL to skip the operation for the current row. This instructs the executor to not perform the row-level operation that invoked the trigger (the insertion or modification of a particular table row). "

So within the trigger test for your condition and return null to prevent the deletion, return the trigger row to allow the deletion to continue.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.