Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr.

Similar presentations


Presentation on theme: "Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr."— Presentation transcript:

1 Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr.
Computer Science & Engineering Department The University of Connecticut 191 Auditorium Road, Box U-155 Storrs, CT (860) About one third of these slides are being used with the permission of Dr. Ling Lui, Associate Professor, College of Computing, Georgia Tech. About one-half of these slides have been adapted from the AWL web site for the textbook.

2 Relational Languages A Relational Language
Defines Operations to Manipulate Relations Used to Specify Retrieval Requests (Queries) Query Result is Expressed in the Form of a Relation Classification Relational Algebra (We’ve Discussed) Relational Calculus To be Briefly Explored as the Basis of ... Structured Query Language (SQL) Relational calculus non-procedural state what the properties that should hold in the result relation are Relational algebra procedural closed: use operators which work on one or two relations and produce another relation chaining of operations

3 Relational Calculus Based on First-Order Predicate Logic
Symbol Alphabet Logic Symbols (e.g., ¬ a Set of Constants a Set of Variables a Set of n-ary Predicates a Set of n-ary Functions Parentheses Expressions (called well-formed formulae (wff)) Built from this Symbol Alphabet Classification: Tuple Relational Calculus Domain Relational Calculus Relational Calculus: Instead of specifying how to obtain the result, specify what the result is, i.e., the relationships that is supposed to hold in the result. Classification: according to the primitive variable used in specifying the queries tuple relational calculus domain relational calculus

4 Tuple Relational Calculus
The Primitive Variable is a Tuple Variable Which Specifies a Tuple of a Relation Ranges Over the Tuples of a Relation In Tuple Relational Calculus, Queries are Specified as {t | F(t)} where t is a Tuple Variable and F is a Formula Consisting of the Atoms and Operators

5 Example EMP(ENO, ENAME, AGE) PROJ(PNO, PNAME, LOC, MGR)
WORKS(ENO, PNO, DUR) Find the Names of Employees under age 30 { t[ENAME] | tEMP t[AGE]<30} Find the Names of Employees working on the CAD/CAM Project { t[ENAME] | tEMP u(u WORKS t[ENO]u v(vPROJu[PNO]=v[PNO] v[PNAME]=‘CAD/CAM’)) ENAME (AGE < 30 (EMP)) ENAME (PNAME=‘CAD/CAM” (PROJ) PNO (WORKS ENOEMP))

6 Tuple Relational Calculus
A formula F is Composed of Atoms Boolean operators ¬ Existential Qualifier  Universal Qualifier  Formation rules: Each Atom is a Formula If F and G are Formulae, so are FG, FG, ¬F, and ¬G If F is a Formula, so is (F) If F is a Formula and t is a Free variable in F, then  t(F) and t(F) are also Formulae Nothing else is a Formula

7 Tuple Relational Calculus
The Atoms are the Following : Tuple variables R.t or R(t) Conditions s[A] t where s and t are Tuple Variables and A and B are Components of s and t, Respectively, and <><=>= specifies that Component A of s stands in relation to component B of t (e.g., s[SALARY] > t[SALARY]) s[A] c where s, A and  are as Defined above and c is a Constant e.g., s[NAME] = 'Smith'.

8 Example Find the names of Employees who have Worked for a Project for more than Two Years { t[ENAME] | tEMP u(u WORKS t[ENO]u u[DUR]=‘24’)) Find all Managers who are less than 40 years old? { t[MGR] | tPROG u(u WORKS t[PNO]uPN v(vEMPu[ENO]=v[ENO] v[AGE]<40))  ENAME (DUR=24 (WORKS) ENO EMP) MGR (AGE<40 EMP ENO (WORKS PNOPROJ))

9 SQL: Tuple Relational Calculus-Based
SQL is a Partial Example of a Tuple Relational Language Simple Queries are all Declarative More Complex Queries are both Declarative and Procedural (e.g., joins, nested queries) Find the names of employees working on the CAD/CAM project SELECT EMP.ENAME FROM EMP, WORKS, PROJ WHERE (EMP.ENO= WORKS.ENO) AND (WORKS.PNO = PROJ.PNO) AND (PROJ.PNAME = “CAD/CAM”) Tuple Variables are Implicit

10 Explicit Tuple Variables
Find the Pairs of all Project Names for those Projects that are Located at the same Place SELECT (P1.PNAME, P2.PNAME) FROM PROJ P1, PROJ P2 WHERE P1.LOC = P2.LOC PNAME, PNAME1 (PROJ LOC = LOC1 PROJ1) Let Proj1(PNAME1, LOC1) = PNAME, LOC (PROJ)

11 SQL Components Data Definition Language (DDL)
For External and Conceptual Schemas Views - DDL for External Schemas Data Manipulation Language (DML) Interactive DML Against External and Conceptual Schemas Embedded DML in Host PLs (EQL, JDBC, etc.) Others Integrity (Allowable Values/Referential) Catalog and Dictionary Facilities Transaction Control (Long-Duration and Batch) Authorization (Who can Do What When)

12 SQL DDL and DML Data Definition Language (DDL)
Defining the Relational Schema - Relations, Attributes, Domains - The Meta-Data CREATE TABLE Student: Name(CHAR(30)), SSN(CHAR(9)), GPA(FLOAT(2)) CREATE TABLE Courses: Course#(CHAR(6)), Title(CHAR(20)), Descrip(CHAR(100)), PCourse#(CHAR(6)) Data Manipulation Language (DML) Defining the Queries Against the Schema SELECT Name, SSN From Student Where GPA > 3.00

13 History of SQL SQL is based on the Relational Tuple Calculus
Evolved from SEQUEL: Structured English QUEry Language - part of IBM’s SYSTEM R, 1974 SQL2 Supported by ORACLE, SYBASE, INFORMIX, IBM DB2, SQL SERVER, … MS Access, MySQL, … SQL2 also called SQL/92 is evolved from SQL/86, SQL/89, all were ANSI & ISO standard Ongoing work on SQL3 with OO Extensions

14 Data Definition Language - DDL
A Pre-Defined set of Primitive Types Numeric Character-string Bit-string Additional Types Defining Domains Defining Schema Defining Tables Defining Views Note: Each DBMS May have their Own DBMS Specific Data Types - Is this Good or Bad? primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

15 DDL - Primitive Types Numeric INTEGER (or INT), SMALLINT
REAL, DOUBLE PRECISION FLOAT(N) Floating Point with at Least N Digits DECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D)) have P Total Digits with D to Right of Decimal Note that INTs and REALs are Machine Dependent (Based on Hardware/OS Platform) primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

16 DDL - Primitive Types Character-String CHAR(N) or CHARACTER(N) - Fixed
VARCHAR(N), CHAR VARYING(N), or CHARACTER VARYING(N) Variable with at Most N Characters Bit-Strings BIT(N) Fixed VARBIT(N) or BIT VARYING(N) Variable with at Most N Bits primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

17 DDL - Primitive Types These Specialized Primitive Types are Used to:
Simplify Modeling Process Include “Popular” Types Reduce Composite Attributes/Programming DATE : YYYY-MM-DD TIME: HH-MM-SS TIME(I): HH-MM-SS-F....F - I Fraction Seconds TIME WITH TIME ZONE: HH-MM-SS-HH-MM TIME-STAMP: YYYY-MM-DD-HH-MM-SS-F...F{-HH-MM} NOTE: Different DBMS have Different Date/Time primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

18 DDL - What are Domains? Domains are Similar in Concepts to Programming Language Type Definitions A Domain can be Defined as Follows: CREATE DOMAIN CITY CHAR(15) DEFAULT ‘<Storrs>’; CREATE DOMAIN SSNFORMAT CHAR(9); Advantage of Using Domains Changing a Domain Definition in One Place Changes it Consistently Everywhere it is Used Default Values Can Be Defined for Domains Constraints Can Be Defined for Domains

19 DDL - Dropping a Domain A Domain is Dropped As Follows:
DROP DOMAIN CITY RESTRICT; DROP DOMAIN SSNFORMAT CASCADE; Restrict: Drop Operation Fails If the Domain is Used in Column Definitions Cascade: Drop Operation Causes Columns to be Defined Directly on the Underlying Data Type

20 What is a SQL Schema? A Schema in SQL is the Major Meta-Data Construct
Create a DB to Contain Multiple Tables Supports the Definition of: Relation - Table with Name Attributes - Columns and their Types Identification - Primary Key Constraints - Referential Integrity (FK) Two Part Definition CREATE Schema - Named Database or Conceptually Related Tables CREATE Table - Individual Tables of the Schema

21 DDL-Create/Drop a Schema
Creating a Schema: CREATE SCHEMA MY_COMPANY AUTHORIZATION Demurjian; Schema MY_COMPANY bas Been Created and is Owner by the User “Demurjian” Tables can now be Created and Added to Schema Dropping a Schema: DROP SCHEMA MY_COMPANY RESTRICT; DROP SCHEMA MY_COMPANY CASCADE; Restrict: Drop Operation Fails If Schema is Not Empty Cascade: Drop Operation Removes Everything in the Schema

22 DDL - Create Tables CREATE TABLE EMPLOYEE
( FNAME VARCHAR(15) NOT NULL , MINIT CHAR , LNAME VARCHAR(15) NOT NULL , SSN CHAR(9) NOT NULL , BDATE DATE ADDRESS VARCHAR(30) , SEX CHAR , SALARY DECIMAL(10,2) , SUPERSSN CHAR(9) , DNO INT NOT NULL , PRIMARY KEY (SSN) , FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN) , FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ) ;

