SQL For Data Manipulation: Modifying Data in Tables and Views
SQL For Data Manipulation: Modifying Data in Tables and Views
ow that you know how to construct queries (from Chapter 9) to view data, you understand how to choose particular rows out of a table. You call upon this ability when modifying data in the database as well. If you want to change the address and zip code of one customer row, you must know how to tell Oracle8 which row to modify. This chapter describes how to modify data using the three SQL commands: INSERT, UPDATE, and DELETE. Each command has several variations illustrated with examples.
10
C H A P T E R
In This Chapter
Updating rows with literals or subqueries Inserting one row with literal values Inserting many rows with a subquery Deleting rows using a Where clause Substituting a subquery for a table name in SQL commands
The section on Tuning in Chapter 15 describes how to construct hints as comments in your SQL commands.
226
Updating Rows
See Reference Section
UPDATE
The UPDATE command enables you to modify existing Table data. The following three sections describe the three basic UPDATE command forms. The final section on UPDATE shows how to combine the three forms into one statement.
Using literals
The most common form of the UPDATE command manipulates Columns using data from the same row. The basic format of the statement:
UPDATE tablename SET columnname = expression, columnname2 = expression2, WHERE clause;
Replace tablename with your Tables name and replace columnname and columnname2 with the names of the Columns you want to modify. expression (and expression2) can represent a literal (such as todays date), another Column, or a combination of both. Replace the WHERE clause with any valid WHERE clause to tell Oracle8 which rows you want to include in the update. You can update all the rows in a Table by omitting the WHERE clause.
227
Example
You can use another Column (or even the Column you are currently updating in the SET clause) in the same Table. Heres an example where you add RED to the list of colors of your fish.
UPDATE FISH SET COLOR = COLOR || ,RED WHERE FISH_NAME = Wesley;
You can set a Columns value to null with the NULL keyword. For example, set all rows to a null DEATH_DATE with this statement:
UPDATE FISH SET DEATH_DATE = NULL;
Heres another example. You head the ticket sales committee for an upcoming benefit dinner. The TICKET Table initially had separate Columns for FIRST_NAME and LAST_NAME. Then you decide to combine those Columns into a new Column called FULL_NAME. Now you want to combine every first and last name in the Table and put the results in this new Column. Heres the statement:
UPDATE TICKET SET FULL_NAME = HOLDER_FIRST_NAME || || HOLDER_LAST_NAME;
Oracle8 replies:
9 rows updated
This statement updates every row in the Table because no Where clause is on the end. You now want to update only the rows of ticket holders who bought their tickets before the 10th of October. Here is the UPDATE command for the early birds:
UPDATE TICKET SET EXTRA_TICKET = YES WHERE PURCHASE_DATE < TO_DATE(10-OCT-97);
Oracle8 replies:
3 rows processed.
228
Replace tablename with the Table to be updated. Replace columnname, columnname2, ... with a list of Columns to be updated. The subquery is everything inside the parentheses after the equal sign. You can place any query inside the subquery as long as the Columns in the subquery (columnname3, columname4, ...) match the Columns in the UPDATE command.
Note
The subquery must return exactly one row. If the subquery returns no rows then the Column is assigned a null. Subqueries may select from the Table being updated. Notice the two WHERE clauses. The first (subquery where clause) corresponds to the subquery SELECT statement while the second one (update where clause) corresponds to the UPDATE.
Example
You run an art gallery. You have a Table named MONTHLY_SALES. You update MONTHLY_SALES at the end of the month with the sum of all purchased art from the DAILY_SALES Table. Heres your UPDATE command for January 1998:
UPDATE MONTHLY_SALES SET (SALES_AMOUNT) = (SELECT SUM(SALES_AMOUNT) FROM DAILY_SALES WHERE SALES_DATE BETWEEN TO_DATE(01-JAN-98) AND TO_DATE(31-JAN-98)) WHERE SALES_MONTH = TO_DATE(JAN-98,MON/YY); ( You may consider formatting the Update statement in this manner making it easier to read)
Oracle8 replies:
1 row processed.
Enclose the subquery in parentheses. The first WHERE clause in this statement only relates to the subquery while the second WHERE clause relates to the UPDATE statement. As a result, only one row (January 1998) in the TOTAL_SALES_PER_MONTH Table is updated.
229
UPDATE tablename SET (columnname, columnname2, ...) = (SELECT columnname3, columnname4, ... FROM tablename2 WHERE tablename2.columnname5 = tablename.columnname6 and subquery where clause) WHERE update where clause;
Replace tablename with the Table to be updated. Replace columnname, columnname2, ... with a list of Columns to be updated. The subquery constitutes everything inside the parentheses after the equal sign. You can place any query inside the subquery. Columns selected in the subquery must correspond with the UPDATE commands list of Columns. The subquery must return exactly one row for each row updated. Notice the two WHERE clauses. The first (beginning at the WHERE and ending with subquery where clause) corresponds to the correlated subquery SELECT statement. Replace tablename2.columnname5 = tablename.columnname6 with a join clause connecting (correlating) the Table youre updating with the Table in the subquery. The second WHERE clause (update where clause) corresponds to the UPDATE command and tells Oracle8 which rows to update with the retrieved subquery data.
Example
You have two Tables named SALAD_TRAY and SALAD_TYPE. You want to increase the selling price of all organic salad trays. A salad type is organic when the SALAD_TYPE.ORGANIC_FLAG Column contains YES. The SQL code for changing the selling price of all organic salad trays follows:
UPDATE SALAD_TRAY A SET (SELLING_PRICE) = SELLING_PRICE * 1.20 WHERE YES = (SELECT ORGANIC_FLAG FROM SALAD_TYPE B WHERE A.SALAD_TYPE = B.SALAD_TYPE)
Oracle8 replies:
4 rows processed.
In the last line of the WHERE clause, the alias A indicates A.SALAD_TYPE in the subquery refers to the SALAD_TRAY Table, which is not in the subquery but in the UPDATE command. The alias B indicates the second B.SALAD_TYPE refers to the SALAD_TYPE Table in the FROM clause of the subquery.
Tip
When using UPDATE in SQL*Plus or SQL Worksheet, remember ROLLBACK can undo the updates. You can mix literals, subqueries, and correlated subqueries in the same UPDATE command.
230
Inserting Rows
See Reference Section
INSERT
The INSERT command has two forms similar to the UPDATE command: the first uses literals while the second uses a subquery. The next two sections describe each variation on the INSERT theme.
Replace tablename with the Table in which you insert the row. Replace columnname1, columnname2, . . . with the Column names in which you insert data.
Note
The entire list of Columns (columnname1, columnname2,...) can be omitted as long as your list of values matches the Tables Columns exactly. Replace value1, value2,... with the actual data. You must enclose everything except numbers in single quotes. Dates must be either in the standard Oracle format (dd-mon-yy) and in single quotes or enclosed in a TO_DATE function.
Example
You add a new type of salad to your lunch counter. Add a new Column to the
SALAD_TYPE Table for this new salad type. You currently have six types of salads in
Oracle replies:
1 row processed.
Tip
Insert a row without specifying all the Columns by only listing the Columns you wish to populate with data. If DEFAULT VALUE is defined for that Column, the omitted Columns are assigned the DEFAULT VALUE. If no DEFAULT VALUE is defined, the Column is set to null. You must include every NOT NULL Column in the Table in your list except those with DEFAULT VALUE assigned. The Chapter 12 section Tables describes how to assign the DEFAULT VALUE and the NOT NULL parameters to a Column using SQL. The Chapter 7 section Tables describes the same concepts when using Schema Manager.
CrossReference
231
Place null values into a Column using the NULL keyword. For example, the last Column will contain nulls in the inserted row using this command:
INSERT INTO SALAD_TRAY values (1,Garden Greens,NO, NULL);
The main difference between UPDATE and INSERT is the INSERT command has no parentheses around the subquery. Omit the list of Columns if you include every Column in the Table and list them in the same order in which they appear in the Table.
Example
You acquire a mailing list Table (MILLIES_MAILING_LIST) and import the Table into the Oracle8 database. Now you want to insert all the rows into your CLIENT Table. Heres the command:
INSERT INTO CLIENT SELECT CUST_ID+125, NAME_OF_CLIENT, STREET_ADDRESS || ||CITY_STATE_ZIP, NULL FROM MILLIES_MAILING_LIST;
Oracle8 replies:
4 rows processed.
Here are some interesting points about this example code: 3 The list of CLIENT Columns was omitted, meaning all Columns in the SELECT subquery must appear in an order corresponding to the order of the CLIENT Columns. 3 MILLIES_MAILING_LIST has a two-Column address you combine in your ADDRESS Column by using the CONCATENATE function. 3 You already have CUST_ID from 1 to 125; add 125 to MILLIES_MAILING_LIST.CUST_ID to make sure you get a unique CUST_ID. 3 MILLIES_MAILING_LIST does not have a COUNTRY Column; substitute NULL in this Column for all the inserted rows.
232
Deleting Rows
The DELETE command is simple:
DELETE FROM tablename WHERE clause;
Replace tablename with the actual Table name. Replace clause with any valid WHERE clause you would put in a query. This command can also include subqueries or correlated subqueries.
Example
You remove the Cinnamon Swirl bread from your bakery line. Heres the code to use a subquery to delete selected rows for the Cinnamon Swirl bread recipe from the RECIPE Table:
DELETE FROM RECIPE WHERE BREAD_NO = (SELECT BREAD_NO FROM BREAD WHERE BREAD_NAME = Cinnamon Swirl);
Oracle8 replies:
4 rows processed.
This code uses a subquery that finds the BREAD_NO for Cinnamon Swirl bread. Then the main WHERE clause uses that number to choose which rows to delete.
Tip
Test your DELETE statement by creating a SELECT statement using the same WHERE clause. With this approach, you can look at what rows are selected for deletion before you delete them.
Here, two Columns are selected in the subquery and, therefore, only two Columns need to be listed in the VALUES clause.
Chapter 10 3 Summary
233
Summary
The ability to write queries helps you write commands to modify data in Tables and views. Only specific kinds of views are allowed when modifying data. When modifying data using a view, the underlying Tables data actually gets modified. An UPDATE command modifies data in existing rows in a Table or view. The UPDATE command has two basic variations: written using literals for the modified data, or written to update data based on a subquery. The INSERT command adds a new row (or set of new rows) to a Table or view. Like the UPDATE command, you use literals to designate the values to be inserted into the Table or view. In addition, the INSERT subquery style enables you to insert many rows at once using the results of a subquery to define the values in the new rows. The DELETE command removes rows from a Table or view. Use a WHERE clause to tell Oracle8 which rows you want to delete. An unusual variation of the INSERT and UPDATE commands lets you replace the Table name with a subquery. Use this command like a view name, except you do not need to define the view in the Data Dictionary.