Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
112 views

SQL Insert, Delete, Update: Session 8, 9

The document discusses SQL statements for modifying data in a database, including INSERT, UPDATE, and DELETE. INSERT adds new rows of data to a table. UPDATE modifies existing data in tables by changing column values that meet the WHERE clause criteria. DELETE removes rows from a table where the WHERE clause evaluates to TRUE. The document provides examples of each statement's syntax and use cases for modifying data.

Uploaded by

Subhadip Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

SQL Insert, Delete, Update: Session 8, 9

The document discusses SQL statements for modifying data in a database, including INSERT, UPDATE, and DELETE. INSERT adds new rows of data to a table. UPDATE modifies existing data in tables by changing column values that meet the WHERE clause criteria. DELETE removes rows from a table where the WHERE clause evaluates to TRUE. The document provides examples of each statement's syntax and use cases for modifying data.

Uploaded by

Subhadip Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

SQL INSERT, DELETE, Session 8 , 9

UPDATE
MODIFYING DATA IN THE
DATABASE
1. INSERT Adds new rows of data to a table

2. DELETE Removes rows of data from a table

3. UPDATE Modifies existing data in the database


UPDATE
 The UPDATE statement is used to change the values in one or more columns and
in one or more rows.
 The UPDATE statement is used to modify the existing records in a table
 To change a value in a column, you simply assign an expression to the column.
 UPDATE is very powerful – you can end up changing thousands of rows
 Most of the time you’ll want to update only one or a few rows.
 SQL processes the UPDATE statement by going through the table row by row,
updating those rows for which the search condition yields a TRUE result and
skipping over those for which the search condition yields a FALSE or NULL result.
UPDATE STATEMENT
The UPDATE statement has only three clauses: UPDATE, SET, and an optional
WHERE clause

UPDATE table_name
SET column1 = value1,
column2 = value2, ...
WHERE condition;

Fig. The syntax diagram of the Update Statement


THE SET CLAUSE
• The SET clause in the UPDATE statement is a list of assignments separated by
commas.
• Each assignment identifies a target column to be updated and specifies how to
calculate the new value for the target column.
• Each target column should appear only once in the list; there should not be two
assignments for the same target column.
CustomerI CustomerName ContactName Address City PostalCode Country
D
1 Alex Smith Alex John Volkspark Berlin 12209 Germany
2 Anna Paul Anna Worli Mumbai 5021 India
3 Antonio Antonio Moreno Mataderos 2312 Mexico 5023 Mexico
4 Amanda Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Belinda Belinda Mary Berguvsvägen 8 Luleå S-958 22 Sweden

UPDATE Customers
SET ContactName = ‘Alex John Smith', City= 'Frankfurt'
WHERE CustomerID = 1;

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alex Smith Alex John Smith Volkspark Frankfurt 12209 Germany
2 Anna Paul Anna Worli Mumbai 5021 India
3 Antonio Antonio Moreno Mataderos 2312 Mexico 5023 Mexico
4 Amanda Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Belinda Belinda Mary Berguvsvägen 8 Luleå S-958 22 Sweden
EXAMPLE 1 – UPDATING ALL
THE ROWS IN A TABLE
PRODUCTS

QuantityonHan
ProductNo ProductName ProductDesc Price d CategoryID
1205 Axe Tool 500 100 1
1206 Hammer Tool 300 25 1
1207 Chisel Tool 250 30 1
“Increase the retail price of all products by 10 percent”
“Change products by increasing the retail price by 10 percent”
Update the products table by setting the retail price equal to the retail price plus 10 percent of
the price

UPDATE Products
SET Price = Price + (0.1 * Price)
EXAMPLE 2 – UPDATING
SELECTED ROWS
PRODUCTS
ProductNo ProductName ProductDescription Price QuantityonHand CategoryID
1205 Axe Tool 500 100 1
1206 Hammer Tool 300 25 1
1207 Chisel Tool 250 30 1
1305 Kurta Apparel 1500 60 2
1306 Shorts Apparel 900 80 2
1307 Shirts Apparel 2000 50 2

