Your SlideShare is downloading. ×
MELJUN CORTES Structured Query Language Complete
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

MELJUN CORTES Structured Query Language Complete

142
views

Published on

MELJUN CORTES Structured Query Language Complete

MELJUN CORTES Structured Query Language Complete

Published in: Technology

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
142
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Chapter 5Structured Query Language (SQL)
  • 2. In this chapter, you will learn:  The basic commands and functions of SQL  How SQL is used for data manipulation (to add, modify, delete, and retrieve data)  How to use SQL to query a database to extract useful informationMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 2
  • 3. In this chapter, you will learn:  How SQL is used for data administration (to create tables, indexes, and views)  About more advanced SQL features such as updatable views, stored procedures, and triggersMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 3
  • 4. Introduction to SQL  Ideal database language  Create database and table structures  Perform basic data management chores (add, delete, and modify)  Perform complex queries to transform data into useful informationMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 4
  • 5. Introduction to SQL  SQL is the ideal DB language  Data definition language (create tables and define access right to tables)  Data manipulation language (update and manipulate data within database tables)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 5
  • 6. Good Reasons to Study SQL  Easy to learn  Portable to many database specification, only minor differences among various SQLs defined in Oracle, SQL server, DB2, Informix, Access, my SQL, …MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 6
  • 7. Good Reasons to Study SQL  ANSI standardization effort led to de facto query standard for relational database (SQL- 99 or SQL3)  Forms basis for present and future DBMS integration efforts  Becomes catalyst in development of distributed databases and database client/server architectureMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 7
  • 8. Data Definition Commands Database model  PRODUCT and VENDORMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 8
  • 9. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 9
  • 10. Data Definition Commands  Create database structure  Holds all tables and is a collection of physical files stored on disk  DBMS automatically creates tables to store metadata  Schema: a group of database objects (tables, indexes and relationships)  Database administrator creates structure or schema  Logical group of tables or logical database  Groups tables by owner  Enforces securityMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 10
  • 11. Data Definition Commands  ANSI standard to create database schema CREATE SCHEMA AUTHORIZATION <creator> Example: CREATE SCHEMA AUTHORIZATION JONESMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 11
  • 12. Data Dictionary TableMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 12
  • 13. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 13
  • 14. Creating Table Structure  Data Types  Number:  NUMBER(L,D)  INTEGER  SMALLINT  DECIMAL(L,D)  Character:  CHAR(L)  VARCHAR(L)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 14
  • 15. Creating Table Structure  Data Types  Date  DATE  Others  TIME  TIME-STAMP  REAL  DOUBLE  FLOAT  ODL  …MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 15
  • 16. Creating Table Structure  Tables store end-user data  May be based on data dictionary entries CREATE TABLE <table name> ( <attribute1 name and attribute1 characteristics, attribute2 name and attribute2 characteristics, attribute3 name and attribute3 characteristics, primary key designation, foreign key designation and foreign key requirement>);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 16
  • 17.  Example:CREATE TABLE VENDOR (V_CODE INTEGER NOT NULL UNIQUEV_NAME VARCHAR(35) NOT NULLV_CONTACT VARCHAR(15) NOT NULLV_AREACODE CHAR(3) NOT NULLV_PHONE CHAR(8) NOT NULLV_STATE CHAT(2) NOT NULLV_ORDER CHAR(1) NOT NULLPRIMARY KEY(V_CODE) );MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 17
  • 18.  Example:CREATE TABLE PRODUCT (P_CODE VARCHAR(10) NOT NULL UNIQUEP_DESCRIPT VARCHAR(35) NOT NULLP_INDATE DATE NOT NULLP_ONHAND SMALLINT NOT NULLP_MIN SMALLINT NOT NULLP_PRICE NUMBER(8,2) NOT NULLP_DISCOUNT NUMBER(5,2) NOT NULLV_CODE INTEGERPRIMARY KEY(P_CODE)FOREIGN KEY(V_CODE) REFERENCES VENDORON DELETE RESTRICTON UPDATE CASCADE); Can not delete vendor table You can change vendor’s codeMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 18
  • 19. Using Domains  Domain is set of permissible values for a column  Definition requires:  Name  Data type  Default value  Domain constraint or condition CREATE DOMAIN <domain_name> AS DATA_TYPE [DEFAULT <default_value>] [CHECK (<condition>)]MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 19
  • 20. Using Domains  Example:CREATE DOMAIN MARITAL_STATUS AS VARCHAR(8) AS DATA_TYPECHECK (VALUE IN (‘Single’, ‘Married’, ‘Divorced’, ‘Widowed’));  You can use domain name instead of attribute’s data type, when you define a new tableCREATE TABLE EMPLOYEE (EMP_NUM INTEGER NOT NULL CONSTRAIN EMPKRY KEY (EMP_NUM),EMP_LNAME VARCHAR(15) NOT NULL,EMP_FNAME VARCHAR(15) NOT NULL,EMP_STATUS MARITAL_STATUS NOT NULL);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 20
  • 21. Using Domains  Draw domain values from other tables by including a SELECT statement int eh CHECK clauseCREATE DOMAIN DISCOUNTING_RATES AS NUMBER(5,2)CHECK (VALUE IN (SELECT DISCOUNT FROM DISCOUNTBL); DISCOUNT attributes in DISCOUNTBL tableMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 21
  • 22. Using Domains  Delete domain Prevent deleting until no attributes based on the domainDROP DOMAIN <domain_name> [RESTRICT |CASCADE]DROP DOMAIN MARITAL_STATUS CASCADE; Change data type to the one defined In domain’s definition  Not all database support create domain like OracleMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 22
  • 23. SQL Integrity Constraints  Adherence to entity integrity and referential integrity rules is crucial  Entity integrity enforced automatically if primary key specified in CREATE TABLE command sequence  Referential integrity can be enforced in specification of FOREIGN KEY  Other specifications to ensure conditions met: ON DELETE RESTRICT   ON UPDATE CASCADEMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 23
  • 24. CREATE TABLE PRODUCT (P_CODE VARCHAR(10) NOT NULL UNIQUEP_DESCRIPT VARCHAR(35) NOT NULLP_INDATE DATE NOT NULLP_ONHAND SMALLINT NOT NULLP_MIN SMALLINT NOT NULLP_PRICE NUMBER(8,2) NOT NULLP_DISCOUNT NUMBER(5,2) NOT NULLV_CODE INTEGERPRIMARY KEY(P_CODE)FOREIGN KEY(V_CODE) REFERENCES VENDORON DELETE RESTRICTON UPDATE CASCADE); Some database does this automatically without explicit specificationsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 24
  • 25. Data Manipulation Commands Common SQL Commands Table 5.3MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 25
  • 26. Data Entry and Saving  Enters data into a table INSERT INTO <table name> VALUES (attribute 1 value, attribute 2 value, … etc.); INSERT INTO VENDOR VALUES (21225, ‘my company’, ‘jun ni’, ‘319’,’232-2194’,’IA’,’Y’);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 26
  • 27. Data Entry and Saving  Use form (GUI) to enter dataMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 27
  • 28. Data Entry and Saving  Saves changes to disk COMMIT <table names> ;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 28
  • 29. Listing Table Contents and Other Commands  Allows table contents to be listed SELECT <attribute names> FROM <table names>; SELECT * FROM PRODUCT; SELECT P_CODE, P_DESCRIPT, P_INDATE, P_ONANG, P_MIN, P_PRICE, P_DISCOUNT, V_CODE FROM PRODUCT;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 29
  • 30. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 30
  • 31. Listing Table Contents and Other Commands  UPDATE command makes data entry corrections UPDATE PRODUCT SET P_INDATE=’01/18/2003’ WHERE P_CODE=’13-Q2/P2’MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 31
  • 32. Listing Table Contents and Other Commands  ROLLBACK command restores database back to previous condition if COMMIT hasn’t been used ROLLBACK;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 32
  • 33. Listing Table Contents and Other Commands  DELETE command removes table row DELETE FROM PRODUCT WHERE P_CODE=‘2238/QPD’; DELETE FROM PRODUCT WHERE P_MIN=5; 5 ROWS ARE DELETEDMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 33
  • 34. Queries  Creating partial listings of table contents SELECT <column(s)> FROM <table name> WHERE <conditions>; Table 5.4 Mathematical OperatorsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 34
  • 35. Examples Mathematical operators SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE = 21344;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 35
  • 36. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 36
  • 37. Examples Mathematical operators SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; Not equalMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 37
  • 38. Examples Mathematical operators SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_PRICE<=10;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 38
  • 39. Examples  Mathematical operators on character attributes SELECT P_CODE,P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558-QWI’;  Mathematical operators on dates SELECT P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE,PINDATE FROM PRODUCT WHERE P_INDATE >= ‘01/20/2002’;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 39
  • 40. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 40
  • 41. Computed Columns  New columns can be created through valid computations or formulas  Formulas may contain mathematical operators  May contain attributes of any tables specified in FROM clause  Alias is alternate name given to table or column in SQL statement SELECT P_DESCRIPT,P_ONHAND,P_PRICE,P_ONHAND*P_PRICE AS TOTVALUE FROM PRODUCT;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 41
  • 42. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 42
  • 43. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 43
  • 44. Operators Logical: AND, OR, NOTSELECT *FROM PRODUCTWHERE V_CODE = 21344OR V_CODE = 24288;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 44
  • 45. Operators  Rules of precedence  Conditions within parenthesis executed first  Boolean algebra SELECT * P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE (P_PRICE<50 AND P_INDATE>’01/05/2002’) OR V_CODE=24288;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 45
  • 46. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 46
  • 47. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 47
  • 48. Special Operators  BETWEEN - defines limitsSELECT * FROM PRODUCT WHERE P_PRICE BETWEEN 500.00 AND 100.00;  IS NULL - checks for nullsSELECT P_CODE, P_DESCRIPT FROM PRODUCT WHERE P_MIN IS NULL;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 48
  • 49. Special Operators  LIKE - checks for similar string (wildcard)SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONEFROM VENDOR WHERE V_CONTACT LIKE ‘Smith%’;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 49
  • 50. Special Operators  IN - checks for value in a set SELECT * FROM PRODUCT WHERE V_CODE=21344 OR V_CODE=24288; SELECT * FROM PRODUCT WHERE V_CODE IN (21344,24288); MORE EFFICIENTLYMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 50
  • 51. Special Operators  EXISTS – NOT NULL DELETE FROM PRODUCT WHERE P_CODE EXISTS; SELECT FROM PRODUCT WHERE V_CODE EXISTS; SELECT FROM PRODUCT WHERE V_CODE IS NOT NULL;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 51
  • 52. Advanced Data Management Commands  ALTER - changes table structure  ADD - adds column  MODIFY - changes column characteristics ALTER TABLE <table name> ADD (<column name> <new column characteristics>); ALTER TABLE <table name> MODIFY (<column name> <new column characteristics>);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 52
  • 53. Advanced Data Management Commands  ALTER - changes table structure  ADD - adds column  MODIFY - changes column characteristicsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 53
  • 54. Advanced Data Management Commands  Changing a column’s data type: CHANGE FROM ALTER TABLE PRODUCT INTEGER TO MODIFY (V_CODE CHAR(5)); CHAARCTERS  Changing attribute characteristics ALTER TABLE PRODUCT Increase width of P_PRICE MODIFY (P_PRICE DECIMAL(9,2));MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 54
  • 55. Advanced Data Management Commands  Adding a column to the table: Add column named ALTER TABLE PRODUCT P_SALECODE to ADD ( P_SALECODE CHAR(1)); PRODUCT table  Dropping (delete) a column from the table: ALTER TABLE VENDOR DROP COLUMN V_ORDER;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 55
  • 56. Advanced Data Management Commands (con’t.) Entering data into new column UPDATE PRODUCT Update entries: SET P_SALECODE=‘2’ WHERE P_CODE=‘1546-qq2’;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 56
  • 57. Advanced Data Management Commands (con’t.) Entering data into new column UPDATE PRODUCT SET P_SALECODE=‘1’ WHERE P_CODE IN (‘2232/QWE’, ‘2232/QTY’);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 57
  • 58. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 58
  • 59. Advanced Data Management Commands (con’t.) UPDATE PRODUCT SET P_SALECODE=‘2’ WHERE P_INDATE<’12/25/2001’; UPDATE PRODUCT SET P_SALECODE=‘1’ WHERE P_INDATE>’01/16/2002 AND P_INDATE<’01/21/2002’;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 59
  • 60. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 60
  • 61. Advanced Data Management Commands (con’t.)  Arithmetic operators and rules of precedence Table 5.5MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 61
  • 62. Advanced Data Management Commands (con’t.)  Arithmetic operators and rules of precedence UPDATE PRODUCT SET P_ONHAND=P_ONHAND+20 WHERE P_CODE=‘2232/QWE’; UPDATE PRODUCT SET P_PRICE=P_PRICE*1.10 WHERE P_PRICE<50.00;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 62
  • 63. Advanced Data Management Commands (con’t.)  Copying parts of tables  Copy the contents of selected table columns with data values INSERT INTO <receiving table> <receiving table’s column names> SELECT <column names of the columns to be copied> FROM <contributing table name>;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 63
  • 64. Advanced Data Management Commands (con’t.)  Copying parts of tables NEW TABLE NAME CREATE TABLE (PART PART_CODE CHAR(8) NOT NULL UNIQUE, PART_DESCRIPT CHAR(35) PART_PRICE DECIMAL(8,2), PRIMARY KEY (PART_CODE)); INSERT INTO PART (PART_CODE,PART_DESCRIPT, PART_PRICE) SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT; SELECT * FROM PART;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 64
  • 65. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 65
  • 66. Advanced Data Management Commands (con’t.)  Deleting a table from database DROP TABLE PART;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 66
  • 67. Advanced Data Management Commands (con’t.)  Primary and foreign key designation ALTER TABLE LINE ADD PRIMARY KEY (INV_NUMBER, LINE_NUMBER) ADD FOREIGN KEY (INV_NUMBER) REFERENCES INVOICE ADD FOREIGN KEY (PROD_CODE) REFERENCES PRODUCT;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 67
  • 68. Advanced Data Management Commands (con’t.)  Primary and foreign key designation ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE); ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 68
  • 69. More complex queries and sql functions  Ordering listing: list in special order (ascending order to descending order) ORDER BY <attributes> ascending ORDER BY <attributes> DESC descending SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE FROM PRODUCT ORDER BY P_PRICE;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 69
  • 70. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 70
  • 71. More complex queries and sql functions  Cascading order sequence ORDER BY <attribute1 attribute2, …> ORDER BY <attribute1, attribute2, …> DESC SELECT EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_AREACODE, EMP_PHONE FROM EMPLOYEE ORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 71
  • 72. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 72
  • 73. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 73
  • 74. More complex queries and sql functions  Use order by clause in conjunction with other SQL commands SELECT P_DESCRIPT, V_CODE, P_INDATE, P_PRICE FROM PRODUCT WHERE P_INDATE<’01/21/2002’ AND P_PRICE<=50.00 ORDER BY V_CODE, P_PRICE DESC;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 74
  • 75. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 75
  • 76. More complex queries and sql functions List unique values SELECT DISTINCT V_CODE FROM PRODUCT;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 76
  • 77. Aggregate Function OperationsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 77
  • 78. Aggregate Function Operations  COUNT (count raw numbers for a given column) SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT; SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT WHERE P_PRICE <= 10.00;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 78
  • 79. Aggregate Function Operations  MAX and MIN SELECT MIN(P_PRICE) FROM PRODUCT; SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT WHERE P_PRICE = MAX(P_PRICE);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 79
  • 80. Example Aggregate Function Operations (con’t.)  SUM SELECT SUM(P_ONHAND * P_PRICE) FROM PRODUCT;  AVG SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE > (SELECT AVG(P_PRICE) FROM PRODUCT) ORDER BY P_PRICE DESC;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 80
  • 81.  Grouping data  Creates frequency distributions  Only valid when used with SQL arithmetic functions SELECT P_SALECODE, MIN(P_PRICE) FROM PRODUCT_2 GROUP BY P_SALECODE;  HAVING clause operates like WHERE for grouping output SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE) FROM PRODUCT_2 GROUP BY V_CODE HAVING AVG(P_PRICE) < 10;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 81
  • 82. More Complex Queries and SQL Functions (con’t.)  Virtual tables: creating a view  CREATE VIEW command  Creates logical table existing only in virtual memory CREATE VIEW PRODUCT_3 AS SELECT P_DESCRIPT, P_ONHAND, P_PRICE FROM PRODUCT WHERE P_PRICE > 50.00; CREATE INDEX P_CODEX SQL indexes ON PRODUCT(P_CODE);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 82
  • 83.  Joining database tables  Data are retrieved from more than one table SELECT PRODUCT.P_DESCRIPT, PRODUCT.P_PRICE, VENDOR.V_NAME, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_PHONE FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE;  Recursive queries joins a table to itself 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  Outer joins can be used when ‘null’ values need to be included in query resultMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 83
  • 84. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 84
  • 85. Updatable Views Common operation in production environments is use of batch routines to update master table attributes using transaction data Batch update routine pools the transactions into a single “batch” to update a master table field in a single operation. Overnight batch jobs Not all views are updatable Example: master PRODUCT and product monthly sales table (PMSALES)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 85
  • 86. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 86
  • 87. UPDATE PRODUCT, PMSALES SET PRODUCT.PROD_ QOH=PROD_QOH-PMS-QTY WHERE PRODUCT.PROD_ID=PMSALES.PROD_ID;This works for ACCESS not for Oracle. If you use Oracle, you need to create anupdatable view.Updatable view is a view that can be used toupdate attributes in base tables.MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 87
  • 88. Updatable Views  Restrictions  GROUP BY expressions cannot be used  Cannot use set operators---UNION, INTERSECTION, etc.  Most restrictions based on use of JOINS or group operators in viewsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 88
  • 89. Updatable Views  Create Updatable viewCREATE VIEW MPSVUPD AS (SET PRODUCT.PROD_ID, PRODUCT.PROD_QOH,PMSALES.PMS_QTYFROM PRODUCT, MPSALES WHERE PRODUCT.PROD_ID=PMSALES.PROD_ID);  Now you can use UPDATE command to update the view UPDATE PMSVUPD SET PROD_QOH=PROD_QOH-PSM-QTY MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 89
  • 90. Procedural SQL  SQL is a declarative language, not support conditional executions of procedures and looping executions  SQL shortcomings  Doesn’t support execution of stored procedures based on logical condition  Fails to support looping operations  The way to use logical or procedural statements is to embed SQL into programming languagesMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 90
  • 91. Procedural SQL  Solution  Embedded SQL can be called from within procedural programming languages.  Using embedded SQL is still the most common approach to maintaining procedural capabilities.  Shared Code is isolated and used by all application programs.  Procedural SQL (PL/SQL) stored within the database, executed by DBMS, and invoked by the end user  Triggers  Stored procedures  PL/SQL functionsMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 91
  • 92. Procedural SQL (con’t.)  Procedural SQL allows the use of procedural code and SQL statements that are stored within the database.  The procedural code is executed by the DBMS when it is invoked by the end user.MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 92
  • 93. Procedural SQL (con’t.)  End users can use procedural SQL (PL/SQL) to create:  Triggers  Stored procedures  PL/SQL functions (different from SQL built-in functions)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 93
  • 94. Triggers  Procedural SQL code invoked before or after data row is selected, inserted, or updated  Associated with a database table  Table may have multiple triggers  Executed as part of transactionMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 94
  • 95. Triggers  Can enforce particular constraints  Automate critical actions and provide warnings for remedial action  Can update values, insert records, and call procedures  Add processing powerMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 95
  • 96. Triggers (con’t.)  Oracle example 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 END;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 96
  • 97. Stored Procedures  Named collection of procedural and SQL statements stored in database  Invoked by name  Executed as unit  Invoked with EXEC  Used in multiple-update transaction (entire contents of stored procedure will be transmitted and executed, which reduce network transfer delay.MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 97
  • 98. Stored Procedures  Invoked with EXEC CREATE OR REPLACE PROCEDURE procedure_name (argument IN/OUT data-type, etc) IS/AS BEGIN DECLARE variable name and data type PL/SQL or SQL statements; END; EXEC store_procedure_name (parameter, parameter, …)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 98
  • 99. Stored Procedures  Example 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>_MIN; END; EXEC PROD_REORDER_SET;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 99
  • 100. Stored Procedures  Example CREATE OR REPLACE PROCEDURE PROD_SALE(CODE IN VARCHAR2, QTYSOLD IN NUMBER) AS BEGIN UPDATE PRODUCT SET P_REORDER=P_ONHAND-QTYSOLD; WHERE P_CODE=CODE; END; EXEC PROD_SALE(‘22232/QTY’,3);MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 100
  • 101. PL/SQL Stored Functions  Named group of procedural and SQL statements that returns a value CREATE FUNCTION function_name (argument IN data-type, etc) RETURN data-type AS BEGIN PL/SQL statements; RETURN (value); …… END;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 101
  • 102. PL/SQL Stored Functions  Invoked from within stored procedures or triggers  Cannot be invoked from within SQL statements CREATE FUNCTION function_name (argument IN data-type, etc) RETURN data-type AS BEGIN PL/SQL statements; RETURN (value); …… END;MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 102
  • 103. Converting an ER model into a database structure  Require the some rules  Database of artist  A painter may have many paintings (1:M)  Each painter painted by one and only one painter (so far it is a 1:M) relationships between PAINTER and PAINTING  A painter must have at least painting (cardinality is (1:N)  A painting might (or might not) be exhibited in a gallery (another Table, which is optional to the paining entity)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 103
  • 104. Artist Database ERD and Tables Figure 5.55MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 104
  • 105. MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 105
  • 106. Table Structure and specific requirements PAINTER(PTR_NUM, PTR_LASTNAME,PTR_FIRSTNAME, PTR)INITIAL, PTR_AREACODE, PTR_PHONE) GALLERY(GAL_NUM,GAL_OWNER, GAL_AREACODE, GAL_PHONE, GAL_RATE) PAINTING(PNTG_NUM, PNTG_TITLE, PNTG_PRICE, PNTG_NUM, GAL_NUM)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 106
  • 107. Further action considerations1. Delete raw of painter will effect the PAINTER’s table and cerate delete anomaly. Impose a DELETE RESTRICT on PAINTER’s table2. No problem to add raw in PAINTER”s table3. Change PRT_NUM (primary key) will affects other tables. Make sure we need to create a trigger to automatically take care the case. Use UPDATE CASCADE (all foreign key references to primary key are updated when the primary key is changed)4. Delete GAL_NUM may cause problem, unless we impose DELETE RESTRICT on GALLERY table.5. No problem to add GALEERY rawMELJUN CORTES, MBA,MPA,BSCS ( table 107 SQL 6. UPDATE CASCADE is used for GALEERY MELJUN CORTES CSSD04C4)
  • 108. Creates Tables using SQL CREATE TABLE PAINTER ( PTR_NUM CHAR(4) NOT NULL UNIQUE, PTR_LASTNAME CHAR(15) NOT NULL, PTR_FIRSTNAME CHAR(15) NOT NULL, PTR_INITIAL CHAR(1), PTR_AREACODE CHAR(3), PTR_PHONE CHAR(8), PRIMARY KEY(PTR_NUM));MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 108
  • 109. Creates Tables using SQL CREATE TABLE GALLERY ( GAL_NUM CHAR(4) NOT NULL UNIQUE, GAL_OWNER CHAR(35) NOT NULL, GAL_AREACODE CHAR(3), GAL_PHONE CHAR(8) NOT NULL, GAL_RATE NUMBER(4,2), PRIMARY KEY(GAL_NUM));MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 109
  • 110. Creates Tables using SQL CREATE TABLE GALLERY ( GAL_NUM CHAR(4) NOT NULL UNIQUE, GAL_OWNER CHAR(35) NOT NULL, GAL_AREACODE CHAR(3), GAL_PHONE CHAR(8) NOT NULL, GAL_RATE NUMBER(4,2), PRIMARY KEY(GAL_NUM));MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 110
  • 111. Creates Tables using SQL CREATE TABLE PAINTING ( PNTG_NUM CHAR(4) NOT NULL UNIQUE, PNTG_TITLE CHAR(35) NOT NULL, PNTG_PRICE NUMBER(9,2), PTR_NUM CHAR(4) NOT NULL, GAL_NUM CHAR(4) PRIMARY KEY(GAL_NUM)); FOREIGN KEY (PTR_NUM) REFERENCES PAINTER ON DELETE RESTRICT ON UPDATE CASCADE, FOREIGN KEY (GAL_NUM) REFERENCES GALLERY ON DELETE RESTRICT ON UPDATE CASCADE,MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 111
  • 112. General Rules Governing Relationships Among Tables SQL statement associated with the combination of Optional and mandatory Vs. Relationships (N:M, 1:M, 1:1)MELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 112
  • 113. General Rules Governing Relationships Among Tables Figure 5.56: M:N, Both Sides Mandatory Figure 5.57: M:N, Both Sides OptionalMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 113
  • 114. General Rules Governing Relationships Among Tables Figure 5.58: M:N, One Side Optional Figure 5.59: 1:M, Both Sides MandatoryMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 114
  • 115. General Rules Governing Relationships Among Tables Figure 5.58: M:N, One Side OptionalMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 115
  • 116. General Rules Governing Relationships Among Tables Figure 5.58: M:N, One Side OptionalMELJUN CORTES, MBA,MPA,BSCS Mandatory 116 SQL MELJUN CORTES ( CSSD04C4) Figure 5.59: 1:M, Both Sides
  • 117. General Rules Governing Relationships Among Tables Figure 5.60: 1:M, Both Sides OptionalMELJUN CORTES, MBA,MPA,BSCS ( CSSD04C4) SQL MELJUN CORTES 117 Figure 5.61: 1:M, Many Side Optional, One Side Mandatory
  • 118. General Rules Governing Relationships Among Tables Figure 5.62: 1:M, One Side Optional, One Side MandatoryMELJUN CORTES, MBA,MPA,BSCSMandatory 118 SQL MELJUN CORTES ( CSSD04C4) Figure 5.63: 1:1, Both Sides
  • 119. General Rules Governing Relationships Among Tables Figure 5.64: 1:1, Both Sides OptionalMELJUN CORTES, MBA,MPA,BSCSOne(Side Mandatory SQL MELJUN CORTES CSSD04C4) Figure 5.65: 1:1, One Side Optional, 119
  • 120. General Rules Governing Relationships Among Tables Figure 5.66: Weak Entity, Foreign Key Located in Weak EntityMELJUN CORTES,Multivalued Attributes (New Table inTable Figure 5.67: MELJUN CORTES ( New 1:M MBA,MPA,BSCSin the CSSD04C4) SQL Relationship, Foreign Key CAR_VIN 120