Start learning free

LESSON 51 OF 173 · BACKEND: SQL

Change Rows with UPDATE in Java

Practice

So far your queries only read rows. UPDATE changes rows that are already in a table. You write the table's name, then SET with a column and its new value. The new value may use the old one: SET stock = stock + 10 adds 10 to each row's stock.

WHERE picks the rows to change, just like in a SELECT. For example, this gives the lamp a stock of 5 and leaves every other row as it was:

UPDATE products
SET stock = 5
WHERE name = 'Lamp';

Without a WHERE, an UPDATE changes every row of the table. That is the classic mistake, so always check the WHERE before you run an UPDATE.

runScript(db, query) runs your statement, then show prints each product's name, category and price. It must print:

name | category | price
Mug | kitchen | 12
Notebook | office | 8
Lamp | home | 29
Pen | office | 3
Plant | home | 15
Teapot | kitchen | 22
Stapler | office | 10
Gift card | NULL | 50
(8 rows)

Your task: in query, raise the price of every product in the 'office' category by 1. All the other products keep their price.


Assignment
Follow the Coding Tutorial to write the UPDATE statement in query, one clause per line.


Hint
On the right of = in SET, a column's name means its old value. Text such as 'office' goes in single quotes, inside the Java string's double quotes. Each query += piece ends with a space, so the clauses don't run together.


STEP 1 OF 3
    Ctrl + Enter to check

    Sql Update in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free