“Modify products by increasing the price by 4 percent for products that are apparels (categoryID
2).”

Update the products table by setting the price equal to price times 1.04 for all products in category
T2
UPDATE Products SET Price = Price * 1.04 WHERE CategoryID = 2
IN CLASS EXERCISE
Raise the credit limit for Acme
Manufacturing to $60,000 and reassign
the company to Mary Jones (employee
number 109).

UPDATE CUSTOMERS
SET CREDIT_LIMIT = 60000.00, CUST_REP =
109
WHERE COMPANY = 'Acme Mfg.';

1 row updated. Customers Table


Transfer all salespeople from the Chicago office (number 12) to the New York office
(number 11) and lower their quotas by 10 percent.

UPDATE SALESREPS
SET REP_OFFICE = 11, QUOTA = .9 * QUOTA
WHERE REP_OFFICE = 12;
IN CLASS EXERCISE
Reassign all customers served by
employee numbers 105, 106, or 107 to
employee number 102.

UPDATE CUSTOMERS
SET CUST_REP = 102
WHERE CUST_REP IN (105, 106, 107);

Customers Table
Assign a quota of $100,000 to any salesperson who currently has no quota.

UPDATE SALESREPS
SET QUOTA = 100000.00
WHERE QUOTA IS NULL;
EXAMPLE
Increase the credit limit for First Corp. to $75,000, you would use the SQL UPDATE
statement
UPDATE CUSTOMERS SET CREDIT_LIMIT = 75000.00 WHERE COMPANY = 'First Corp.';

Raise the quota for all salespeople by $15,000

UPDATE SALESREPS SET QUOTA = QUOTA + 15000.00


UPDATING ALL THE ROWS
Raise all quotas by 5 percent

UPDATE SALESREPS
SET QUOTA = 1.05 * QUOTA;

UPDATE statement without a WHERE clause performs a bulk update of the entire
table, as demonstrated in the preceding example.
Customers

UPDATE WITH SUBQUERY


Subqueries can play an important role in the
UPDATE statement because they let you
select rows to update based on information
contained in other tables.

Raise by $5000 the credit limit of any


customer who has placed an order for
more than $25,000.
UPDATE CUSTOMERS
SET CREDIT_LIMIT = CREDIT_LIMIT + Orders
5000.00
WHERE CUST_NUM IN (SELECT DISTINCT
CUST FROM ORDERS WHERE AMOUNT >
25000.00);
DELETE
A row of data is typically deleted from a database when the entity represented by the row
disappears from the outside world.
For example, in the sample database:
• When a customer cancels an order, the corresponding row of the ORDERS table must be
deleted.
• When a salesperson leaves the company, the corresponding row of the SALESREPS table
must be deleted.
• When a sales office is closed, the corresponding row of the OFFICES table must be deleted.
If the salespeople in the office are terminated, their rows should be deleted from the
SALESREPS table as well. If they are reassigned, their REP_OFFICE column values must
be updated.
The smallest unit of data that can be deleted from a relational database is a single row.
DELETE STATEMENT

Removes selected rows of data from a single table.


The FROM clause specifies the target table containing the rows.
The WHERE clause specifies which rows of the table are to be deleted.
Remove Henry Jacobsen from the database.

DELETE FROM SALESREPS WHERE NAME = 'Henry Jacobsen';


IN CLASS EXERCISE
Remove all orders for InterCorp (customer number 2126).

DELETE FROM ORDERS WHERE CUST = 2126;

SQL applies the WHERE clause to each row of the ORDERS table, deleting those where the
search condition yields a TRUE result and retaining those where the search condition yields a
FALSE or NULL result.

Delete all orders placed before November 15, 2007.

DELETE FROM ORDERS WHERE ORDER_DATE < '2007-11-15';


Delete all rows for customers served by Bill Adams, Mary Jones, or Dan Roberts
(employee numbers 105, 109, and 101).

