]> begriffs open source - ai-pg/blob - full-docs/txt/dml-update.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / dml-update.txt
1
2 6.2. Updating Data #
3
4    The modification of data that is already in the database is referred to
5    as updating. You can update individual rows, all the rows in a table,
6    or a subset of all rows. Each column can be updated separately; the
7    other columns are not affected.
8
9    To update existing rows, use the UPDATE command. This requires three
10    pieces of information:
11     1. The name of the table and column to update
12     2. The new value of the column
13     3. Which row(s) to update
14
15    Recall from Chapter 5 that SQL does not, in general, provide a unique
16    identifier for rows. Therefore it is not always possible to directly
17    specify which row to update. Instead, you specify which conditions a
18    row must meet in order to be updated. Only if you have a primary key in
19    the table (independent of whether you declared it or not) can you
20    reliably address individual rows by choosing a condition that matches
21    the primary key. Graphical database access tools rely on this fact to
22    allow you to update rows individually.
23
24    For example, this command updates all products that have a price of 5
25    to have a price of 10:
26 UPDATE products SET price = 10 WHERE price = 5;
27
28    This might cause zero, one, or many rows to be updated. It is not an
29    error to attempt an update that does not match any rows.
30
31    Let's look at that command in detail. First is the key word UPDATE
32    followed by the table name. As usual, the table name can be
33    schema-qualified, otherwise it is looked up in the path. Next is the
34    key word SET followed by the column name, an equal sign, and the new
35    column value. The new column value can be any scalar expression, not
36    just a constant. For example, if you want to raise the price of all
37    products by 10% you could use:
38 UPDATE products SET price = price * 1.10;
39
40    As you see, the expression for the new value can refer to the existing
41    value(s) in the row. We also left out the WHERE clause. If it is
42    omitted, it means that all rows in the table are updated. If it is
43    present, only those rows that match the WHERE condition are updated.
44    Note that the equals sign in the SET clause is an assignment while the
45    one in the WHERE clause is a comparison, but this does not create any
46    ambiguity. Of course, the WHERE condition does not have to be an
47    equality test. Many other operators are available (see Chapter 9). But
48    the expression needs to evaluate to a Boolean result.
49
50    You can update more than one column in an UPDATE command by listing
51    more than one assignment in the SET clause. For example:
52 UPDATE mytable SET a = 5, b = 3, c = 1 WHERE a > 0;