Menu
CoddyTech

Update Selected Rows

Part of the SQL Foundations section of Coddy's PostgreSQL journey. Lesson 17 of 22.

UPDATE changes existing rows. SET assigns new values and WHERE limits which rows change. Without WHERE every row is eligible. RETURNING shows the updated values.

Input table products:

idnamecategorypricestockactivenote
1Maptravel125TrueNULL
2Notebookbooks80TrueRecycled
3Atlasbooks243FalseNULL
4Mughome128TrueBlue
5lamphome302FalseClearance
6Mini maptravel610TrueNULL
UPDATE products SET stock = stock + 2 WHERE id = 4 RETURNING id, stock;

Mug stock changes from 8 to 10. The expression reads the old stock to calculate the new value. A precise condition is essential because UPDATE is a stored change, unlike a SELECT expression.

Use SET to calculate new values and WHERE to restrict UPDATE. RETURNING exposes the new row values.

challenge icon

Challenge

Medium

Receive five extra units of product id 2. Update its stock and return id and stock.

The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.

Try it yourself

-- Write your SQL here.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in SQL Foundations

Practice on your own: PostgreSQL playground