DELETE FROM CUSTOMERS WHERE CUST_REP IN (105, 109, 101);

Delete all salespeople hired before July 2006 who have not yet been assigned a quota

DELETE FROM SALESREPS WHERE HIRE_DATE < '2006-07-01' AND


QUOTA IS NULL;
DELETING ALL ROWS
The WHERE clause in a DELETE statement is optional, but it is almost always present. If the
WHERE clause is omitted from a DELETE statement, all rows of the target table are deleted.

Delete all orders.


Delete from orders;

Although this DELETE statement produces an empty table, it does not erase the
ORDERS table from the database. The definition of the ORDERS table and its
columns is still stored in the database. The table still exists, and new rows can still be
inserted into the ORDERS table with the INSERT statement. To erase the definition of
the table from the database, the DROP TABLE statement
DELETE WITH SUBQUERY
DELETE statements with simple search conditions, select rows for deletion based
solely on the contents of the rows themselves.
Sometimes the selection of rows must be made based on data from other tables.
For example, suppose you want to delete all orders taken by Sue Smith.
Without knowing her employee number, you can’t find the orders by consulting the
ORDERS table alone. To find the orders, you could use a two-table query

Find the orders taken by Sue Smith.

SELECT ORDER_NUM, AMOUNT FROM ORDERS, SALESREPS


WHERE REP = EMPL_NUM AND NAME = 'Sue Smith';
ERROR !!!!
DELETE FROM ORDERS, SALESREPS
WHERE REP = EMPL_NUM AND NAME = 'Sue Smith';

You can’t use a join in a DELETE statement. The way to handle the request is with
one of the subquery search conditions. Here is a valid form of the DELETE
statement that handles the request:

