Officially out now: The TypeDB 3.0 Roadmap >>

Lesson 4.4: Updating data

The Update query

To update the values of attributes, we use an Update query. An Update query consists of a match clause, a delete clause, and an insert clause. In effect, the Update query deletes an existing attribute of an entity (or relation) and then inserts a new one in its place. Consider the following two queries.

match
$order-38 isa order, has id "o0038";
$dispatched "dispatched" isa status;
delete
$order-38 has $dispatched;

studio fail Do not run

match
$order-38 isa order, has id "o0038";
insert
$order-38 has status "delivered";

studio fail Do not run

When run one after the other, they replace the existing order status "dispatched" with "delivered". We can do this more efficiently using an Update query.

match
$order-38 isa order, has id "o0038";
$dispatched "dispatched" isa status;
delete
$order-38 has $dispatched;
insert
$order-38 has status "delivered";

studio runstudio check Run and commit

In addition to being more efficient and easier for readers to interpret, Update queries are sometimes a necessity if we’re replacing the attribute we’re matching on. In the following query, we match every book that has the genre "art", and replace it with the genre "art and design". Functionally, this represents a rename of the genre without changing the books in it. If we were to try this with a Delete query followed by an Insert query, then the Insert query would have nothing to match on!

match
$book isa book, has $art;
$art "art" isa genre;
delete
$book has $art;
insert
$book has genre "art and design";

studio runstudio check Run and commit

Exercise

Use an Update query to decrease the stock attribute of Pride and Prejudice by one. In order to do so, you will need to first retrieve its current value.

Hint

To get the correct ISBN and current stock, you can use the following query.

match
$pride-prejudice isa book, has title "Pride and Prejudice";
fetch
$pride-prejudice: isbn, stock;
Sample solution
match
$pride-prejudice isa book, has isbn "9780553212150";
$stock 15 isa stock;
delete
$pride-prejudice has $stock;
insert
$pride-prejudice has stock 14;

studio runstudio check Run and commit

Of course, having to retrieve the current stock value before updating it is a bit inconvenient. We’ll learn how to use arithmetic operations to automatically decrement it in a single query in Lesson 7.5.