To create a PostgreSQL stored procedure that automatically updates an updated_at column with the current timestamp when a record is updated, you can use a trigger and a function. Here’s how you can create such a stored procedure:
- First, you need to create a function that will update the
updated_atcolumn. This function will be called by a trigger whenever an update operation is performed on a specific table.
CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql;
In this function:
CREATE OR REPLACE FUNCTION update_updated_at()creates a new function namedupdate_updated_at.RETURNS TRIGGERspecifies that the function returns a trigger type.NEW.updated_at = NOW();updates theupdated_atcolumn of the record being modified with the current timestamp.RETURN NEW;returns the updated record.
- Next, you can create a trigger that fires before an
UPDATEoperation on your table. This trigger will call theupdate_updated_at()function.
CREATE TRIGGER trigger_update_updated_at BEFORE UPDATE ON your_table FOR EACH ROW EXECUTE FUNCTION update_updated_at();
In this trigger:
CREATE TRIGGER trigger_update_updated_atcreates a new trigger namedtrigger_update_updated_at.BEFORE UPDATE ON your_tablespecifies that the trigger will fire before anUPDATEoperation on a table namedyour_table. Replaceyour_tablewith the name of your table.FOR EACH ROWindicates that the trigger will operate on each row being updated.EXECUTE FUNCTION update_updated_at();specifies that theupdate_updated_at()function will be executed before theUPDATEoperation.
With this setup, whenever you perform an UPDATE operation on the specified table, the updated_at column will automatically be updated with the current timestamp without the need to modify your SQL queries directly.