PostgreSQL Trigger on Insert or Update
19,034
Since you haven't mentioned the RDBMS, I assume it is Oracle. Below is the trigger. If you are using another RDBMS, tweak the code to fit the syntax.
CREATE OR REPLACE TRIGGER TRG_CAR
AFTER INSERT OR UPDATE ON CAR
FOR EACH ROW
BEGIN
IF :new.FUEL THEN
INSERT INTO FUEL (CAR_ID) VALUES (:new.ID);
ELSE
DELETE FROM FUEL WHERE CAR_ID = :new.ID;
END IF;
END;
Author by
Ozzy
Updated on June 05, 2022Comments
-
Ozzy almost 2 years
I have two tables. I want to create a trigger on the
car
table which will insert or delete on thefuel
table depending on a certain value.Car
id - SERIAL fuel - BOOLEAN
Fuel
car_id - INTEGER
I am not including any row data as the description of the trigger does not need it.
Basically, I want to create a trigger on the
Car
table that:- Runs on an insert or update.
- Inserts
Car.id
intoFuel
table ifCar.fuel is true
. - If
Car.fuel is false
, the trigger should delete all rows in theFuel
table whereFuel.car_id = Car.id
.
How would I do this?
EDIT: To clarify I am using Postgres
-
a_horse_with_no_name about 11 yearsI don't think
IF :new.FUEL THEN
will work in Oracle as it does not have a BOOLEAN SQL datatype (only PL/SQL has). So the:NEW
record can not have a boolean column. I actually think Ozzy is using Postgres (psql
is Postgres' command line tool)