DELETE FROM ORDERS WHERE REP = (SELECT EMPL_NUM FROM SALESREPS WHERE
NAME = 'Sue Smith’);
The subquery finds the employee number for Sue Smith, and the WHERE clause then selects the orders
with a matching value
IN CLASS EXERCISES
Delete customers served by salespeople whose sales are less than 80 percent of
quota.

DELETE FROM CUSTOMERS WHERE CUST_REP IN (SELECT EMPL_NUM


FROM SALESREPS WHERE SALES < (.8 * QUOTA));

Delete any salesperson whose current orders total less than 2 percent of their quota

DELETE FROM SALESREPS WHERE (.02 * QUOTA) > (SELECT


SUM(AMOUNT) FROM ORDERS WHERE REP = EMPL_NUM);
INSERT – ADDING DATA INTO
THE DATABASE
A new row of data is typically added to a relational database when a new entity
represented by the row appears in the outside world.
For example, in the sample database:

1. When you hire a new salesperson, a new row must be added to the SALESREPS
table to store the salesperson’s data
2. When a salesperson signs a new customer, a new row must be added to the
CUSTOMERS table, representing the new customer
3. When a customer places an order, a new row must be added to the ORDERS
table to contain the order data.
ADDING DATA
The smallest unit of data that can be added to a relational database is a single row. In general, a SQL-
based DBMS provides three ways to add new rows of data to a database:

• Single-row INSERT A single-row INSERT statement adds a single new row of data to a table. It is commonly used
in daily applications—for example, data entry programs.
1
• Multirow INSERT A multirow INSERT statement extracts rows of data from another part of the database and adds
them to a table. It is commonly used, for example, in end-of-month processing when old rows of a table are moved
2 to an inactive table, or when monthly results are summarized into a table that has been set up to hold them.

• Bulk load A bulk load utility adds data to a table from a file that is outside of the database. It is commonly used to
initially load the database or to incorporate data downloaded from another computer system or collected from many
3 sites.
THE SINGLE-ROW INSERT
STATEMENT
The single-row INSERT statement, adds a new row to a table.
The INTO clause specifies the table that receives the new row (the target table), and
the VALUES clause specifies the data values that the new row will contain.
The column list indicates which data value goes into which column of the new row.
Suppose you just hired a new salesperson, Henry Jacobsen, with the following
personal data:
Name: Henry Jacobsen
Age: 36 Add Henry Jacobsen as a new salesperson.
Employee Number: 111
Title: Sales Manager
INSERT INTO SALESREPS (NAME,
AGE, EMPL_NUM, SALES, TITLE,
Office: Atlanta (office number 13) HIRE_DATE, REP_OFFICE)
Hire Date: July 25, 2008 VALUES ('Henry Jacobsen', 36, 111,
Quota: Not yet assigned 0.00, 'Sales Mgr', '2008-07-25', 13);
Year-to-Date Sales: $0.00
INSERTING A SINGLE ROW
INSERTING VALUES
When SQL inserts a new row of data into a table, it automatically assigns a NULL
value to any column whose name is missing from the column list in the INSERT
statement.
In this INSERT statement, which added Mr. Jacobsen to the SALESREPS table, the
QUOTA and MANAGER columns were omitted:

INSERT INTO SALESREPS (NAME, AGE, EMPL_NUM, SALES, TITLE, HIRE_DATE,


REP_OFFICE)
VALUES ('Henry Jacobsen', 36, 111, 0.00, 'Sales Mgr’, '2008-07-25', 13);

INSERT statement can become lengthy if there are many columns of data, but its format is still
very straightforward
INSERTING NULL VALUES
ORDERS
AMOUNT – 2340.00 Add this entry into orders.
MFR- ACI INSERT INTO ORDERS (AMOUNT,
PRODUCT - 41004 MFR, PRODUCT, QTY,
QTY - 20 ORDER_DATE,
ORDER_DATE – current date
ORDER_NUM, CUST, REP) VALUES
(2340.00, 'ACI', '41004', 20,
ORDER_NUM - 113069
CURRENT_DATE, 113069, 2126,
CUST - 2126 The INSERT statement uses the system
111);
constant CURRENT DATE in its VALUES
REP- 111
clause, causing the current date to be
inserted as the order date.
INSERTING NULL VALUES
INSERT INTO SALESREPS (NAME, AGE, EMPL_NUM, SALES, TITLE,
HIRE_DATE, REP_OFFICE) VALUES ('Henry Jacobsen', 36, 111, 0.00,
'Sales Mgr', '2008-07-25', 13);

OR

INSERT INTO SALESREPS (NAME, AGE, EMPL_NUM, SALES, QUOTA,


TITLE, MANAGER, HIRE_DATE, REP_OFFICE) VALUES ('Henry
Jacobsen', 36, 111, 0.00, NULL, 'Sales Mgr', NULL, '2008-07-25', 13);
INSERTING ALL COLUMNS
SQL allows you to omit the column list from the INSERT statement. When the
column list is omitted, SQL automatically generates a column list consisting of all
columns of the table, in left-to-right sequence. This is the same column sequence
generated by SQL when you use a SELECT * query.
INSERT INTO SALESREPS
VALUES (111, 'Henry Jacobsen', 36, 13, 'Sales Mgr', '2008-07-25', NULL, NULL,
0.00);
When you omit the column list, the NULL keyword must be used in the values list to
explicitly assign NULL values to columns. The sequence of data values must
correspond exactly to the sequence of columns in the table.
MULTI-ROW INSERT
Adding rows whose values come from within the database itself may seem strange at first, but it’s
very useful in some special situations. For example, suppose you want to copy the order number,
date, and amount of all orders placed before January 1, 2008, from the ORDERS table into another
table, called OLDORDERS. The multirow INSERT statement provides a concise, efficient way to
copy the data

Copy old orders into the OLDORDERS table.


INSERT INTO OLDORDERS (ORDER_NUM, ORDER_DATE, AMOUNT)
SELECT ORDER_NUM, ORDER_DATE, AMOUNT FROM ORDERS WHERE ORDER_DATE < '2008-01-
01';

You might also like