Sample Header Ad - 728x90

Postgres: automatic action (increment count of foreign key) after update

0 votes
1 answer
64 views
How to automate an update in a table, after a change in another table ? Say (please see below) I have a table countries, and a table cities. How to make that, when adding a city in table cities, the total column is automatically updated (incremented for the corresponding city) in the table countries ? Kind of : --------- BEGIN; INSERT INTO cities VALUES ('Tokyo', 'Japan'); UPDATE countries SET total=1 WHERE name='Japan'; COMMIT; , but automatic, **do a countries.the_city.total++ when adding cities.the_city**. Countries: ---------- postgres=# SELECT * FROM countries; name | total -------+------- USA | 0 Japan | 0 (2 rows) Cities: ------- postgres=# SELECT * FROM cities; name | country ------+--------- (0 rows) Commands: --------- CREATE DATABASE geo; \c geo; CREATE TABLE countries ( name VARCHAR(15) PRIMARY KEY, total int ); CREATE TABLE cities ( name VARCHAR(15), country VARCHAR(15), FOREIGN KEY (country) REFERENCES countries(name) ); Context: -------- Standard SQL, or Postgres v16
Asked by ymudyruc (3 rep)
May 6, 2024, 02:48 PM
Last activity: May 6, 2024, 05:23 PM