0% found this document useful (0 votes)
48 views

SQL For Data Manipulation: Modifying Data in Tables and Views

This document discusses SQL commands for data manipulation in Oracle databases. It covers the INSERT, UPDATE, and DELETE commands and how they are used to modify data in tables and views. Examples are provided for inserting rows with literal values or subqueries, updating rows by setting column values or using subqueries, and deleting rows using a WHERE clause. Restrictions on modifying data in views are also outlined.

Uploaded by

Arsalan Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

SQL For Data Manipulation: Modifying Data in Tables and Views

This document discusses SQL commands for data manipulation in Oracle databases. It covers the INSERT, UPDATE, and DELETE commands and how they are used to modify data in tables and views. Examples are provided for inserting rows with literal values or subqueries, updating rows by setting column values or using subqueries, and deleting rows using a WHERE clause. Restrictions on modifying data in views are also outlined.

Uploaded by

Arsalan Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

SQL for Data Manipulation

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

Modifying Data in Tables and Views


The real power of SQL derives from its operation on many rows of data at one time. A single line of SQL code can change every row in a Table. You can use the same techniques you use to gather many rows together for a report to modify many rows at the same time. The breakdown: the three basic commands are UPDATE, INSERT, and DELETE. Each command has some interesting subtleties. You can insert, update, or delete rows from Tables and views. You must have the corresponding privilege (INSERT to insert rows and so forth) on the Table or view. Modifying the rows in a view actually modifies the rows in the underlying Table. You can use special comments in an INSERT, UPDATE, or DELETE statement to pass instructions (hints) to help the Oracle8 optimizer choose the best execution plan for the statement.
CrossReference

The section on Tuning in Chapter 15 describes how to construct hints as comments in your SQL commands.

226

Chapter 10 3 SQL for Data Manipulation

Modifying Data in a View


Some restrictions apply when using INSERT, UPDATE, and DELETE commands on a view rather than on a Table. If the view was created with the WITH CHECK OPTION, you can only update or insert into the view if the resulting data satisfies the views defining query. You cannot modify data using a view if the views defining query contains any of the following constructs: 3 join 3 set operator (UNION, UNION ALL, MINUS, INTERSECT) 3 GROUP BY clause 3 group function (MAX, MIN, AVG, and so forth) 3 DISTINCT operator

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.

Chapter 10 3 Updating Rows

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.

Update using subqueries


The second variation on the UPDATE command has a great amount of flexibility because it uses a subquery a query within the UPDATE command. The basic format:
UPDATE tablename SET (columnname, columnname2, ...) = (SELECT columnname3, columnname4, ... FROM tablename2

228

Chapter 10 3 SQL for Data Manipulation

WHERE 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 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.

Update using correlated subqueries


Although the third variation on the UPDATE command is difficult to understand, it is one of the most flexible UPDATE commands. This variation is similar to the preceding UPDATE command syntax except the subquery is slightly different. The basic format:

Chapter 10 3 Updating Rows

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

Chapter 10 3 SQL for Data Manipulation

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.

Inserting with literals


Heres the way to insert a row where you know exactly how the row will appear:
INSERT INTO tablename (columnname1, columnname2,...) values (value1, value2, ...);

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

your Table. Heres the code to add a seventh variety:


INSERT INTO SALAD_TYPE (SALAD_TYPE, DESCRIPTION_TEXT, ORGANIC_FLAG, PRICE_PER_POUND) VALUES (7, Caesar, YES, 9.50);

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

Chapter 10 3 Inserting Rows

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);

Inserts using a subquery


The strategy is similar to the subquery used in updates. Inserting using a subquery enables you to insert as many rows returned by the subquery. Review the section on updates using subqueries for a detailed look at how to write a subquery. The basic format for this kind of insert:
INSERT INTO tablename (column1, column2, ... ) subquery;

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

Chapter 10 3 SQL for Data Manipulation

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.

Substituting a Subquery for a Table Name


The actual Table or view to be modified is usually listed in an INSERT, UPDATE, or DELETE command. You can use a subquery in place of the Table or view name. The subquery is treated as if it were a view. Therefore, the same rules apply here as when modifying a view (see the sidebar Modifying Data in a View at the beginning of the chapter).
Example

An example of this command form:


INSERT INTO (SELECT BREAD_NO, BREAD_NAME FROM BREAD) VALUES (10,Poppy Seed);

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.

You might also like