23 DDL - Create Tables (continued)
CREATE TABLE DEPARTMENT ( DNAME VARCHAR(15) NOT NULL , DNUMBER INT NOT NULL , MGRSSN CHAR(9) NOT NULL , MGRSTARTDATE DATE , PRIMARY KEY (DNUMBER) , UNIQUE (DNAME) , FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN) ) ; CREATE TABLE DEPT_LOCATIONS (DNUMBER INT NOT NULL , DLOCATION VARCHAR(15) NOT NULL , PRIMARY KEY (DNUMBER, DLOCATION) , FOREIGN KEY (DNUMBER) REFERENCES DEPARTMENT(DNUMBER) ) ;

24 DDL - Create Tables (continued)
CREATE TABLE PROJECT (PNAME VARCHAR(15) NOT NULL , PNUMBER INT NOT NULL , PLOCATION VARCHAR(15) , DNUM INT NOT NULL , PRIMARY KEY (PNUMBER) , UNIQUE (PNAME) , FOREIGN KEY (DNUM) REFERENCES DEPARTMENT(DNUMBER) ) ; CREATE TABLE WORKS_ON (ESSN CHAR(9) NOT NULL , PNO INT NOT NULL , HOURS DECIMAL(3,1) NOT NULL , PRIMARY KEY (ESSN, PNO) , FOREIGN KEY (ESSN) REFERENCES EMPLOYEE(SSN) , FOREIGN KEY (PNO) REFERENCES PROJECT(PNUMBER) ) ;

