Top Banner
ISOM MIS710 Module 2 Query Languages – RA/RC and SQL Arijit Sengupta
54

ISOM MIS710 Module 2 Query Languages – RA/RC and SQL Arijit Sengupta.

Dec 26, 2015

Download

Documents

Nora Glenn
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Slide 1
  • ISOM MIS710 Module 2 Query Languages RA/RC and SQL Arijit Sengupta
  • Slide 2
  • ISOM Structure of this semester Database Fundamentals Relational Model Normalization Conceptual Modeling Query Languages Advanced SQL Transaction Management Java DB Applications JDBC Data Mining 0. Intro 1. Design 3. Applications 4. Advanced Topics NewbieUsersProfessionalsDesigners MIS710 2. Querying Developers
  • Slide 3
  • ISOM Todays Buzzwords Query Languages Formal Query Languages Procedural and Declarative Languages Relational Algebra Relational Calculus SQL Aggregate Functions Nested Queries
  • Slide 4
  • ISOM Objectives At the end of the lecture, you should Get a formal as well as practical perspective on query languages Have a background on query language basics (how they came about) Be able to write simple SQL queries from the specification Be able to look at SQL queries and understand what it is supposed to do Be able to write complex SQL queries involving nesting Execute queries on a database system
  • Slide 5
  • ISOM Set Theory Basics A set: a collection of distinct items with no particular order Set description: { b | b is a Database Book} {c | c is a city with a population of over a million} {x | 1 < x < 10 and x is a natural number} Most basic set operation: Membership: x S (read as x belongs to S if x is in the set S) 3.7 who have taken a CIS Course TRC: DRC:">
  • ISOM Find students with GPA > 3.7 who have taken a CIS Course TRC: DRC:
  • Slide 24
  • ISOM Find students who have taken all CIS courses DRC: TRC: How will you do this with Relational Algebra?
  • Slide 25
  • ISOM Monotonic and Non-Monotonic Queries Monotonic queries: queries for which the size of the results either increase or stay the same as the size of the inputs increase. The result size never decreases Non-monotonic queries: queries for which it is possible that the size of the result will DECREASE when the size of the input increases Examples of each? Which of the algebra operations is non-monotonic? What does this signify?
  • Slide 26
  • ISOM Structured Query Language Need for SQL Operations on Data Types Definition Manipulation Operations on Sets Declarative (calculus) vs. Procedural (algebra) Evolution of SQL SEQUEL..SQL_92.. SQL_93 SQL Dialects Does SQL treat Relations as Sets?
  • Slide 27
  • ISOM Horizontal Slices Restriction Specifying Conditions Unconditional List all students select* fromSTUDENT; (Student) Conditional List all students with GPA > 3.0 select* fromSTUDENT whereGPA > 3.0; GPA > 3.0 (Student) Algebra: selection or restriction (R)
  • Slide 28
  • ISOM Pattern Matching %any string with n characters, n>=0 _any single character. x exact sequence of string x. List all CIS 3200 level courses. select* fromCOURSE wherecourse# like ? ; List all CIS courses. select* fromCOURSE wherecourse# like CIS%;
  • Slide 29
  • ISOM Specifying Conditions List all students in... select* fromSTUDENT wherecity in (Boston,Atlanta); List all students in... select* fromSTUDENT wherezip not between 60115 and 60123;
  • Slide 30
  • ISOM Missing or Incomplete Information List all students whose address or telephone number is missing: select* fromSTUDENT whereAddress is null or GPA is null;
  • Slide 31
  • ISOM Vertical Slices Projection Specifying Elements No Specification List all information about Students select* fromSTUDENT; (Student) Conditional List IDs, names, and addresses of all students select StudentID, name, address from STUDENT; StudentID, name, address (Student) Algebra: projection (R)
  • Slide 32
  • ISOM Does SQL treat Relations as Sets? What are the different salaries we pay to our employees? selectsalary fromEMPLOYEE; OR is the following better? selectDISTINCT salary fromEMPLOYEE;
  • Slide 33
  • ISOM Horizontal and Vertical Query: List all student ID, names and addresses who have GPA > 3.0 and date of birth before Jan 1, 1980. selectStudentID, Name, Address fromSTUDENT whereGPA > 3.0 and DOB < 1-Jan-80 order byName DESC; Algebra: StudentID,name, address ( GPA > 3.0 and DOB < 1-Jan-80 (STUDENT)) Calculus: {t.StudentID, t.name, t.address | t Student t.GPA > 3.0 t.DOB < 1-Jan-80} Order by sorts result in descending (DESC) order. Note: The default order is ascending (ASC) as in: order by Name;
  • Slide 34
  • ISOM Summaries and Aggregates Calculate the average GPA selectavg. (GPA) from STUDENT, Find the lowest GPAselectmin (GPA) as minGPA from STUDENT, How many CIS majors?selectcount (StudentId) fromSTUDENT wheremajor=CIS; Discarding duplicatesselectavg (distinct GPA) STUDENT where major=CIS (is this above query correct?)
  • Slide 35
  • ISOM Aggregate Functions COUNT (attr)- a simple count of values in attr SUM (attr)- sum of values in attr AVG (attr)- average of values in attr MAX (attr)- maximum value in attr MIN (attr)- minimum value in attr Take effect after all the data is retrieved from the database Applied to either the entire resulting relation or groups Cant be involved in any query qualifications (where clause) n Would the following query be permitted? selectStudentId fromSTUDENT whereGPA = max (GPA);
  • Slide 36
  • ISOM Grouping Results Obtained n Show all students enrolled in each course. selectcno, StudentID fromREGISTRATION group by cno;Is this grouping OK? n Calculate the average GPA of students by county. selectcounty, avg (GPA) as CountyGPA fromSTUDENT group by county; n Calculate the enrollment of each class. selectcno, year, term, count (StudentID) as enroll fromREGISTRATION group by cno, year, term;
  • Slide 37
  • ISOM Selections on Groups n Show all CIS courses that are full. selectcno, count (StudentID) fromREGISTRATION group by cno havingcount (StudentID) > 29;
  • Slide 38
  • ISOM Union n List students who live in Atlanta or GPA > 3.0 selectStudentID, Name, DOB, Address fromSTUDENT where Address = Atlanta union selectStudentID, Name, DOB, Address fromSTUDENT where GPA > 3.0; Can we perform a Union on any two Relations ?
  • Slide 39
  • ISOM Union Compatibility n Two relations, A and B, are union-compatible if A and B contain a same number of attributes, and The corresponding attributes of the two have the same domains Examples CIS=Student (ID: D id ; Name: D name ; Address: D addr ; Grade: D grade ); Senior-Student (SName: D name ; S#: D id ; Home: D addr ; Grade: D grade ); Course (C#: D number ; Title: D str ; Credits: D number ) Are CIS-Student and Senior-Student union compatible? Are CIS-Student and Course union compatible? What happens if we have duplicate tuples? What will be the column names in the resulting Relation?
  • Slide 40
  • ISOM Union, Intersect, Minus selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA UNION selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA UNION selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA INTERSECT selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA INTERSECT selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA MINUS selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; selectCUSTNAME, ZIP fromCUSTOMER where STATE = MA MINUS selectSUPNAME, ZIP fromSUPPLIER whereSTATE = MA ORDER BY 2; B A B A B AA
  • Slide 41
  • ISOM Connecting/Linking Relations List information about all students and the classes they are taking What can we use to connect/link Relations? Join: Connecting relations so that relevant tuples can be retrieved. Student Class
  • Slide 42
  • ISOM Join Cartesian Product Student: 30 tuplesClass: 4 tuples Total Number of Tuples in the Cartesian Product. ? (match each tuple of student to every tuple of class) Select tuples having identical Student Ids. Expected number of such Tuples: Join Selectivity R1R2
  • Slide 43
  • ISOM Join Forms General Join Forms Equijoin Operator Dependent Natural Join Outer Join Left Right Full selects.*, c.* fromSTUDENT s, CLASS c wheres.StudentID = c.SID (+); selects.*, c.* fromSTUDENT s, CLASS c wheres.StudentID = c. SID; = x > y ... R1R2 R1R2
  • Slide 44
  • ISOM Grouping Results after Join n Calculate the average GPA of each class selectcourse#, avg (GPA) fromSTUDENT S, CLASS C whereS.StudentID = C.SID group by course#,
  • Slide 45
  • ISOM Nesting Queries SELECTattribute(s) FROMrelation(S) WHEREattr [not] {in | comparison operator | exists } ( query statement(s) ); List names of students who are taking BA201 select Name from Student whereStudentID in ( selectStudentID fromREGISTRATION where course#=BA201);
  • Slide 46
  • ISOM Sub Queries List all students enrolled in CIS courses selectname fromSTUDENT where StudentId in (selectStudentId fromREGISTRATION wherecno like CIS%); List all students enrolled in CIS courses selectname fromSTUDENT where StudentId in (selectStudentId fromREGISTRATION wherecno like CIS%); List all courses taken by Student (Id 1011) selectcname fromCOURSE wherecnum = any (selectcno fromREGISTRATION whereStudentId = 1011);
  • Slide 47
  • ISOM Sub Queries Who received the highest grade in CIS 8140 selectStudentId fromREGISTRATION wherecnum = CIS 8140 and grade >=all (selectgrade fromREGISTRATION wherecno = CIS 8140); Who received the highest grade in CIS 8140 selectStudentId fromREGISTRATION wherecnum = CIS 8140 and grade >=all (selectgrade fromREGISTRATION wherecno = CIS 8140); List all students enrolled in CIS courses. selectname fromSTUDENT S whereexists (select* fromREGISTRATION whereStudentId = S.StudentId and cno like CIS%);
  • Slide 48
  • ISOM Relational Views Relations derived from other relations. Views have no stored tuples. Are useful to provide multiple user views. View 1View 2View N Base Relation 1 Base Relation 2 What level in the three layer model do views belong? Which kind of independence do they support?
  • Slide 49
  • ISOM View Creation Create View view-name [ ( attr [, attr ]...) ] AS subquery [ with check option ] ; DROP VIEW view-name; Create a view containing the student ID, Name, Age and GPA for those who are qualified to take 300 level courses, i.e., GPA >=2.0.
  • Slide 50
  • ISOM View Options With Check Option enforces the query condition for insertion or update To enforce the GPA >=2.0 condition on all new student tuples inserted into the view A view may be derived from multiple base relations Create a view that includes student IDs, student names and their instructors names for all CIS 300 students.
  • Slide 51
  • ISOM View Retrieval Queries on views are the same as that on base relations. Queries on views are expanded into queries on their base relations. selectName, Instructor-Name fromCIS300-Student whereName = Instructor-Name;
  • Slide 52
  • ISOM View: Update Update on a view actually changes its base relation(s)! update Qualified-Student setGPA = GPA-0.1 whereStudentID = s3; insert intoQualified-Student values( s9, Lisa, 4.0 ) insert intoQualified-Student values( s10, Peter, 1.7 ) Why are some views not updateable? What type of views are updateable?
  • Slide 53
  • ISOM Non-monotonic queries again! Need to use either MINUS or NOT EXISTS! Find courses where no student has gpa over 3.5 Find students who have taken all courses that Joe has taken How would you solve these?
  • Slide 54
  • ISOM Summary SQL is a low-complexity, declarative query language The good thing about being declarative is that internally the query can be changed automatically for optimization Good thing about being low-complexity? No SQL query ever goes into an infinite loop No SQL query will ever take indefinite amount of space to get the solution Can be used for highly complex problems!