The UPDATE statement allows you to update a single record or multiple records in a table.
The syntax for the UPDATE statement is:
<code> UPDATE table
SET column = expression
WHERE predicates;</code>
Example #1 - Simple example
Let's take a look at a very simple example.
<code> UPDATE suppliers
SET name = 'HP'
WHERE name = 'IBM';</code>
This statement would update all supplier names in the suppliers table from IBM to HP.
Example #2 - More complex example
You can also perform more complicated updates.
You may wish to update records in one table based on values in another table. Since you can't list more than one table in the UPDATE statement, you can use the EXISTS clause.
For example:
<code> UPDATE suppliers
SET supplier_name = ( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS
( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);</code>
Whenever a supplier_id matched a customer_id value, the supplier_name would be overwritten to the customer name from the customers table.
The syntax for the UPDATE statement is:
<code> UPDATE table
SET column = expression
WHERE predicates;</code>
Example #1 - Simple example
Let's take a look at a very simple example.
<code> UPDATE suppliers
SET name = 'HP'
WHERE name = 'IBM';</code>
This statement would update all supplier names in the suppliers table from IBM to HP.
Example #2 - More complex example
You can also perform more complicated updates.
You may wish to update records in one table based on values in another table. Since you can't list more than one table in the UPDATE statement, you can use the EXISTS clause.
For example:
<code> UPDATE suppliers
SET supplier_name = ( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS
( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);</code>
Whenever a supplier_id matched a customer_id value, the supplier_name would be overwritten to the customer name from the customers table.
Comments
Post a Comment