Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test run an UPDATE statement in PostgreSQL?

How can I test an UPDATE statement for example to see if it would work, for example if it would actually update rows etc?

Is there a way to simulate it easily?

like image 576
user1154863 Avatar asked Feb 08 '12 21:02

user1154863


People also ask

How update works in Postgres?

PostgreSQL implements multiversioning by keeping the old version of the table row in the table – an UPDATE adds a new row version (“tuple”) of the row and marks the old version as invalid. In many respects, an UPDATE in PostgreSQL is not much different from a DELETE followed by an INSERT .

How do I check for an update in SQL?

SQL UPDATE Syntax To use the UPDATE method, you first determine which table you need to update with UPDATE table_name . After that, you write what kind of change you want to make to the record with the SET statement. Finally, you use a WHERE clause to select which records to change.

Do Postgres views update automatically?

Updatable Views. Simple views are automatically updatable: the system will allow INSERT , UPDATE and DELETE statements to be used on the view in the same way as on a regular table.

How do I rollback the last query in PostgreSQL?

The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. The ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.


1 Answers

Use a transaction to wrap your update statement and a select query (to test the update) and then always roll it back.

Example:

BEGIN;  UPDATE accounts SET balance = balance - 100.00     WHERE name = 'Alice';  SELECT balance FROM accounts WHERE name = 'Alice';  ROLLBACK; -- << Important! Un-does your UPDATE statement above! 

A transaction typically ends with a commit but since you're just testing and do not want the changes to be permanent you will just roll back.

like image 148
Paul Sasik Avatar answered Sep 22 '22 16:09

Paul Sasik