25 DDL - Create Tables with Constraints
CREATE TABLE EMPLOYEE ( , DNO INT NOT NULL DEFAULT 1, CONSTRAINT EMPPK PRIMARY KEY (SSN) , CONSTRAINT EMPSUPERFK FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN) ON DELETE SET NULL ON UPDATE CASCADE , CONSTRAINT EMPDEPTFK FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ON DELETE SET DEFAULT ON UPDATE CASCADE );

26 DDL - Create Tables with Constraints
CREATE TABLE DEPARTMENT ( , MGRSSN CHAR(9) NOT NULL DEFAULT ' ' , . . . , CONSTRAINT DEPTPK PRIMARY KEY (DNUMBER) , CONSTRAINT DEPTSK UNIQUE (DNAME), CONSTRAINT DEPTMGRFK FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN) ON DELETE SET DEFAULT ON UPDATE CASCADE );

27 Create and Drop: Summary
Defines Types and Order of Attributes in a Relation May Specify Which Attribute Are Keys and Which Cannot Be Null Create a New Empty Table May Define DELETION Effect by Cascade/Restricted CREATE TABLE Supplier_Parts ( S# CHAR(5) NOT NULL, P# CHAR(6) NOT NULL, QTY INTEGER, PRIMARY KEY (S# P#) FOREIGN KEY S# REFERENCE SUPPLIER ON DELETE CASCADE, REFERENCE PART ON DELETE RESTRICT);

28 SQL Data Definition Drop Table A Relation Can Be Dropped at Any Time
Drop Will Delete Both Definition and Data All Views, Indexes, and FKs are Dropped DROP TABLE SUPPLIER; Alter Table Add New Attributes or PK and FK to the Table All Existing Records are Expanded With Nulls, but Not Physically Changed. ALTER TABLE SUPPLIER ADD DISCOUNT SMALLINT;

29 DDL - Drop Tables Command: DROP TABLE EMPLOYEE RESTRICT;
DROP TABLE DEPARTMENT CASCADE; Restrict: Drop Operation fails if the Table is Referenced by View and/or Constraint Definitions Cascade: Drop Operation Removes Referencing View and Constraint Definitions

30 DDL - Change Table Structure
Add a Column to a Table: ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12); No DEFAULT Implies NULL Values for all Tuples Drop a Column from a table ALTER TABLE EMPLOYEE DROP JOB RESTRICT (or CASCADE); Restrict: Drop Operation Fails if Column is Referenced Cascade: Drop Operation Removes Referencing View and Constraint Definitions

