Let's say that my database has 2 tables (Person & Car):
Person (personID, number_of_cars)
Car (carID, owner)
where the owner
attribute in Car
refers to the personID
in the Person table. Now, what I want is that whenever I insert a new car object into the Car table, then the number_of_cars
of the owner will be incremented by one. The only solution that I have come up so far is to write the UPDATE
statement right after the INSERT
statement, something like this:
INSERT INTO Car (carID, owner) VALUES (1, 1);
UPDATE Person SET number_of_cars = number_of_cars + 1 WHERE personID = 1;
However, I don't feel like this is a good way of writing it because then I would have to do the update after every single insert statement. So what is a good way to achieve this in PostgreSQL?