MIS 311 BUSINESS DABABASE MANAGEMENT Prepared by the Course Instructor: Dr. Mustafa Eid Note please, because there is an incompatibility between the MS WORD editor and SQL View editor, do not run the SQL query directly from this Word Doc. First Copy the query from this Word document to the Note Pad editor and then copy the query from Note Pad to the SQL View editor to run it. SQL Examples from Chapters 6&7: SQL is not case sensitive in MS ACCESS, but Capital letters are used only to increase clarity. Creating Tables Because VENDOR AND PRODUCT tables already exist in the SALE_CO database, then you create the VENDOR and PRODUCT with new names such as VENDOR_NEW and PRODUCT_NEW. Also, since V_CODE is used as a foreign key in PRODUCT_NEW, you need to create VENDOR_NEW table before cresting PRODUCT_NEW table. CREATE TABLE VENDOR_NEW( V_CODE INTEGER NOT NULL UNIQUE, V_NAME VARCHAR(35) NOT NULL, V_CONTACT VARCHAR(15) NOT NULL, V_AREACODE CHAR(3) NOT NULL, V_PHONE CHAR(8) NOT NULL, V_STATE CHAR(2) NOT NULL, V_ORDER CHAR(1) NOT NULL, PRIMARY KEY (V_CODE)); CREATE TABLE PRODUCT_NEW( P_CODE VARCHAR(10) NOT NULL UNIQUE, P_DESCRIPT VARCHAR(35) NOT NULL, P_INDATE DATE NOT NULL, P_OHNAND SMALLINT NOT NULL, P_MIN SMALLINT NOT NULL, P_PRICE NUMBER NOT NULL, P_DISCOUNT NUMBER NOT NULL, V_CODE INTEGER, PRIMARY KEY (P_CODE), FOREIGN KEY (V_CODE) REFERENCES VENDOR_NEW); 1
Creating Domains CREATE DOMAIN Command does not work in MS ACCESS. The purpose of using domains is to provide automatic data validation. However, data validation in MS ACCESS can be done from Forms. Adding data to a Table INSERT INTO VENDOR_NEW VALUES (21225, "Bryson, Inc.", "Smithson", "615", "223-3234", "TN", "Y"); Listing the table contents If you wanted to list all columns and all rows of a table, then use the following select command: SELECT * ; Notice * is referred to as wild card in SQL. This means SQL allows the use of some wild cards such as * and? in MS ACCESS. If you want to select only the columns: P_CODE and P_DESCRIPT, and all rows, the select statement should be written as follows: Select P_CODE, P_DESCRIPT From product; Updating Data in a Table To make a correction on or to modify existing data in row(s) of a Table, use the Update command. Update command works with only one table at a time, see the example below: Modify the in_date value to new date 01/18/2002 for product 13-Q2/P2 Update product Set p_indate = #01/18/2002# Where p_code = 13-Q2/P2 ; Notice to achieve the right results, you need enter the exact letter case of the product code value 13-Q2/P2. That is, Character based primary key values are case sensitive. Producing Partial Listing of one Table contents Problem 1: Produce a listing of the columns: P_DESCRIPT, P_INDATE, P_PRICE, V_CODE for all products supplied by the Vendor whose code is 21344? SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE WHERE V_CODE = 21344; 2
partial listing problem 1 query P_DESCRIPT P_INDATE P_PRICE V_CODE 7.25-in. pwr. saw blade 18-Jan-02 $14.99 21344 9.00-in. pwr. saw blade 13-Nov-01 $17.49 21344 Rat-tail file, 1/8-in. fine 15-Dec-01 $4.99 21344 Problem 2: Produce a listing of the columns: P_DESCRIPT, P_INDATE, P_PRICE, V_CODE for all products supplied by all Vendors but not including the Vendor whose code is 21344. SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE WHERE V_CODE <> 21344; partial listing problem 2 query P_DESCRIPT P_INDATE P_PRICE V_CODE Power painter, 15 psi., 3-nozzle 03-Nov-01 $109.99 25595 Hrd. cloth, 1/4-in., 2x50 15-Jan-02 $39.95 23119 Hrd. cloth, 1/2-in., 3x50 15-Jan-02 $43.99 23119 B&D jigsaw, 12-in. blade 30-Dec-01 $109.92 24288 B&D jigsaw, 8-in. blade 24-Dec-01 $99.87 24288 B&D cordless drill, 1/2-in. 20-Jan-02 $38.95 25595 Claw hammer 20-Jan-02 $9.95 21225 Hicut chain saw, 16 in. 07-Feb-02 $256.99 24288 1.25-in. metal screw, 25 01-Mar-02 $6.99 21225 2.5-in. wd. screw, 50 24-Feb-02 $8.45 21231 Steel matting, 4'x8'x1/6",.5" mesh 17-Jan-02 $119.95 25595 Problem 3: Produce a listing of the columns: P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE for all products priced less than 10. SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE WHERE P_PRICE <= 10; Partial Listing Problem 3 Query P_DESCRIPT P_ONHAND P_MIN P_PRICE Claw hammer 23 10 $9.95 Rat-tail file, 1/8-in. fine 43 20 $4.99 PVC pipe, 3.5-in., 8-ft 188 75 $5.87 1.25-in. metal screw, 25 172 75 $6.99 2.5-in. wd. screw, 50 237 100 $8.45 Problem 4: Produce a listing of the columns: P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE for all products whose P_CODE is less than 1558-QW1. SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE WHERE P_CODE < 1558-QW1 ; 3
Partial Listing Problem 4 Query P_DESCRIPT P_ONHAND P_MIN P_PRICE Power painter, 15 psi., 3-nozzle 8 5 $109.99 7.25-in. pwr. saw blade 32 15 $14.99 9.00-in. pwr. saw blade 18 12 $17.49 Hrd. cloth, 1/4-in., 2x50 15 8 $39.95 Problem 5: Produce a listing of the columns: P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE, P_INDATE for all products whose P_INDATE is greater than or equals to 01/20/2002. Notice MS ACCESS DBMS sets the date format when used against logical operators in where clause, as enclosing dates with the hash wild card, as shown in the following example: SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE, P_INDATE WHERE P_INDATE >= #01/20/2002#; Partial Listing Problem 5 Query P_DESCRIPT P_ONHAND P_MIN P_PRICE P_INDATE B&D cordless drill, 1/2-in. 12 5 $38.95 20-Jan-02 Claw hammer 23 10 $9.95 20-Jan-02 Hicut chain saw, 16 in. 11 5 $256.99 07-Feb-02 PVC pipe, 3.5-in., 8-ft 188 75 $5.87 20-Feb-02 1.25-in. metal screw, 25 172 75 $6.99 01-Mar-02 2.5-in. wd. screw, 50 237 100 $8.45 24-Feb-02 Using Computed Columns and Column Aliases Problem 6: Produce a listing of the columns: P_DESCRIPT, P_ONHAND, P_PRICE with the total value of each of the products currently held in inventory. To produce the total value for each product, it is needed to multiply the quantity on hand P_ONHAND by the product price P_PRICE. SELECT P_DESCRIPT, P_ONHAND, P_PRICE, P_ONHAND*P_PRICE ; Using Computed Columns Problem 1 Query P_DESCRIPT P_ONHAND P_PRICE Expr1003 Power painter, 15 psi., 3-nozzle 8 $109.99 $879.92 7.25-in. pwr. saw blade 32 $14.99 $479.68 9.00-in. pwr. saw blade 18 $17.49 $314.82 Hrd. cloth, 1/4-in., 2x50 15 $39.95 $599.25 Hrd. cloth, 1/2-in., 3x50 23 $43.99 $1,011.77 B&D jigsaw, 12-in. blade 8 $109.92 $879.36 B&D jigsaw, 8-in. blade 6 $99.87 $599.22 B&D cordless drill, 1/2-in. 12 $38.95 $467.40 Claw hammer 23 $9.95 $228.85 Sledge hammer, 12 lb. 8 $14.40 $115.20 Rat-tail file, 1/8-in. fine 43 $4.99 $214.57 4
Using Computed Columns Problem 1 Query P_DESCRIPT P_ONHAND P_PRICE Expr1003 Hicut chain saw, 16 in. 11 $256.99 $2,826.89 PVC pipe, 3.5-in., 8-ft 188 $5.87 $1,103.56 1.25-in. metal screw, 25 172 $6.99 $1,202.28 2.5-in. wd. screw, 50 237 $8.45 $2,002.65 Steel matting, 4'x8'x1/6",.5" mesh 18 $119.95 $2,159.10 Use the alias TOTVALUE for the result of the multiplication of P_ONHAND by P_PRICE SELECT P_DESCRIPT, P_ONHAND, P_PRICE, P_ONHAND*P_PRICE as TOTVALUE ; Using Computed Columns Problem 2 P_DESCRIPT P_ONHAND P_PRICE TOTVALUE Power painter, 15 psi., 3-nozzle 8 $109.99 $879.92 7.25-in. pwr. saw blade 32 $14.99 $479.68 9.00-in. pwr. saw blade 18 $17.49 $314.82 Hrd. cloth, 1/4-in., 2x50 15 $39.95 $599.25 Hrd. cloth, 1/2-in., 3x50 23 $43.99 $1,011.77 B&D jigsaw, 12-in. blade 8 $109.92 $879.36 B&D jigsaw, 8-in. blade 6 $99.87 $599.22 B&D cordless drill, 1/2-in. 12 $38.95 $467.40 Claw hammer 23 $9.95 $228.85 Sledge hammer, 12 lb. 8 $14.40 $115.20 Rat-tail file, 1/8-in. fine 43 $4.99 $214.57 Hicut chain saw, 16 in. 11 $256.99 $2,826.89 PVC pipe, 3.5-in., 8-ft 188 $5.87 $1,103.56 1.25-in. metal screw, 25 172 $6.99 $1,202.28 2.5-in. wd. screw, 50 237 $8.45 $2,002.65 Steel matting, 4'x8'x1/6",.5" mesh 18 $119.95 $2,159.10 Logical Operators: AND, OR, and NOT OR Problem 7: Produce a listing of the columns: P_DESCRIPT, P_INDATE, P_PRICE, V_CODE for all products supplied by the Vendors whose codes are 21344 and 24288. SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE WHERE V_CODE = 21344 OR V_CODE = 24288; 5
AND Problem 8: Produce a listing of the columns: P_DESCRIPT, P_INDATE, P_PRICE, V_CODE for all products whose price is less than 50.00 and P_INDATE is greater than 01/05/2002. SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE WHERE P_PRICE < 50 AND P_INDATE > #01/05/2002#; Problem 9: Produce a listing of the columns: P_DESCRIPT, P_INDATE, P_PRICE, V_CODE for all products whose price is less than 50.00 and P_INDATE is greater than 01/05/2002, also included in the listing all products supplied by the vendor whose vendor code is 24288. SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE WHERE (P_PRICE < 50 AND P_INDATE > #01/05/2002#) OR V_CODE = 24288; PRECEDENCE OF PROCESSING ARITHMETIC OPERATORS 1. If there exist Arithmetic Operators within parentheses ( ), they are done first, then the operators outside the parentheses will be done next 2. Power operator 3. Multiplication * 4. Division / 5. Addition + 6. Subtraction Notice arithmetic operators within parentheses will be processed in the sequence stated in 2 to 6 above. NOT operator is similar t o the operator not equals to <>. Also, MS ACCESS does not support NOT operator. Example: SELECT * WHERE V_CODE NOT 21344; 6
Special Operators BETWEEN Problem 10: List all products whose prices are between $50.00 and $100.00. SELECT * WHERE P_PRICE BETWEEN 50.00 AND 100.00; If the DBMS SQL you use does not support BETWEEN, then the following Query will produce the same listing requested in problem 10. SELECT * WHERE P_PRICE > 50.00 AND P_PRICE < 100.00; IS NULL is used to check for a null data entry (or an attribute/column has null value) Problem 11: List all products whose product minimum value (P_MIN) is not stated or not entered (or NULL). SELECT P_CODE, P_DESCRIPT, P_MIN WHERE P_MIN IS NULL; Another example: List all products whose product P_INDATE value is not stated or not entered (or NULL). SELECT P_CODE, P_DESCRIPT, P_INDATE WHERE P_INDATE IS NULL; Another example: List all products whose supplying vendors are not known, or V_CODE value is not stated or not entered (or NULL). SELECT P_CODE, P_DESCRIPT, V_CODE WHERE V_CODE IS NULL; LIKE is used to check for similar characters string. Notice, in most SQL implementations, the matching with LIKE operator is case sensitive, that is, you need to enter the exact value you want to match to. LIKE must be used in 7
conjunction with wildcard characters. MS ACCESS uses * and _. Also, a combination of wildcards can be used with LIKE. Problem 12: List Contact information for all vendors whose contact name begins with Smith. SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM VENDOR WHERE V_CONTACT LIKE Smith* ; If you want to list all contacts that ends with son then put the wildcard * before the string of characters. For example: SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM VENDOR WHERE V_CONTACT LIKE *son ; If you are not sure the Vendor s Contact is t spelled as Smithson or Smithsen, you can use the LIKE operator with _ wild card as follows: SELECT * FROM VENDOR WHERE V_CONTACT LIKE Smith_n ; IN is used to check whether and attribute value matches a value contained within a subset of listed values. Problem 13: Produce a listing of all columns for all products supplied by the Vendors whose codes are 21344 and 24288. SELECT * WHERE V_CODE IN (21344, 24288); Notice, the same listing may be produced from the query: SELECT * WHERE V_CODE = 21344 OR V_CODE = 24288; EXISTS is used to check whether an attribute has a value. So, EXISTS is the opposite of IS NULL operator. EXISIS is not supported by MS ACESS Problem 14: List all products with existing (non-null) vendor codes. SELECT * WHERE V_CODE EXISTS; 8
Notice that the required listing may also be produced by applying NOT NULL as shown in the following query: SELECT * WHERE V_CODE IS NOT NULL; ADVANCED SQL COMMANDS DATA DEFINITION COMMANDS ALTER command is used to change table structures. ALTER is used: To change attributes/columns data types of characteristics, To add new columns to a table, or To drop or delete an existing column in a table. Remember since you are not the owner of the SALES COMPANY DATA BASE, then you can not run the ALTER command. You must be either the owner or you have been granted the access right to run ALTER command. In practice, usually the database administrator (DBA) who manages the database uses the ALTER command and can give access right to use the ALTER command. Try to create a new database for the sales company yourself using the MS ACCESS, and name SALES_01 for example. Then create the tables and add few rows, then try to use the ALTER command. CHANGING A COLUMNS DATA TYPE Problem 15: change the V_CODE from Integer to CHAR(5). ALTER TABLE VENDOR MODIFY (V_CODE CHAR(5)); To check the result of your query, select the table VENDOR and double click the view design to show the table VENDOR columns and their data types. ADDING A COLUMN TO THE TABLE Problem 16: add the new column P_SALECODE to the PRODUCT table. ALTER TABLE PRODUCT ADD (P_SALECODE CHAR(1)); 9
Check the result of your query. DROPPING A COLUMN Problem 17: delete the column P_ORDER from the VENDOR table. ALTER TABLE VENDOR DROP COLUM P_ORDER; Check the result of your query. ENTERING DATA INTO THE NEW COLUMN It is not possible to enter data into new column(s) in a table, because INSERT is used to enter data for the whole row values, which includes all columns in the row. Therefore, to enter data for one column value in a row, the UPDATE command must be used. Problem 18: enter the value 1 for the new column SALECODE in product whose CODE is 2232/QWE and 2232/QTY in the PRODUCT table. UPDATE PRODUCT SET P_SALECODE = 1 WHERE P_CODE IN ( 2232/QWE, 2232/QTY ); Check the result of your query. COPYING PARTS OF TABLES You can copy data from an old table to a new table with columns that matching data types. Problem 19: create a new table named PART and insert its data from the PRODUCT table by copying data from the PRODUCT table. CREATE TABLE PART ( PART_CODE PART_DESCRIPT PART_PRICE PRIMARY KEY CHAR(10) NOT NULL UNIQUE, VARCHAR(35), NUMBER, (PART_CODE)); Check the result of the CREATE query. INSERT INTO PART (PART_CODE, PART_DESCRIPT, PART_PRICE) SELECT P_CODE, P_DESCRIPT, P_PRICE ; Notice, in this case the data types of the new table: PART must match the PRODUCT table from which the data is copied. Check the results of the INSERT SELECT query. 10
DELETING A TABLE FROM THE DATABASE To delete a table from use the DROP command. Problem 20: delete the PART table. DROP TABLE PART; PRIMARY AND FOREIGN KEY DESIGNATON In case of importing tables between relational databases, the new imported table will not be assigned a primary key or foreign key. Then you need to assign a primary key and their foreign keys if they need foreign keys. Problem 21: Assuming that the PRODUCT and LINE tables are imported to the Sales Company Database. Add the primary key P_CODE to the PRODUCT table, and add the foreign key V_CODE to the PRODUCT table. ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE); ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR; Problem 22: Add the composite primary key INV_NUMBER and LINE_NUMBER to the LINE table. Also, add the foreign keys INV_NUMBER and PROD_CODE to the LINE table. ALTER TABLE LINE ADD PRIMARY KEY (INV_NUMBER, LINE_NUMBER) ADD FOREIGN KEY (INV_NUMBER) REFERENCES INVOICE ADD FOREIGN KEY (PROD_CODE) REFERENCES PRODUCT; MORE COMPLEX QUERIES AND SQL COMMANDS ORDERING A LISTING The ORDER BY is used to sort the output listing (rows) in an ascending or descending order. The sorting is based on one or more columns. By default, the ordering is done in an ascending order. Therefore, you do not need to specify ASCENDING, if you wanted the listing sorted in an ascending order. Otherwise, you specify DESC if you wanted the listing sorted in a descending order. 11
Problem 23: Produce a listing of all products by price in an Ascending order, and including product codes, description, in date, and price. SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE ORDER BY P_PRICE; Problem 24: Produce a listing of all products by price in a Descending order, and including product codes, description, in date, and price. SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE ORDER BY P_PRICE DESC; You can order the output listing based on more than one column, see the problem below. Problem 25: produce a telephone listing (phone directory) for all employees working in the organization, sorted by Last name, first name and middle name (employee initial). SELECT EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_AREACODE, EMP_PHONE FROM EMPLOYEE ORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL; Problem 26: produce a listing for all products whose price is 50 or less, and their product in date is less than 01/21/2002. The listing should be sorted by vendor code and product price in a descending order. SELECT P_CODE, P_DESCRIPT, P_INDATE, V_CODE, P_PRICE WHERE P_INDATE < #01/21/2002# AND P_PRICE <= 50 ORDER BY V_CODE, P_PRICE DESC; Listing Unique Values DISTINCT is used to generate only the unique values stored in one column. Problem 27: produce a listing of vendor codes from the PRODUCT table. The list must not have duplicate vendors. SELECT DISTINCT V_CODE ; 12
Aggregate Functions in SQL SQL have the following mathematical built in mathematical functions: COUNT MIN MAX SUM AVG COUNT is used to calculate (tally) the number of value stored in an attribute or column in a table. Problem 28: Calculate the number of actual vendors supplying products. SELECT COUNT(V_CODE) ; DISTICT is used in the above query because the vendor code V_CODE has duplicate values. Try rewriting and running the query without the DISTINCT, and check the result. The resulting count value will be bigger because all vendors stored in the V_CODE in the PRODUCT table will counted, which is wrong. Also, null values are not counted with the COUNT function. Problem 29: Calculate the number of actual vendors supplying products whose prices are less than or equals to $10.00. SELECT COUNT(V_CODE) WHERE P_PRICE <= 10.00; MAX is used to find the maximum value from amongst the values of a column in a table. Problem 30: find the highest product price in the product table. SELECT MAX(P_PRICE) ; Problem 31: List product code, product description, and price of the product that has the highest price in the product table. SELECT P_CODE, P_DESCRIPT, P_PRICE WHERE P_PRICE = (SELECT MAX(P_PRICE) FROM PRODUCT); 13
This query is called nested query as it has inner query (SELECT MAX(P_PRICE ) and an outer query which is SELECT P_CODE, P_DESCRIP, P_PRICE WHERE P_PRICE =. The inner query is done (processed) first and after that the outer query, for the simple reason because the WHERE clause (that compares between the P_PRICE and maximum price) in the outer query depends on the maximum price value to be generated from the inner query. MIN is used to find the minimum value from amongst the values of a column in a table. Problem 32: find the lowest product price in the product table. SELECT MIN(P_PRICE) ; Problem 33: List product code, product description, and price of the product that has the lowest price in the product table. SELECT P_CODE, P_DESCRIPT, P_PRICE WHERE P_PRICE = (SELECT MIN(P_PRICE) FROM PRODUCT); SUM computes the total for any specified column or attribute, using any condition(s) imposed. Problem 34: find the total value of all the items (products) carried in the inventory (store). SELECT SUM(P_ONHAND*P_PRICE) ; Problem 35: find the total value of all the items (products) carried in the inventory (store), supplied by vendor whose code is 21344. SELECT SUM(P_ONHAND*P_PRICE) WHERE V_CODE = 21344; AVG is used to calculate the average values of a certain column. Problem 36: Find the average product price of all products in the product table. SELECT AVG(P_PRICE) ; 14
Problem 37: find a list of all products with the price that exceeds the average product price of all products stored in the product table. Order the output listing by price in a descending order. SELECT P_CODE, P_DESCRIPT, P_PRICE, V_CODE WHERE P_PRICE > (SELECT AVG(P_PRICE) ) ORDER BY P_PRICE DESC; GROUPING DATA GROUP BY Grouping data is useful for the generation of frequency distribution information. The grouping of data is achieved by using the GROUP BY clause. Since the grouping of data generates distinct groups with their corresponding calculated values such as count, max, min, average or sum, the GROUP BY is valid only with the SQL built in function (COUNT, MAX, MIN, SUM, and AVG). Problem 38: find the count of products supplied by each vendor in the product table. SELECT V_CODE, COUNT(P_CODE) GROUP BY V_CODE; Problem 39: find the count and average price of products supplied by each vendor in the product table. SELECT V_CODE, COUNT(P_CODE), AVG(P_PRICE) GROUP BY V_CODE; The GROUP BY features HAVING clause HAVING clause is applied to impose conditions on the listing generated from the GROUP BY command. Problem 40: find the count of products supplied by each vendor in the product table, and whose prices average below $10.00. SELECT V_CODE, COUNT(DISTINCT(P_CODE)), AVG(P_PRICE) GROUP BY V_CODE HAVING AVG(P_PRICE) < 10; 15
In SQL, it is possible to combine multiple clauses and functions. See the following problem. Problem 41: produce a list contain the vendor code, and sum or total number of quantity on hand of products supplied by each vendors, but include in the list only those vendors having total number that exceed 5. The list must be sorted or ordered in a descending order by total number of quantity on hand. SELECT V_CODE, SUM(P_ONHAND) AS TotalQtyonhand GROUP BY V_CODE HAVING (SUM(P_ONHAND) > 5) ORDER BY SUM(P_ONHAND) DESC; VIEWS (VIRTUAL TABLES) Views are virtual (logical) tables which are only created for the program run time processing session. That is views are not stored permanently in the database like normal table, instead they are only stored in the main memory for the program run time processing. The purpose of creating views is to achieve complex calculation or processing of the data stored in the database tables. CREATING VIEWS Usually, the syntax of creating a view is combined with the select command in order to copy in the new created view data from an existing table. Then applied to the view the required calculation or processing without affecting the data stored in the original table where the data comes from. Problem 42: Create the view named PRODUCT_3 with only three columns: product description, product quantity on hand, and price from the product table. Include in the view only products with a price greater than $50. CREATE VIEW PRODUCT_3 AS SELECT P_DESCRIPT, P_ONHAND, P_PRICE WHERE P_PRICE > 50; Problem 43: list all products in the PRODUCT_3 view. SELECT * _3; Views are useful in making the data available to end users without having to worry about the corruption of data in the real tables, thereby maintaining higher level of data integrity. Views can improve data privacy too, because they enable you to restrict user o only view portions of the data from the real tables. 16
Views are dynamically updated. That is, if new products are added that meet the criterion P_PRICE > 50, those new products will automatically appear in the PRODUCT_3 view the next time the view is run or accessed. Also, views are often used as the basis for reports. Problem 44: Produce a report or listing that shows a summary of total product quantity on hand by vendor. CREATE VIEW SUMPRDXVEN AS SELECT V_CODE, SUM(P_ONHAND) AS TOTQTY, MAX(P_ONHAND) AS MAXQTY, MIN(P_ONHAND) AS MINQTY GROUP BY V_CODE; CREATING SQL INDEXES Indexes in SQL are used to improve efficiency of searching when using the select commands. CREATE UNIQUE INDEX P_CODEX ON PRODUCT(P_CODE); UNIQUE is needed here because P_CODE is a primary key. However, creating an index on an attribute that allows duplicate values, the create index query must not use UNIQUE feature. Also, to make efficient searching, use index on multiple attributes. Problem 45: Create an index on the vendor code (V_CODE) and P_CODE in PRODUCT table. CREATE INDEX VENPRODX ON PRODUCT(V_CODE, P_CODE); 17
JOINING DATABASE TABLES Joining tables is used to access data from multiple tables. Problem 46: Create a report listing that includes the following information: product description, product price, and the information (vendor name, contact, area-code, vendor phone) of supplying vendors of all products stored in table PRODUCT. SELECT P_DESCRIPT, P_PRICE, V_NAME, V_CONTACT, V_AREACODE, V_PHONE, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE; Problem 47: Order the listing produced in problem 46, by price in an ascending order. SELECT P.P_DESCRIPT, P.P_PRICE, V.V_NAME, V.V_CONTACT, V.V_AREACODE, V.V_PHONE P, VENDOR V WHERE P.V_CODE = V.V_CODE ORDER BY PRICE; Notice, the query has used aliases to differentiate between same column names in different tables. Problem 48: Restrict the listing of problem 46, to produce only the products whose in date is greater than the date 01/15/2002. Order the listing by in date in an ascending order. SELECT P_DESCRIPT, P_PRICE, V_NAME, V_CONTACT, V_AREACODE, V_PHONE, P_INDATE P, VENDOR V WHERE P.V_CODE = V.V_CODE AND P_INDATE > #01/15/2002# ORDER BY P_INDATE; Recursive Queries Recursive query is a SQL query that joins a table with itself. Problem 49: produce a listing of all employees and their managers names. The EMP table structure is shown below: EMP_NUM (Primary key) EMP_TITLE EMP_LNAME 18
EMP_FNAME EMP_INITIAL EMP_DOB EMP_HIRE_DATE EMP_AREA_CODE EMP_PHONE EMP_MGR (EMP_MGR acts as a foreign key which is based on the primary key EMP_NUM of the same table EMP) SELECT A.EMP_NUM, A.EMP_LNAME, A.EMP_MGR, B.EMP_LNAME FROM EMP A, EMP B WHERE A.EMP_MGR = B.EMP_NUM ORDER BY A.EMP_MGR; Notice, the table EMP is used twice, that is the DBMS creates another copy of the EMP table to accomplish the join operator between table EMP with itself. A.EMP_NUM, A.EMP_LNAME these two columns represents the employee number and employee last name in EMP copy A, and B.EMP_LNAME this column represents the employee last name of the manager in EMP copy B. EMP table (COPY A) EMP table (COPY B) EMP_NUM ENM_MGR (FK) 100 110 EMP_NUM (PK) 110 ENM_MGR OUTER JOINS Left outer join in MS ACCESS is done as follows: SELECT P_CODE, VENDOR.[V_CODE], V_CODE FROM VENDOR LEFT JOIN PRODUCT ON VENDOR.[V_CODE] = PRODUCT.V_CODE; Right outer join in MS ACCESS is done as follows: SELECT P_CODE, VENDOR.[V_CODE], V_CODE FROM VENDOR RIGHT JOIN PRODUCT ON VENDOR.[V_CODE] = PRODUCT.V_CODE; 19
UPDATABLE VIEWS Common operation in production environments is use of batch routines to update master table attributes using transaction data Overnight batch jobs Not all views are updatable Restrictions GROUP BY expressions cannot be used Cannot use set operators---union, INTERSECTION, etc. In MS ACCESS it is possible to run UPDATE for updating one column in one table but requiring the use of a column in another table. That is using the UPDATE command with multiple tables (see example in page 263-264). UPDATE PRODUCT, PMSALES SET PRODUCT.PROD_QOH = PROD_QOH PMS_QTY WHERE PRODUCT.PROD_ID = PMSALES.PROD_ID; This SQL query will first join the tables: PRODUCT and PMSALES, then it will update all products quantity on hand that have a matching value of PROD_ID in PMSALES. In Oracle, it is not possible to run the update command with multiple tables. Therefore, to achieve updating one column in a table based on a column exists in another table, two steps are needed: 1. a view is created first to include the columns needed from multiple tables, then 2. update the column need to be updated in the new view which will update the column in the original table PRODUCT See example in page 265. the steps shown below present the two queries: Step 1: CREATE VIEW PMSVUPD AS ( SELECT PRODUCT.PROD_ID, PRODUCT.PROD_QOH, PMSALES.PMS_QTY, PMSALES WHERE PRODUCT.PROD_ID = PMSALES.PROD_ID); Step 2: UPDATE PMSVUPD SET PROD_QOH = PROD_QOH PMS_QTY; 20
PROCEDURAL SQL SQL shortcomings SQL queries retrieves a set or rows (listing) Does not support conditional programming statements such as: IF-THEN-ELSE or Looping operations Solutions Embedded SQL can be called from within procedural programming languages such as COBOL, C, or Visual Basic Shared Code stored and executed within the database. To meet this requirement, most RDBMS vendors create a programming language extension (called Procedural SQL) to support end users procedural activities. Procedural SQL (PL/SQL) stored within the database, executed by DBMS, and invoked by the end user. Stored procedures include: Triggers Stored procedures PL/SQL functions TRIGGERS A trigger is procedural SQL code that is automatically invoked (run) by the DBMS upon the occurrence of a data manipulation event. A trigger is always run before or after a data row is selected, inserted, or one or column values are updated. A trigger is always associated with a database table. But a database table may have one or more triggers. A trigger is executed as part of the transaction that triggered it. Problem 50: Create a trigger that will automatically run if the column P_ONHAND is changed by an insert or update command. The trigger will compare the P_ONHAND with the P_MIN column. If the value of P_ONHAND is equal to or less than P_MIN, the trigger must update the P_REORDER to 1. The trigger s code is written in Oracle SQL*Plus. CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER AFTER INSERT OR UPDATE OF P_ONHAND ON PRODUCT BEGIN UPDATE PRODUCT SET P_REORDER =1 WHERE P_ONHAND <= P_MIN; To check if the created trigger works, do run the following SQL queries: SELECT * 21
WHERE P_CODE = 11QER/31 ; UPDATE PRODUCT SET P_ONHAND = 4 WHERE P_CODE = 11QER/31 ; SELECT * WHERE P_CODE = 11QER/31 ; STORED PROCEDURES A Stored Procedure is a set of procedural and SQL statements. It is stored in the database it is related to, and invoked/run by name from the DBMS, that it is not run automatically like a Trigger. The following SQL*Plus syntax is used to create a stored procedure. CREATE OR REPLACE procedure name (argument IN/OUT data type, etc) IS/AS BEGIN DECLARE variable name and data type PL/SQL or SQL statements END; To invoke/run a stored procedure use the following syntax in SQL*Plus: EXEC stored-procedure _name (parameter, parameter, ) Problem 51: Create a stored procedure to set (or update) the P_REORDER column value to 1 in PORDUCT table when a product s P_ONHAMD value reaches or becomes less than the product s minimum quantity P_MIN value. Also, the procedure need to set the product s P_REORDER value to 0 when a product s P_ONHAMD value becomes greater than the product s minimum quantity P_MIN value. The following code is written in Oracle SQL*Plus SQL> RUN CREATE OR REPLACE PROCEDURE PROD_REORDER_SET AS BEGIN UPDATE PRODUCT SET P_REORDER = 1 WHERE P_ONHAND <= P_MIN; UPDATE PRODUCT SET P_REORDER = 0 WHERE P_ONHAND > P_MIN; END; 22
Procedure created SQL> EXEC PROD_REORDER_SET PL/SQL Procedure successfully completed SQL> PL/SQL STORED FUNCTIONS A stored function is similar to stored procedure, but stored function can only be run from a stored procedure or a trigger by calling it. It is basically a set of procedural and SQL statements that returns a value (indicated by the RETURN statement in its code). The syntax for creating a SQL stored function is CREATE FUNCTION function-name (argument IN data type, etc.) RETURN data type AS BEGIN PL/SQL statements RETURN (value); END; 23