Chapter 5Chapter 5
Structured Query Structured Query Language (SQL)Language (SQL)
MELJUN CORTES, MBA,MPA,BSCS
2MELJUN CORTES ( CSSD04C4) SQL
In this chapter, you will In this chapter, you will learn:learn:
The basic commands and The basic commands and functions of SQLfunctions of SQL
How SQL is used for data How SQL is used for data manipulation (to add, modify, manipulation (to add, modify, delete, and retrieve data)delete, and retrieve data)
How to use SQL to query a How to use SQL to query a database to extract useful database to extract useful informationinformation
MELJUN CORTES, MBA,MPA,BSCS
3MELJUN CORTES ( CSSD04C4) SQL
In this chapter, you will In this chapter, you will learn:learn:
How SQL is used for data How SQL is used for data administration (to create tables, administration (to create tables, indexes, and views)indexes, and views)
About more advanced SQL About more advanced SQL features such as updatable views, features such as updatable views, stored procedures, and triggersstored procedures, and triggers
MELJUN CORTES, MBA,MPA,BSCS
4MELJUN CORTES ( CSSD04C4) SQL
Introduction to SQLIntroduction to SQL Ideal database languageIdeal database language
Create database and table structuresCreate database and table structures Perform basic data management Perform basic data management
chores (add, delete, and modify)chores (add, delete, and modify) Perform complex queries to Perform complex queries to
transform data into useful transform data into useful informationinformation
MELJUN CORTES, MBA,MPA,BSCS
5MELJUN CORTES ( CSSD04C4) SQL
Introduction to SQLIntroduction to SQL SQL is the ideal DB languageSQL is the ideal DB language
Data definition languageData definition language (create (create tables and define access right to tables and define access right to tables)tables)
Data manipulation languageData manipulation language (update (update and manipulate data within database and manipulate data within database tables)tables)
MELJUN CORTES, MBA,MPA,BSCS
6MELJUN CORTES ( CSSD04C4) SQL
Good Reasons to Study Good Reasons to Study SQLSQL
Easy to learnEasy to learn Portable to many database Portable to many database
specification, only minor specification, only minor differences among various SQLs differences among various SQLs defined in Oracle, SQL server, defined in Oracle, SQL server, DB2, Informix, Access, my SQL, …DB2, Informix, Access, my SQL, …
MELJUN CORTES, MBA,MPA,BSCS
7MELJUN CORTES ( CSSD04C4) SQL
Good Reasons to Study Good Reasons to Study SQLSQL
ANSI standardization effort led to ANSI standardization effort led to de de factofacto query standard for relational query standard for relational database (SQL-99 or SQL3)database (SQL-99 or SQL3)
Forms basis for present and future Forms basis for present and future DBMS integration effortsDBMS integration efforts
Becomes catalyst in development of Becomes catalyst in development of distributed databases and database distributed databases and database client/server architectureclient/server architecture
MELJUN CORTES, MBA,MPA,BSCS
8MELJUN CORTES ( CSSD04C4) SQL
Data Definition Data Definition CommandsCommands
Database modelDatabase model PRODUCT and PRODUCT and
VENDORVENDOR
MELJUN CORTES, MBA,MPA,BSCS
9MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
10MELJUN CORTES ( CSSD04C4) SQL
Data Definition Data Definition CommandsCommands
Create database structureCreate database structure Holds all tables and is a collection of Holds all tables and is a collection of
physical files stored on diskphysical files stored on disk DBMS automatically creates tables to store DBMS automatically creates tables to store
metadatametadata Schema: a group of database objects (tables, Schema: a group of database objects (tables,
indexes and relationships)indexes and relationships) Database administrator creates structure or Database administrator creates structure or
schemaschema Logical group of tables or logical databaseLogical group of tables or logical database Groups tables by ownerGroups tables by owner Enforces securityEnforces security
MELJUN CORTES, MBA,MPA,BSCS
11MELJUN CORTES ( CSSD04C4) SQL
Data Definition Data Definition CommandsCommands
ANSI standard to create ANSI standard to create database schemadatabase schema
CREATE SCHEMA AUTHORIZATION <creator>
Example:CREATE SCHEMA AUTHORIZATION JONES
MELJUN CORTES, MBA,MPA,BSCS
12MELJUN CORTES ( CSSD04C4) SQL
Data Dictionary TableData Dictionary Table
MELJUN CORTES, MBA,MPA,BSCS
13MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
14MELJUN CORTES ( CSSD04C4) SQL
Creating Table Creating Table StructureStructure
Data TypesData Types Number:Number:
NUMBER(L,D)NUMBER(L,D) INTEGERINTEGER SMALLINTSMALLINT DECIMAL(L,D)DECIMAL(L,D)
Character:Character: CHAR(L)CHAR(L) VARCHAR(L)VARCHAR(L)
MELJUN CORTES, MBA,MPA,BSCS
15MELJUN CORTES ( CSSD04C4) SQL
Creating Table Creating Table StructureStructure
Data TypesData Types DateDate
DATEDATE OthersOthers
TIMETIME TIME-STAMPTIME-STAMP REALREAL DOUBLEDOUBLE FLOATFLOAT ODLODL ……
MELJUN CORTES, MBA,MPA,BSCS
16MELJUN CORTES ( CSSD04C4) SQL
Creating Table Creating Table StructureStructure
Tables store end-user dataTables store end-user data May be based on data dictionary May be based on data dictionary
entriesentriesCREATE 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
17MELJUN CORTES ( CSSD04C4) SQL
Example: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
18MELJUN CORTES ( CSSD04C4) SQL
Example: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 tableYou can change vendor’s code
MELJUN CORTES, MBA,MPA,BSCS
19MELJUN CORTES ( CSSD04C4) SQL
Using DomainsUsing Domains Domain is set of permissible values for a columnDomain is set of permissible values for a column Definition requires:Definition requires:
NameName Data typeData type Default valueDefault value Domain constraint or conditionDomain constraint or condition
CREATE DOMAIN <domain_name> AS DATA_TYPE[DEFAULT <default_value>][CHECK (<condition>)]
MELJUN CORTES, MBA,MPA,BSCS
20MELJUN CORTES ( CSSD04C4) SQL
Using DomainsUsing Domains Example:Example:
You can use domain name instead of attribute’s You can use domain name instead of attribute’s data type, when you define a new tabledata type, when you define a new table
CREATE DOMAIN MARITAL_STATUS AS VARCHAR(8) AS DATA_TYPECHECK (VALUE IN (‘Single’, ‘Married’, ‘Divorced’, ‘Widowed’));
CREATE 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
21MELJUN CORTES ( CSSD04C4) SQL
Using DomainsUsing Domains Draw domain values from other Draw domain values from other
tables by including a SELECT tables by including a SELECT statement int eh CHECK clausestatement int eh CHECK clause
CREATE DOMAIN DISCOUNTING_RATES AS NUMBER(5,2)CHECK (VALUE IN (SELECT DISCOUNT FROM DISCOUNTBL);
DISCOUNT attributes in DISCOUNTBL table
MELJUN CORTES, MBA,MPA,BSCS
22MELJUN CORTES ( CSSD04C4) SQL
Using DomainsUsing Domains Delete domainDelete domain
Not all database support create domain like Oracle Not all database support create domain like Oracle DROP DOMAIN <domain_name> [RESTRICT |CASCADE]
DROP DOMAIN MARITAL_STATUS CASCADE;
Prevent deleting until no attributes based on the domain
Change data type to the one defined In domain’s definition
MELJUN CORTES, MBA,MPA,BSCS
23MELJUN CORTES ( CSSD04C4) SQL
SQL Integrity SQL Integrity ConstraintsConstraints
Adherence to Adherence to entity integrityentity integrity and and referential integrityreferential integrity rules is crucial rules is crucial Entity integrity enforced automatically if Entity integrity enforced automatically if
primary key specified in CREATE TABLE primary key specified in CREATE TABLE command sequencecommand sequence
Referential integrity can be enforced in Referential integrity can be enforced in specification of FOREIGN KEYspecification of FOREIGN KEY
Other specifications to ensure conditions met:Other specifications to ensure conditions met: ON DELETE RESTRICTON DELETE RESTRICT ON UPDATE CASCADEON UPDATE CASCADE
MELJUN CORTES, MBA,MPA,BSCS
24MELJUN CORTES ( CSSD04C4) SQL
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 Some database does this automatically without explicit automatically without explicit specificationsspecifications
MELJUN CORTES, MBA,MPA,BSCS
25MELJUN CORTES ( CSSD04C4) SQL
Data Manipulation Data Manipulation CommandsCommandsCommon SQL CommandsCommon SQL Commands
Table 5.3
MELJUN CORTES, MBA,MPA,BSCS
26MELJUN CORTES ( CSSD04C4) SQL
Data Entry and SavingData Entry and Saving Enters data into a tableEnters data into a table
INSERT INTO <table name> VALUES (attribute 1 value, attribute 2 value, … etc.);
INSERT INTO VENDORVALUES (21225, ‘my company’, ‘jun ni’, ‘319’,’232-2194’,’IA’,’Y’);
MELJUN CORTES, MBA,MPA,BSCS
27MELJUN CORTES ( CSSD04C4) SQL
Data Entry and SavingData Entry and Saving
Use form (GUI) to enter dataUse form (GUI) to enter data
MELJUN CORTES, MBA,MPA,BSCS
28MELJUN CORTES ( CSSD04C4) SQL
Data Entry and SavingData Entry and Saving
Saves changes to diskSaves changes to disk
COMMIT <table names> ;
MELJUN CORTES, MBA,MPA,BSCS
29MELJUN CORTES ( CSSD04C4) SQL
Listing Table Contents Listing Table Contents and Other Commandsand Other Commands
Allows table contents to be listedAllows table contents to be listedSELECT <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
30MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
31MELJUN CORTES ( CSSD04C4) SQL
Listing Table Contents Listing Table Contents and Other Commandsand Other Commands
UPDATE command makes data UPDATE command makes data entry correctionsentry corrections
UPDATE PRODUCT SET P_INDATE=’01/18/2003’ WHERE P_CODE=’13-Q2/P2’
MELJUN CORTES, MBA,MPA,BSCS
32MELJUN CORTES ( CSSD04C4) SQL
Listing Table Contents Listing Table Contents and Other Commandsand Other Commands
ROLLBACK command restores ROLLBACK command restores database back to previous database back to previous condition if COMMIT hasn’t been condition if COMMIT hasn’t been usedusedROLLBACK;
MELJUN CORTES, MBA,MPA,BSCS
33MELJUN CORTES ( CSSD04C4) SQL
Listing Table Contents Listing Table Contents and Other Commandsand Other Commands
DELETE command removes table DELETE command removes table rowrow
DELETE FROM PRODUCT WHERE P_CODE=‘2238/QPD’;
DELETE FROM PRODUCT WHERE P_MIN=5;
5 ROWS ARE DELETED
MELJUN CORTES, MBA,MPA,BSCS
34MELJUN CORTES ( CSSD04C4) SQL
QueriesQueries Creating partial listings of table Creating partial listings of table
contentscontentsSELECT <column(s)>FROM <table name>WHERE <conditions>;
Table 5.4 Mathematical Operators
MELJUN CORTES, MBA,MPA,BSCS
35MELJUN CORTES ( CSSD04C4) SQL
ExamplesExamples
Mathematical Mathematical operatorsoperatorsSELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE
FROM PRODUCTWHERE V_CODE = 21344;
MELJUN CORTES, MBA,MPA,BSCS
36MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
37MELJUN CORTES ( CSSD04C4) SQL
ExamplesExamples
Mathematical Mathematical operatorsoperatorsSELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODEFROM PRODUCTWHERE V_CODE <> 21344;
Not equal
MELJUN CORTES, MBA,MPA,BSCS
38MELJUN CORTES ( CSSD04C4) SQL
ExamplesExamples
Mathematical Mathematical operatorsoperatorsSELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE
FROM PRODUCTWHERE P_PRICE<=10;
MELJUN CORTES, MBA,MPA,BSCS
39MELJUN CORTES ( CSSD04C4) SQL
ExamplesExamples Mathematical operators on Mathematical operators on
character attributescharacter attributes
Mathematical operators on datesMathematical operators on dates
SELECT P_CODE,P_DESCRIPT,P_ONHAND,P_MIN,P_PRICEFROM PRODUCTWHERE P_CODE < ‘1558-QWI’;
SELECT P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE,PINDATEFROM PRODUCTWHERE P_INDATE >= ‘01/20/2002’;
MELJUN CORTES, MBA,MPA,BSCS
40MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
41MELJUN CORTES ( CSSD04C4) SQL
Computed Columns Computed Columns New columns can be created New columns can be created
through valid computations or through valid computations or formulasformulas Formulas may contain mathematical Formulas may contain mathematical
operatorsoperators May contain attributes of any tables May contain attributes of any tables
specified in FROM clausespecified in FROM clause Alias is alternate name given to Alias is alternate name given to
table or column in SQL statementtable or column in SQL statementSELECT P_DESCRIPT,P_ONHAND,P_PRICE,P_ONHAND*P_PRICE AS TOTVALUE FROM PRODUCT;
MELJUN CORTES, MBA,MPA,BSCS
42MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
43MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
44MELJUN CORTES ( CSSD04C4) SQL
OperatorsOperators
Logical: AND, OR, Logical: AND, OR, NOTNOT
SELECT *FROM PRODUCTWHERE V_CODE = 21344 OR V_CODE = 24288;
MELJUN CORTES, MBA,MPA,BSCS
45MELJUN CORTES ( CSSD04C4) SQL
OperatorsOperators Rules of precedenceRules of precedence
Conditions within parenthesis Conditions within parenthesis executed firstexecuted first
Boolean algebraBoolean algebraSELECT *P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCTWHERE (P_PRICE<50 AND P_INDATE>’01/05/2002’) OR V_CODE=24288;
MELJUN CORTES, MBA,MPA,BSCS
46MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
47MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
48MELJUN CORTES ( CSSD04C4) SQL
SpecialSpecial Operators Operators BETWEEN - defines limitsBETWEEN - defines limits
IS NULL - checks for nullsIS NULL - checks for nulls
SELECT * FROM PRODUCT WHERE P_PRICE BETWEEN 500.00 AND 100.00;
SELECT P_CODE, P_DESCRIPT FROM PRODUCT WHERE P_MIN IS NULL;
MELJUN CORTES, MBA,MPA,BSCS
49MELJUN CORTES ( CSSD04C4) SQL
SpecialSpecial Operators Operators LIKE - checks for similar string LIKE - checks for similar string
(wildcard)(wildcard)SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONEFROM VENDOR WHERE V_CONTACT LIKE ‘Smith%’;
MELJUN CORTES, MBA,MPA,BSCS
50MELJUN CORTES ( CSSD04C4) SQL
SpecialSpecial Operators Operators
IN - checks for value in a set 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 EFFICIENTLY
MELJUN CORTES, MBA,MPA,BSCS
51MELJUN CORTES ( CSSD04C4) SQL
SpecialSpecial Operators Operators
EXISTS – NOT NULLEXISTS – 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
52MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data ManagementManagementCommandsCommands ALTER - changes table structureALTER - changes table structure
ADD - adds columnADD - adds column MODIFY - changes column MODIFY - changes column
characteristicscharacteristicsALTER TABLE <table name>ADD (<column name> <new column characteristics>);
ALTER TABLE <table name>MODIFY (<column name> <new column characteristics>);
MELJUN CORTES, MBA,MPA,BSCS
53MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data ManagementManagementCommandsCommands
ALTER - changes table structureALTER - changes table structure ADD - adds columnADD - adds column MODIFY - changes column MODIFY - changes column
characteristicscharacteristics
MELJUN CORTES, MBA,MPA,BSCS
54MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data ManagementManagementCommandsCommands
Changing a column’s data type:Changing a column’s data type:
Changing attribute characteristicsChanging attribute characteristics
ALTER TABLE PRODUCT MODIFY (V_CODE CHAR(5));
CHANGE FROM INTEGER TO CHAARCTERS
ALTER TABLE PRODUCT MODIFY (P_PRICE DECIMAL(9,2));
Increase width of P_PRICE
MELJUN CORTES, MBA,MPA,BSCS
55MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data ManagementManagementCommandsCommands
Adding a column to the table:Adding a column to the table:
Dropping (delete) a column from Dropping (delete) a column from the table:the table:
ALTER TABLE PRODUCT ADD ( P_SALECODE CHAR(1));
ALTER TABLE VENDOR DROP COLUMN V_ORDER;
Add column named P_SALECODE to PRODUCT table
MELJUN CORTES, MBA,MPA,BSCS
56MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Commands Management Commands
(con’t.)(con’t.) Entering data into Entering data into
new columnnew column Update entries:Update entries: UPDATE PRODUCT
SET P_SALECODE=‘2’ WHERE P_CODE=‘1546-qq2’;
MELJUN CORTES, MBA,MPA,BSCS
57MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Commands Management Commands
(con’t.)(con’t.) Entering data into Entering data into
new columnnew column
UPDATE PRODUCTSET P_SALECODE=‘1’ WHERE P_CODE IN (‘2232/QWE’, ‘2232/QTY’);
MELJUN CORTES, MBA,MPA,BSCS
58MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
59MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Commands Management Commands
(con’t.)(con’t.)UPDATE PRODUCTSET P_SALECODE=‘2’ WHERE P_INDATE<’12/25/2001’;
UPDATE PRODUCTSET P_SALECODE=‘1’ WHERE P_INDATE>’01/16/2002 AND P_INDATE<’01/21/2002’;
MELJUN CORTES, MBA,MPA,BSCS
60MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
61MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Arithmetic operators and rules of Arithmetic operators and rules of precedenceprecedence
Table 5.5
MELJUN CORTES, MBA,MPA,BSCS
62MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Arithmetic operators and rules of Arithmetic operators and rules of precedenceprecedence
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
63MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Copying parts of tablesCopying parts of tables Copy the contents of selected table Copy the contents of selected table
columns with data values 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
64MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Copying parts of tablesCopying parts of tables
CREATE TABLE (PARTPART_CODE CHAR(8) NOT NULL UNIQUE,PART_DESCRIPT CHAR(35)PART_PRICE DECIMAL(8,2),PRIMARY KEY (PART_CODE));
NEW TABLE NAME
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
65MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
66MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Deleting a table from databaseDeleting a table from database
DROP TABLE PART;
MELJUN CORTES, MBA,MPA,BSCS
67MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Primary and foreign key Primary and foreign key
designationdesignationALTER TABLE LINEADD PRIMARY KEY (INV_NUMBER, LINE_NUMBER)ADD FOREIGN KEY (INV_NUMBER) REFERENCES INVOICEADD FOREIGN KEY (PROD_CODE) REFERENCES PRODUCT;
MELJUN CORTES, MBA,MPA,BSCS
68MELJUN CORTES ( CSSD04C4) SQL
Advanced Data Advanced Data Management Management
Commands (con’t.)Commands (con’t.) Primary and foreign key Primary and foreign key
designationdesignationALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE);
ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR;
MELJUN CORTES, MBA,MPA,BSCS
69MELJUN CORTES ( CSSD04C4) SQL
More complex queries More complex queries and sql functionsand sql functions
Ordering listing: list in special Ordering listing: list in special order (ascending order to order (ascending order to descending order)descending order)ORDER BY <attributes>
ORDER BY <attributes> DESC
ascending
descending
SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE FROM PRODUCT ORDER BY P_PRICE;
MELJUN CORTES, MBA,MPA,BSCS
70MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
71MELJUN CORTES ( CSSD04C4) SQL
More complex queries More complex queries and sql functionsand sql functions
Cascading order sequenceCascading order sequence
ORDER BY <attribute1 attribute2, …>
ORDER BY <attribute1, attribute2, …> DESC
SELECT EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_AREACODE, EMP_PHONE
FROM EMPLOYEEORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL;
MELJUN CORTES, MBA,MPA,BSCS
72MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
73MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
74MELJUN CORTES ( CSSD04C4) SQL
More complex queries More complex queries and sql functionsand sql functions
Use order by clause in Use order by clause in conjunction with other SQL conjunction with other SQL commandscommandsSELECT P_DESCRIPT, V_CODE, P_INDATE, P_PRICE FROM PRODUCT WHERE P_INDATE<’01/21/2002’ AND P_PRICE<=50.00ORDER BY V_CODE, P_PRICE DESC;
MELJUN CORTES, MBA,MPA,BSCS
75MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
76MELJUN CORTES ( CSSD04C4) SQL
More complex queries More complex queries and sql functionsand sql functions
List unique valuesList unique values
SELECT DISTINCT V_CODE FROM PRODUCT;
MELJUN CORTES, MBA,MPA,BSCS
77MELJUN CORTES ( CSSD04C4) SQL
AggregateAggregate Function Operations Function Operations
MELJUN CORTES, MBA,MPA,BSCS
78MELJUN CORTES ( CSSD04C4) SQL
AggregateAggregate Function Operations Function Operations
COUNT (count raw numbers for a COUNT (count raw numbers for a given column)given column)
SELECT COUNT(DISTINCT V_CODE)FROM PRODUCT;
SELECT COUNT(DISTINCT V_CODE)FROM PRODUCTWHERE P_PRICE <= 10.00;
MELJUN CORTES, MBA,MPA,BSCS
79MELJUN CORTES ( CSSD04C4) SQL
AggregateAggregate Function Operations Function Operations
MAX and MINMAX and MIN
SELECT MIN(P_PRICE)FROM PRODUCT;
SELECT P_CODE, P_DESCRIPT, P_PRICEFROM PRODUCTWHERE P_PRICE = MAX(P_PRICE);
MELJUN CORTES, MBA,MPA,BSCS
80MELJUN CORTES ( CSSD04C4) SQL
Example Aggregate Example Aggregate Function Operations Function Operations
(con’t.)(con’t.) SUMSUM
AVGAVG
SELECT SUM(P_ONHAND * P_PRICE)FROM PRODUCT;
SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODEFROM PRODUCTWHERE P_PRICE > (SELECT AVG(P_PRICE) FROM PRODUCT)ORDER BY P_PRICE DESC;
MELJUN CORTES, MBA,MPA,BSCS
81MELJUN CORTES ( CSSD04C4) SQL
Grouping dataGrouping data Creates frequency distributionsCreates frequency distributions Only valid when used with SQL Only valid when used with SQL
arithmetic functionsarithmetic functions
HAVING clause operates like WHERE for HAVING clause operates like WHERE for grouping output grouping output
SELECT P_SALECODE, MIN(P_PRICE)FROM PRODUCT_2GROUP BY P_SALECODE;
SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE)FROM PRODUCT_2GROUP BY V_CODEHAVING AVG(P_PRICE) < 10;
MELJUN CORTES, MBA,MPA,BSCS
82MELJUN CORTES ( CSSD04C4) SQL
More Complex Queries More Complex Queries and and
SQL Functions (con’t.)SQL Functions (con’t.) Virtual tables: creating a viewVirtual tables: creating a view CREATE VIEW commandCREATE VIEW command Creates logical table existing only in Creates logical table existing only in
virtual memoryvirtual memory
SQL indexes SQL indexes
CREATE VIEW PRODUCT_3 ASSELECT P_DESCRIPT, P_ONHAND, P_PRICEFROM PRODUCTWHERE P_PRICE > 50.00;
CREATE INDEX P_CODEXON PRODUCT(P_CODE);
MELJUN CORTES, MBA,MPA,BSCS
83MELJUN CORTES ( CSSD04C4) SQL
Joining database tablesJoining database tables Data are retrieved from more than one tableData are retrieved from more than one table
Recursive queries joins a table to itselfRecursive queries joins a table to itself
Outer joins can be used when ‘null’ values need to be Outer joins can be used when ‘null’ values need to be included in query result included in query result
SELECT PRODUCT.P_DESCRIPT, PRODUCT.P_PRICE, VENDOR.V_NAME, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_PHONEFROM PRODUCT, VENDORWHERE PRODUCT.V_CODE = VENDOR.V_CODE;
SELECT A.EMP_NUM,A.EMP_LNAME,A.EMP_MGR,B.EMP_LNAME FROM EMP A, EMP BWHERE A.EMP_MGR=B.EMP_NUMORDER BY A.EMP_MGR
MELJUN CORTES, MBA,MPA,BSCS
84MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
85MELJUN CORTES ( CSSD04C4) SQL
Updatable ViewsUpdatable Views
Common operation in production Common operation in production environments is use of batch routines to environments is use of batch routines to update master table attributes using update master table attributes using transaction datatransaction data
Batch update routine pools the Batch update routine pools the transactions into a single “batch” to transactions into a single “batch” to update a master table field in a single update a master table field in a single operation.operation.
Overnight batch jobsOvernight batch jobs Not all views are updatableNot all views are updatable Example: master PRODUCT and product Example: master PRODUCT and product
monthly sales table (PMSALES)monthly sales table (PMSALES)
MELJUN CORTES, MBA,MPA,BSCS
86MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
87MELJUN CORTES ( CSSD04C4) SQL
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 an updatable view.
Updatable view is a view that can be used to update attributes in base tables.
MELJUN CORTES, MBA,MPA,BSCS
88MELJUN CORTES ( CSSD04C4) SQL
Updatable ViewsUpdatable Views RestrictionsRestrictions
GROUP BY expressions cannot be GROUP BY expressions cannot be usedused
Cannot use set operators---UNION, Cannot use set operators---UNION, INTERSECTION, etc.INTERSECTION, etc.
Most restrictions based on use of Most restrictions based on use of JOINS or group operators in viewsJOINS or group operators in views
MELJUN CORTES, MBA,MPA,BSCS
89MELJUN CORTES ( CSSD04C4) SQL
Updatable ViewsUpdatable Views Create Updatable viewCreate Updatable view
Now you can use UPDATE command to Now you can use UPDATE command to update the viewupdate the view
CREATE VIEW MPSVUPD AS (SET PRODUCT.PROD_ID, PRODUCT.PROD_QOH, PMSALES.PMS_QTYFROM PRODUCT, MPSALES WHERE PRODUCT.PROD_ID=PMSALES.PROD_ID);
UPDATE PMSVUPDSET PROD_QOH=PROD_QOH-PSM-QTY
MELJUN CORTES, MBA,MPA,BSCS
90MELJUN CORTES ( CSSD04C4) SQL
Procedural SQLProcedural SQL SQL is a declarative language, not SQL is a declarative language, not
support conditional executions of support conditional executions of procedures and looping executionsprocedures and looping executions
SQL shortcomingsSQL shortcomings Doesn’t support execution of stored Doesn’t support execution of stored
procedures based on logical conditionprocedures based on logical condition Fails to support looping operationsFails to support looping operations
The way to use logical or The way to use logical or procedural statements is to embed procedural statements is to embed SQL into programming languagesSQL into programming languages
MELJUN CORTES, MBA,MPA,BSCS
91MELJUN CORTES ( CSSD04C4) SQL
Procedural SQLProcedural SQL SolutionSolution
Embedded SQL can be called from within procedural Embedded SQL can be called from within procedural programming languages.programming languages.
Using embedded SQL is still the most common Using embedded SQL is still the most common approach to maintaining procedural approach to maintaining procedural capabilities.capabilities.
Shared Code is isolated and used by all application Shared Code is isolated and used by all application programs.programs.
Procedural SQL (PL/SQL) stored within the database, Procedural SQL (PL/SQL) stored within the database, executed by DBMS, and invoked by the end userexecuted by DBMS, and invoked by the end user
TriggersTriggers Stored proceduresStored procedures PL/SQL functionsPL/SQL functions
MELJUN CORTES, MBA,MPA,BSCS
92MELJUN CORTES ( CSSD04C4) SQL
Procedural SQL Procedural SQL (con’t.)(con’t.) Procedural SQL allows the use of Procedural SQL allows the use of
procedural code and SQL procedural code and SQL statements that are stored within statements that are stored within the database.the database.
The procedural code is executed The procedural code is executed by the DBMS when it is invoked by by the DBMS when it is invoked by the end user.the end user.
MELJUN CORTES, MBA,MPA,BSCS
93MELJUN CORTES ( CSSD04C4) SQL
Procedural SQL Procedural SQL (con’t.)(con’t.)
End users can use procedural SQL End users can use procedural SQL (PL/SQL) to create:(PL/SQL) to create: TriggersTriggers Stored proceduresStored procedures PL/SQL functions (different from SQL PL/SQL functions (different from SQL
built-in functions)built-in functions)
MELJUN CORTES, MBA,MPA,BSCS
94MELJUN CORTES ( CSSD04C4) SQL
TriggersTriggers Procedural SQL code invoked Procedural SQL code invoked
before or after data row is before or after data row is selected, inserted, or updatedselected, inserted, or updated
Associated with a database tableAssociated with a database table Table may have multiple triggersTable may have multiple triggers Executed as part of transactionExecuted as part of transaction
MELJUN CORTES, MBA,MPA,BSCS
95MELJUN CORTES ( CSSD04C4) SQL
TriggersTriggers Can enforce particular constraintsCan enforce particular constraints Automate critical actions and Automate critical actions and
provide warnings for remedial provide warnings for remedial actionaction
Can update values, insert records, Can update values, insert records, and call proceduresand call procedures
Add processing powerAdd processing power
MELJUN CORTES, MBA,MPA,BSCS
96MELJUN CORTES ( CSSD04C4) SQL
Triggers (con’t.)Triggers (con’t.) Oracle example Oracle example
CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDERAFTER INSERT OR UPDATE OF P_ONHAND ON PRODUCTBEGIN
UPDATE PRODUCTSET P_REORDER=1WHERE P_ONHAND<=P_MINEND;
MELJUN CORTES, MBA,MPA,BSCS
97MELJUN CORTES ( CSSD04C4) SQL
Stored ProceduresStored Procedures Named collection of procedural and Named collection of procedural and
SQL statements stored in databaseSQL statements stored in database Invoked by nameInvoked by name Executed as unitExecuted as unit Invoked with EXECInvoked with EXEC Used in multiple-update transaction Used in multiple-update transaction
(entire contents of stored procedure (entire contents of stored procedure will be transmitted and executed, will be transmitted and executed, which reduce network transfer which reduce network transfer delay.delay.
MELJUN CORTES, MBA,MPA,BSCS
98MELJUN CORTES ( CSSD04C4) SQL
Stored ProceduresStored Procedures Invoked with EXECInvoked with EXEC CREATE OR REPLACE PROCEDURE procedure_name (argument IN/OUT data-type, etc) IS/AS BEGIN
DECLARE variable name and data typePL/SQL or SQL statements;
END;
EXEC store_procedure_name (parameter, parameter, …)
MELJUN CORTES, MBA,MPA,BSCS
99MELJUN CORTES ( CSSD04C4) SQL
Stored ProceduresStored Procedures ExampleExample CREATE OR REPLACE PROCEDURE PROD_REORDER_SETAS BEGIN UPDATE PRODUCTSET P_REORDER=1 WHERE P_ONHAND <=P_MIN;UPDATE PRODUCTSET P_REORDER=0 WHERE P_ONHAND>_MIN;END;
EXEC PROD_REORDER_SET;
MELJUN CORTES, MBA,MPA,BSCS
100MELJUN CORTES ( CSSD04C4) SQL
Stored ProceduresStored Procedures ExampleExample 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
101MELJUN CORTES ( CSSD04C4) SQL
PL/SQL Stored FunctionsPL/SQL Stored Functions
Named group of procedural and Named group of procedural and SQL statements that returns a SQL statements that returns a valuevalueCREATE FUNCTION function_name (argument IN data-type, etc)RETURN data-typeAS BEGIN
PL/SQL statements;RETURN (value); ……
END;
MELJUN CORTES, MBA,MPA,BSCS
102MELJUN CORTES ( CSSD04C4) SQL
PL/SQL Stored FunctionsPL/SQL Stored Functions
Invoked from within stored Invoked from within stored procedures or triggersprocedures or triggers
Cannot be invoked from within Cannot be invoked from within SQL statementsSQL statements
CREATE FUNCTION function_name (argument IN data-type, etc)RETURN data-typeAS BEGIN
PL/SQL statements;RETURN (value); ……
END;
MELJUN CORTES, MBA,MPA,BSCS
103MELJUN CORTES ( CSSD04C4) SQL
Converting an ER model Converting an ER model into a database structureinto a database structure Require the some rulesRequire the some rules Database of artistDatabase of artist
A painter may have many paintings A painter may have many paintings (1:M)(1:M)
Each painter painted by one and only Each painter painted by one and only one painter (so far it is a 1:M) one painter (so far it is a 1:M) relationships between PAINTER and relationships between PAINTER and PAINTINGPAINTING
A painter must have at least painting A painter must have at least painting (cardinality is (1:N)(cardinality is (1:N)
A painting might (or might not) be A painting might (or might not) be exhibited in a gallery (another Table, exhibited in a gallery (another Table, which is optional to the paining entity)which is optional to the paining entity)
MELJUN CORTES, MBA,MPA,BSCS
104MELJUN CORTES ( CSSD04C4) SQL
Artist Database ERD Artist Database ERD and Tablesand Tables
Figure 5.55
MELJUN CORTES, MBA,MPA,BSCS
105MELJUN CORTES ( CSSD04C4) SQL
MELJUN CORTES, MBA,MPA,BSCS
106MELJUN CORTES ( CSSD04C4) SQL
Table Structure and Table Structure and specific requirementsspecific 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
107MELJUN CORTES ( CSSD04C4) SQL
Further action Further action considerationsconsiderations
1. Delete raw of painter will effect the PAINTER’s table and cerate delete anomaly. Impose a DELETE RESTRICT on PAINTER’s table
2. No problem to add raw in PAINTER”s table
3. 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 raw
6. UPDATE CASCADE is used for GALEERY table
MELJUN CORTES, MBA,MPA,BSCS
108MELJUN CORTES ( CSSD04C4) SQL
Creates Tables using Creates Tables using SQLSQL
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
109MELJUN CORTES ( CSSD04C4) SQL
Creates Tables using Creates Tables using SQLSQL
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
110MELJUN CORTES ( CSSD04C4) SQL
Creates Tables using Creates Tables using SQLSQL
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
111MELJUN CORTES ( CSSD04C4) SQL
Creates Tables using Creates Tables using SQLSQL
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 PAINTERON DELETE RESTRICTON UPDATE CASCADE,
FOREIGN KEY (GAL_NUM) REFERENCES GALLERYON DELETE RESTRICTON UPDATE CASCADE,
MELJUN CORTES, MBA,MPA,BSCS
112MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
SQL statement associated with the combination of
Optional and mandatoryVs.Relationships (N:M, 1:M, 1:1)
MELJUN CORTES, MBA,MPA,BSCS
113MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
Figure 5.57: M:N, Both Sides Optional
Figure 5.56: M:N, Both Sides Mandatory
MELJUN CORTES, MBA,MPA,BSCS
114MELJUN CORTES ( CSSD04C4) SQL
General Rules Governing General Rules Governing Relationships Among Relationships Among
TablesTables
Figure 5.58: M:N, One Side Optional
Figure 5.59: 1:M, Both Sides Mandatory
MELJUN CORTES, MBA,MPA,BSCS
115MELJUN CORTES ( CSSD04C4) SQL
General Rules Governing General Rules Governing Relationships Among Relationships Among
TablesTables
Figure 5.58: M:N, One Side Optional
MELJUN CORTES, MBA,MPA,BSCS
116MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
Figure 5.58: M:N, One Side Optional
Figure 5.59: 1:M, Both Sides Mandatory
MELJUN CORTES, MBA,MPA,BSCS
117MELJUN CORTES ( CSSD04C4) SQL
General Rules Governing General Rules Governing Relationships Among Relationships Among
TablesTables
Figure 5.60: 1:M, Both Sides Optional
Figure 5.61: 1:M, Many Side Optional, One Side Mandatory
MELJUN CORTES, MBA,MPA,BSCS
118MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
Figure 5.62: 1:M, One Side Optional, One Side Mandatory
Figure 5.63: 1:1, Both Sides Mandatory
MELJUN CORTES, MBA,MPA,BSCS
119MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
Figure 5.64: 1:1, Both Sides Optional
Figure 5.65: 1:1, One Side Optional, One Side Mandatory
MELJUN CORTES, MBA,MPA,BSCS
120MELJUN CORTES ( CSSD04C4) SQL
General Rules General Rules Governing Governing
Relationships Among Relationships Among TablesTables
Figure 5.66: Weak Entity, Foreign Key Located in Weak Entity
Figure 5.67: Multivalued Attributes (New Table in 1:M Relationship, Foreign Key CAR_VIN in the New Table