0
0
PostgreSQLquery~10 mins

UPDATE with RETURNING clause in PostgreSQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - UPDATE with RETURNING clause
Start UPDATE command
Find rows matching WHERE condition
Update specified columns
Collect updated rows
RETURNING clause outputs updated rows
End
The UPDATE command finds rows matching the condition, changes specified columns, then RETURNING outputs the updated rows.
Execution Sample
PostgreSQL
UPDATE employees
SET salary = salary + 500
WHERE department = 'Sales'
RETURNING id, name, salary;
This updates salaries for Sales department employees and returns their id, name, and new salary.
Execution Table
StepActionRows MatchedColumns UpdatedRETURNING Output
1Start UPDATE---
2Find rows WHERE department = 'Sales'Rows with dept='Sales' found: 2--
3Update salary = salary + 5002 rowssalary column updated-
4RETURNING id, name, salary2 rows-[{"id": 3, "name": "Alice", "salary": 3500}, {"id": 5, "name": "Bob", "salary": 4200}]
5End---
💡 All matching rows updated and their new values returned by RETURNING clause.
Variable Tracker
VariableStartAfter Step 3Final
salary of Alice300035003500
salary of Bob370042004200
Key Moments - 2 Insights
Why do we see output rows after UPDATE when normally UPDATE returns only count?
Because of the RETURNING clause (see execution_table step 4), the updated rows are output instead of just a count.
Does RETURNING show old or new values?
RETURNING shows the new updated values after the change (execution_table step 4 shows updated salaries).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, how many rows matched the WHERE condition?
A2
B3
C0
D5
💡 Hint
Check the 'Rows Matched' column at step 2 in execution_table.
At which step does the salary column get updated?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Columns Updated' column in execution_table.
If we remove RETURNING clause, what changes in the output?
ANo rows are updated
BUpdated rows are still returned
COnly count of updated rows is returned
DQuery will fail
💡 Hint
RETURNING clause controls output; without it, UPDATE returns count only.
Concept Snapshot
UPDATE table_name
SET column = value
WHERE condition
RETURNING columns;

- Updates rows matching condition
- RETURNING outputs updated rows
- Useful to see new values immediately
Full Transcript
The UPDATE with RETURNING clause in PostgreSQL first finds rows matching the WHERE condition. Then it updates the specified columns in those rows. After updating, the RETURNING clause outputs the updated rows with the columns requested. This lets you see the new values right away instead of just the count of updated rows. For example, updating salaries in the Sales department and returning id, name, and new salary shows exactly which rows changed and their new data.