31 Chinook sql file

32 Chinook sql file

33 Chinook sql file

34 Chinook sql file

35 Chinook sql file

36 Data Manipulation Language - DML
SQL has the SELECT Statement for Retrieving Info. from a Database (Not Relational Algebra Select) SQL vs. Formal Relational Model SQL Allows a Table (Relation) to have Two or More Identical Tuples in All Their Attribute Values Hence, an SQL Table is a Multi-set (Sometimes Called a Bag) of Tuples; it is Not a Set of Tuples SQL Relations Can Be Constrained to Sets by PRIMARY KEY or UNIQUE Attributes Using the DISTINCT Option in a Query primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

37 Interactive DML - Main Components
Select-from-where Statement Contains: Select Clause - Chosen Attributes/Columns From Clause - Involved Tables Where Clause - Constrain Tuple Values Tuple Variables - Distinguish Among Same Names in Different Tables String Matching - Detailed Matching Including Exact Starts With Near Ordering of Rows - Sorting Tuple Results

38 Interactive DML - Main Components
Select-from-where Statement Contains: Set Operations - Search to See if a Value is in Set Built-in Functions - Count, Mix, Max, Sum, Avg Nested Subqueries - Queries within Queries Joins - As Discussed for Relational Algebra Recursive Queries (Defer - Part of SQL3) Modification-Based Selects for Insert - Create a New Tuple Delete - Remove Existing Tuple(s) Update - Change Existing Tuple(s)

39 SQL Data Manipulation target-listconditionrelation-list
Skeleton Query: SELECT target-list FROM relation-list WHERE condition or subquery GROUP BY attribute-list HAVING condition ORDER BY attribute-list SELECT - relational “project” WHERE - relational “select” and/or “join” In principle, a SQL query equals to an algebra expression target-listconditionrelation-list

40 Simple Select-From-Where
Format: Equivalent Algebra Statement: SELECT Specifies the Columns of the Query Result FROM Specifies the Tables to Be Used in the Query WHERE Specifies the Query Condition Restriction: Must Refer to Columns of the Tables in the FROM Clause SELECT A1, A2, ... An FROM R1 , R2 , ... Rm WHERE Predicate (Boolean/Set Expression) p A 1 , 2 , ... n ( s P R  R m ))  ... 

41 Recall Prior Schema

42 …and Corresponding DB Tables
Which Represent Tuples/Instances of Each Relation A S C null W B 1 4 5

43 …and Corresponding DB Tables

44 Simple SQL Queries Query 0: Retrieve the Birthdate and Address of the Employee whose Name is 'John B. Smith'. SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’ Which Row(s) are Selected? Note: While All of these Next Queries are from Chapter 4, Some are From “Earlier” Edition B S C null W

45 Simple SQL Queries Query 1: Retrieve Name and Address of all Employees who work for the 'Research' Department SELECT FNAME, MINIT, LNAME, ADDRESS, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO What Action is Being Performed?

46 Simple SQL Queries - Result
Theta Join on DNO=DNUMBER

47 Simple SQL Queries – Fully Qualified
The Full Table Name with “.” Notation Differentiates Among the Attributes Query 1: Retrieve Name and Address of all Employees who work for the 'Research' Department SELECT EMPLOYEE.FNAME, EMPLOYEE.MINIT, EMPLOYEE. LNAME,EMPLOYEE.ADDRESS, DEPARTMENT.DNAME FROM EMPLOYEE, DEPARTMENT WHERE DEPARTMENT.DNAME='Research' AND DEPARTMENT.DNUMBER= EMPLOYEE.DNO

