Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent deletion of the first row in table (PostgreSQL)?

Is it possible to prevent deletion of the first row in table on PostgreSQL side?

I have a category table and I want to prevent deletion of default category as it could break the application. Of course I could easily do it in application code, but it would be a lot better to do it in database.

I think it has something to do with rules on delete statement, but I couldn't find anything remotely close to my problem in documentation.

like image 873
Maiku Mori Avatar asked May 01 '09 04:05

Maiku Mori


People also ask

How do you delete a row from a table in Postgres?

The PostgreSQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows. Otherwise, all the records would be deleted.

What is restrict in PostgreSQL?

From postgresql documentation: RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything.

How do I select specific rows in PostgreSQL?

A Simple SELECT Use the following syntax to retrieve all rows and columns from a table: SELECT * FROM table_name; The asterisk ( * ) character, as mentioned in the explanation of SELECT 's syntax, is short-hand for all non-system columns.

How do I delete triggers in PostgreSQL?

To drop a PostgreSQL trigger, we use the DROP TRIGGER statement with the following syntax: DROP TRIGGER [IF EXISTS] trigger-name ON table-name [ CASCADE | RESTRICT ]; The trigger-name parameter denotes the name of the trigger that is to be deleted.


1 Answers

You were right about thinking of the rules system. Here is a link to an example matching your problem. It's even simpler than the triggers:

create rule protect_first_entry_update as
  on update to your_table
  where old.id = your_id
  do instead nothing;
create rule protect_first_entry_delete as
  on delete to your_table
  where old.id = your_id
  do instead nothing;

Some answers miss one point: also the updating of the protected row has to be restricted. Otherwise one can first update the protected row such that it no longer fulfills the forbidden delete criterion, and then one can delete the updated row as it is no longer protected.

like image 158
j.p. Avatar answered Sep 29 '22 17:09

j.p.