Documentation
 
 
 

5.2. Updating Data

The modification of data that is already in the database is referred to as updating. You can update individual rows, all the rows in a table, or a subset of all rows. Each column can be updated separately; the other columns are not affected.

To perform an update, you need three pieces of information:

  1. The name of the table and column to update,

  2. The new value of the column,

  3. Which row(s) to update.

Recall from Chapter 4 that SQL does not, in general, provide a unique identifier for rows. Therefore it is not necessarily possible to directly specify which row to update. Instead, you specify which conditions a row must meet in order to be updated. Only if you have a primary key in the table (no matter whether you declared it or not) can you reliably address individual rows, by choosing a condition that matches the primary key. Graphical database access tools rely on this fact to allow you to update rows individually.

For example, this command sets the salaries of all employees that belonging to department number 10 to 1000.

UPDATE emp SET sal = 1000 WHERE deptno = 10;

This may cause zero, one, or many rows to be updated. It is not an error to attempt an update that does not match any rows.

Let's look at that command in detail: First is the key word UPDATE followed by the table name. As usual, the table name may be schema-qualified, otherwise it is looked up in the path. Next is the key word SET followed by the column name, an equals sign and the new column value. The new column value can be any scalar expression, not just a constant, as in the example above. For example to raise the salaries of all the employees in dept 10 by 10% you could use:

UPDATE emp SET sal = sal * 1.10 WHERE deptno = 10;

As you see, the expression for the new value can also refer to the old value. We also left out the WHERE clause. If it is omitted, it means that all rows in the table are updated. If it is present, only those rows that match the condition after the WHERE are updated. Note that the equals sign in the SET clause is an assignment while the one in the WHERE clause is a comparison, but this does not create any ambiguity. Of course, the condition does not have to be an equality test. Many other operators are available (see Chapter 8). But the expression needs to evaluate to a Boolean result.

You can also update more than one column in an UPDATE command by listing more than one assignment in the SET clause. For example:

UPDATE emp SET sal = sal + 100, comm = 25 WHERE deptno = 10;

 
 ©2004-2007 EnterpriseDB All Rights Reserved