48 Simple SQL Queries Query 2: For Every Project in 'Stafford', list the Project Number, the Controlling Dept. Number, and the Dept. Manager's Last Name, Address, and Birthdate SELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford' In Q2, there are Two Join Conditions: The Join Condition DNUM=DNUMBER Relates a Project to its Controlling Department The Join Condition MGRSSN=SSN Relates the Controlling Department to the Employee who Manages that Department

49 Query Results SELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford' A S C null W B

50 Qualification of Attributes
In SQL, the Same Name for Two (or More) Attributes is Allowed if Attributes are in Different Relations In Those Cases, Query Must Qualify by Prefixing the Relation Name to the Attribute Name EMPLOYEE.LNAME, DEPARTMENT.DNAME Aliases: When Queries Must Refer to the Same Relation Twice Alias is Akin to a Variable in a PL - Reference In These Situations, it is Considered that there are Two Different Copies of the Same Relation Let’s See Examples of Both Concepts

51 Attribute Qualification
Query 8: For Each Employee, Retrieve the Employee's Name, and Name of his or her Immediate Supervisor SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S WHERE E.SUPERSSN=S.SSN E and S are aliases for the EMPLOYEE relation E Represents Employees in the Role of Supervisees S Represents Employees in the Role of Supervisor Another Form of Query 8 is: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN

52 Query Results – Refer to Same Table Twice
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN A S C null W B

53 Conceptually There are two Separate Tables
System Goes Through Every Row of Top Against Every Row of Bottom This is Conceptual In Reality – Only 1 Table Exists EMPLOYEE AS E A S C null W B EMPLOYEE AS S A S C null W B

54 Unspecified WHERE Clause
A Missing Where-clause Indicates No Condition; All Tuples of Relations in From-clause Are Selected Query 9: Retrieve the SSN Values for All Employees SELECT SSN FROM EMPLOYEE

55 Unspecified WHERE Clause
More Than One Relation and No Join Condition Results in the CARTESIAN PRODUCT of Tuples Query 10: SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT Overlooking Selection and Join Conditions in the Where-Clause Likely Yields Incorrect and Very Large Relations May Result – What Happens with these?

56 How Many Tuples are Generated?
Every Row of Employee table is matched with Every Row of the Department table 8 times 3 – means 24 Rows Most are useless….

57 Use of * and Distinct When a * is Used, All of the Attributes are Chosen Q1C: SELECT * FROM EMPLOYEE WHERE DNO=5

58 Use of * and Distinct When a * is Used, All of the Attributes are Chosen Q1D: SELECT * FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNO=DNUMBER

59 Use of * and Distinct SQL Does Not Support Sets so Duplicates are Retrieved Q11: SELECT SALARY FROM EMPLOYEE Q11A: SELECT DISTINCT SALARY FROM EMPLOYEE

60 SELECT * in MySQL WorkBench

61 SELECT * in MySQL WorkBench

