DBMS LAb-2
DBMS LAb-2
3SELECT
4'Kicking in the wall' AS book_name, '9781608681563' AS
book_isbn,
Updating Data
Whenever you need to change the value of certain fields in one or more rows,
you will come across the UPDATE statement. In its most simple form, the syntax
is the following:
1UPDATE table_name
2SET field1 = X,
3field2 = Y
4WHERE field1 = Z;
sql
Where field1 and field2 are two fields from table_name whose values will be
changed to X and Y, respectively - but only on the record where the current
value of field1 is Z.
You can add as many field = value pairs as needed, as long as they are
separated by commas.
If you omit the WHERE clause, those fields will be updated for all the records in
the table. To minimize the likelihood of human error during this operation, you
can follow a simple rule of thumb: do a SELECT first. If you utilize the
same WHERE clause and it returns the expected row(s), you can go ahead with
the UPDATE.
For example, let's say we need to correct customer Jill Devera's name to Jack
and Jill Devera and the address to 62 Fillmore Ave. To begin, let us execute
the query below:
1SELECT * FROM customers WHERE customer_name = 'Jill
Devera';
sql
As we can see in Fig. 3, we can proceed to update the customer's name and
address on file if we are sure it is the right record. To do so, let us begin by
deleting everything to the left of the WHERE clause:
1WHERE customer_name = 'Jill Devera';
sql
Then add on top:
1UPDATE customers
Fig. 3 also shows another SELECT after the UPDATE took place that confirms it
was successful. Note that since the name was changed, we
used customer_id in the WHERE clause.
Deleting Data
Before we attempt to delete any records, it is worthy and well to keep the
same precautions as with the update operation. In short, we are only safe to
proceed if the SELECT returns the correct row(s) when you apply the same filter
condition.
Most of the scenarios where you might want to delete data are already familiar
to you. Whenever you unsubscribe from an email newsletter, sell a product
(either online or in-person), or donate office furniture, the DELETE statement is
likely involved. In the first example, you request that your address be removed
from a distribution list. The second and third scenarios assume that you keep
track of the products you offer and the office assets under your care using a
relational database (as you should!).
To delete the row(s) of table_name where the current value of field1 is Z, do
as follows:
1DELETE FROM table_name
2WHERE field1 = Z;
sql
Sad news - our customer Tim Murphy has canceled his membership so now
we need to remove his name from the customers table. First off, we need to
make sure he has returned all the books he ever borrowed from the library:
1SELECT customer_id FROM customers WHERE customer_name =
'Tim Murphy';
CREATE TABLE