How can we use the UPDATE statement?

UPDATE customer SET name='Alex', email='' WHERE id=1005;
UPDATE tableName SET credit=credit - !payment!;

When the new value equals to existing value, MySQL ignores the assignment.

UPDATE reports a row-affected count to indicate how many rows were actually changed. This count doesn't include rows that were selected for updating but for which the update didn't change any columns from their current values.

If a table contains a TIMESTAMP column that has ON UPDATE CURRENT_TIMESTAMP in its definition, that column is updated automatically only if another column changes value. An UPDATE that sets columns to their current values does not change the TIMESTAMP. If you need the TIMESTAMP to be updated for every UPDATE, you can set it explicitly to the value of the CURRENT_TIMESTAMP function.

Some client programs or APIs enable you to ask the MySQL server to return a rows-matched count rather than rows-affected count. This causes the row count to include all rows selected for updating, even if their columns weren't changed from their existing values.

How can we control the order of which rows are updated?

To control the order of which rows are updated first (to avoid possible duplicate key violation):

UPDATE people SET id = id - 1 ORDER BY id;

UPDATE also allows a LIMIT clause, which places a limit on the number of records updated. ORDER BY and LIMIT may be used together in the same UPDATE statement.

How can we update columns in one table using values from another table?

update $chld_table as A ,$this->table_name as B set A.$fld = B.$fld where A.relation_id = B.contact_id and =1;

update emailActivity_team ea,
    select activityID, group_concat(contactID) as contactIDs
    from emailContactStatus ecs
    where ecs.status = 'draft'
    group by activityID
  ) as t1
  set ea.contactIDs = t1.contactIDs
  where ea.activityID = t1.activityID;

Normally, and update statement consist of only one table. This SQL consists of two tables. The second table is created by a sub-select statement. This SQL also join the two tables and update the first table using values from second table. The more general form:

UPDATE t1, t2 SET = WHERE =;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License