62 Set Operations - Union/Intersection/Minus
Not all DBMS Support Intersection/Minus Union: The two Relations must have Same Attributes and the Attributes must Appear in the Same Order Query 4: All Project Numbers for Projects with Employee 'Smith' as a Worker or as a Manager (SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

63 Set Operations - Union/Intersection/Minus
(SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

64 Set Operations - Union/Intersection/Minus
Utilizing the DISTINCT KEYWORD Query 4: Make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project. (SELECT DISTINCT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT DISTINCT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

65 Substring Comparison in SQL Queries
In Regard to Strings, Most DBMSs Support SQL Queries for Exact, Near, and Starts with Matching LIKE is Used to Compare Partial Strings '%' (or '*') Replaces an Arbitrary # of characters '_' replaces a single arbitrary character Query 12: Retrieve all Employees whose Address is in Houston, Texas. SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX% ' Houston, TX can be anywhere within the ADDRESS VAR CHAR String

66 Substring Comparison in SQL Queries
The LIKE Operator Allows us to get Around the Fact that each Value is Considered Atomic and Indivisible SQL: Character String Attribute values are not Atomic Query 12A: Retrieve all employees who were born during the 1950s. SELECT FNAME, LNAME FROM EMPLOYEE WHERE BDATE LIKE ' __5_______' There are two “_” before 5 and seven “_” after 5 Underscores are “blanks”

67 Arithmetic Operations in SQL Queries
Standard Arithmetic Operators '+', '-'. '*', and '/' can be Applied to Numeric Values in an SQL Query Result Query 13: Show the Effect of Giving all Employees who work on the 'ProductX' project a 10% raise. SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' This Doesn’t Change the Table – just Output!

68 ORDER BY Clause in SQL Queries
ORDER BY used to Sort the Tuples in a Query Result based on the Values of one or More Attribute(s) Query 15: Retrieve a list of Employees and the Projects each works in, ordered by Dept., and within each Dept., alphabetically by Employee last name SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BY DNAME, LNAME Default is Ascending - Can be ASC/DESC as we’ll see in a Later Example in Chapter 5

69 Natural Join Queries Specially Tells SQL that a Natural Join is Defined Between Tables SELECT * FROM COUNTRIES NATURAL JOIN CITIES SELECT * FROM COUNTRIES JOIN CITIES USING (COUNTRY, COUNTRY_ISO_CODE) Note that * Expands the JOIN in 1st Query to: All the common columns Every column in the first (left) table that is not a common column Every column in the second (right) table that is not a common column Natural Join in the FROM LIST

70 Homework 3 from Spr 2015 Problem 6.18 from the 6th edition done in SQL and NOT relational expressions

71 Problem 6.18 in 6th edition How many copies of the book titled The Lost Tribe are owned by the library branch whose name is ‘Sharpstown’? SELECT NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' AND BranchName='Sharpstown’ BaB= (BOOKCOPIES *(Title=‘The Lost Tribe’ (BOOK))) ) BookId Ans = No_Of_Copies( (BranchName=‘Sharpstown’ (LIBRARY-BRANCH)) * BaB) BranchID

72 Problem 6.18 in 6th edition BranchId
b. How many copies of the book titled The Lost Tribe are owned by each library branch? SELECT BranchName, NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' CaB = BOOKCOPIES * LIBRARY_BRANCH) BranchId Ans = BranchName, No_Of_Copies( (Title=‘The Lost Tribe’ (BOOK)) * CaB) BookId

73 Homework 3 from Spr 2015 Problem 4.10 in 6th edition

74 Problem 4.10 in 6th edition

75 Problem 4.10 in 6th edition (a) Retrieve the names of employees in department 5 who work more than 10 hours per week on the 'ProductX' project. SELECT LNAME, FNAME FROM EMPLOYEE, WORKS_ON, PROJECT WHERE DNO=5 AND SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' AND HOURS>10 Result: LNAME FNAME Smith John English Joyce

76 Problem 4.10 in 6th edition Result (empty):
(b) List the names of employees who have a dependent with the same first name as themselves. SELECT LNAME, FNAME FROM EMPLOYEE, DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME Result (empty):

77 Problem 4.10 in 6th edition (c) Find the names of employees that are
directly supervised by 'Franklin Wong'. SELECT E.LNAME, E.FNAME FROM EMPLOYEE E, EMPLOYEE S WHERE S.FNAME='Franklin' AND S.LNAME='Wong' AND E.SUPERSSN=S.SSN Result: LNAME FNAME Smith John Narayan Ramesh English Joyce

78 Problem 4.10 in 6th edition Result: AVG(SALARY) 31000
(h) Retrieve the average salary of all female employees. SELECT AVG (SALARY) FROM EMPLOYEE WHERE SEX='F’ Result: AVG(SALARY) 31000

79 Other SQL Queries Hmwk 4 Spring 2015
Problem 3.4 for the Northwind Database Schema Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. Count and print the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. For each country (ShipCountry in Orders), total the Freight charges. The countries are: France, Germany, Brazil, Belgium, Switzerland, Venezuela, Austria, Mexico, USA, Sweden, Finland, Italy, Spain, UK, Ireland, Portugal, Canada, Denmark, Poland, Norway, Argentina

80 Explaining Northwind Schema
Suppliers: A Suppliers Contact Info and web link. Products: Names, suppliers, and Prices Categories: Categories of Northwind products such as Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood Orders: For each Customer with dates &Shipping Order Details: Products, quantities, and price. Employees: Typical Info. Customers: Typical Info. Shippers: Typical Info.

81 Northwind Schema

82 Northwind Schema – Key Types

83 Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. SELECT DISTINCT suppliers.CompanyName, suppliers.Address FROM northwind.suppliers, northwind.categories, northwind.products WHERE suppliers.SupplierID = products.SupplierID AND categories.CategoryID = products.CategoryID AND categories.CategoryName = 'Seafood';

84 Count/the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. SELECT categories.CategoryName, COUNT(suppliers.SupplierID) FROM northwind.categories, northwind.products, northwind.suppliers WHERE suppliers.SupplierID = products.SupplierID AND products.categoryID = categories.CategoryID GROUP BY categories.CategoryName;

85 For each country (ShipCountry in Orders), total the Freight charges.
SELECT orders.ShipCountry, SUM(orders.Freight) FROM northwind.orders GROUP BY orders.ShipCountry;

86 Other SQL Queries Hmwk 2 Fall 2015
Problem 3.4 for the Northwind Database Schema Find the list of all customers from United Kingdom sorted by Company Name in ascending order and return the company Name and Country. Find the number of customers that are located in each country. Find the Product Name, UnitPrice, and UnitsInStock and Sorted by ProductName for all products where the product name starts with “Ch”.

87 Find list of all customers from United Kingdom
SELECT northwind.suppliers.CompanyName, northwind.suppliers.country FROM northwind.suppliers WHERE northwind.suppliers.Country="UK" ORDER BY northwind.suppliers.CompanyName ASC Exotic Liquids UK Specialty Biscuits, Ltd.

88 Find number of customers in each country.
Argentina 3 Austria 2 Belgium Brazil 9 Canada Denmark Finland France 11 Germany Ireland 1 Italy Mexico 5 Norway Poland Portugal Spain Sweden Switzerland UK 7 USA 13 Venezuela 4 SELECT northwind.customers.country, COUNT(*) FROM northwind.customers WHERE northwind.customers.country IS NOT NULL GROUP BY northwind.customers.country

89 Find the Product Name …starts with “Ch”.
SELECT northwind.products.productid, northwind.products.productname, northwind.products.UnitsinStock FROM northwind.products WHERE northwind.products.productname LIKE 'CH%'; 1 Chai 39 2 Chang 17 Chartreuse verte 69 4 Chef Anton's Cajun Seasoning 53 5 Chef Anton's Gumbo Mix 48 Chocolade 15

90 INSERT SQL Queries Add one or more Tuples to a Relation, with Attribute values Listed in the order specified in the CREATE Update 1: INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', ' ', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M', ,' ', 4 ) Another Form of Update 1: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN) VALUES ('Richard','K','Marini') All PK and FK Values must be Provided Nulls are Allowed DDL Constraints are Enforced

91 INSERT SQL Queries More Sophisticated Insert can Involve Query
Update 3A: CREATE TABLE DEPTS_INFO (DEPT_NAME VARCHAR(10), NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER); Update 3B: INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME ;

92 Program Level INSERTS Mass Import into DB Consider Chinook_MySql.sql

93 Program Level INSERTS Importing Excel Directly into MySQL
Many Available Tools Importing an XML File directly into MySQL LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL; Tools such as: Likewise – Ability to EXPORT as well SQL Data Export and Import Wizard For MySQL See:

94 DELETE SQL Queries Sample Deletes Include
DELETE FROM EMPLOYEE WHERE LNAME='Brown' DELETE FROM EMPLOYEE WHERE SSN=' ’ DELETE FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') DELETE FROM EMPLOYEE No. of Tuples Deleted Dependent on WHERE Clause Referential Integrity is Enforced During DELETE

95 UPDATE SQL Queries Used to Modify Attribute Values of One or More Selected Tuples A Where-clause Selects the Tuples to Be Modified An Additional Set-Clause Specifies the Attributes to Be Modified and Their New Values Each Command Modifies Tuples in the Same Relation Referential Integrity Must Be Enforced UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10

96 UPDATE SQL Queries Give all Employees in the 'Research' Dept. a 10% raise UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') Modified SALARY Value Depends on the Original SALARY Value in each Tuple SALARY = SALARY *1.1 - Use PL Interpretation

97 Concluding Remarks What have we Seen in Chapter 4?
Complete Data Definition in SQL Creating Schema Creating/Dropping Tables FKs and PKs Basic Data Manipulation in SQL Different Selects Aggregate Functions Insert, Update, and Delete Strongly Encouraged to Engage in Practice with your DBMS of Choice for your Project

98 Jump to Homework 2 in cse4701ann.pptx


Download ppt "Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr."

Similar presentations


Ads by Google