SQL: Interactive Queries (1) John Ortiz Lecture 11SQL: Interactive Queries (1)2 Basic Select Statement  Basic form of the select statement: select target-attribute-list.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 1 R &G - Chapter 5 Life is just a bowl of queries. -Anon (not Forrest Gump)
Advertisements

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
 Database is SQL1.mdb ◦ import using MySQL Migration Toolkit 
Relational Algebra Ch. 7.4 – 7.6 John Ortiz. Lecture 4Relational Algebra2 Relational Query Languages  Query languages: allow manipulation and retrieval.
1 Lecture 11: Basic SQL, Integrity constraints
CS 405G: Introduction to Database Systems
CREATE VIEW SYNTAX CREATE VIEW name [(view_col [, view_col …])] AS [WITH CHECK OPTION];
 CS 405G: Introduction to Database Systems Lecture 7: Relational Algebra II Instructor: Chen Qian Spring 2014.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 Chapter 5 SQL: QUERIES, CONSTRAINTS, TRIGGERS. 2 INTRODUCTION - The current presentation is consistent with both SQL-92 and SQL: 99 (differences will.
Chapter 11.1 and 11.2 Data Manipulation: Relational Algebra and SQL Brian Cobarrubia Introduction to Database Management Systems October 4, 2007.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts - 6 th Edition SQL Schema Changes and table updates instructor teaches.
INFS614 - Lecture week 9 1 More on SQL Lecture Week 9 INFS 614, Fall 2008.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Lecture 2 of Advanced Databases Advanced SQL Instructor: Mr.Ahmed Al Astal.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
ITBIS373 Database Development
Database Management COP4540, SCS, FIU SQL (Continued) Querying Multiple Tables.
A Guide to MySQL 5. 2 Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
1 CSE 480: Database Systems Lecture 11: SQL. 2 SQL Query SELECT FROM WHERE –In MySQL, FROM and WHERE clauses are optional –Example:
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester
Chapter 11 – Data Manipulation: Relational Algebra and SQL1 Unit 7: Data Manipulation: Relational Algebra and SQL IT238: Data Modeling and Database Design.
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
Copyright Curt Hill SQL Queries Yet Another Set of Query Features.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly.
ICS 321 Fall 2009 SQL: Queries, Constraints, Triggers Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 9/8/20091Lipyeow.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
I NTRODUCTION TO SQL II. T ABLE JOINS A simple SQL select statement is one that selects one or more columns from any single table There are two types.
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 4 Relational Algebra.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Chapter 3: Introduction to SQL
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
CMPT 258 Database Systems SQL Queries (Chapter 5).
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 The Relational Algebra and Relational Calculus.
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 4 © Akhilesh Bajaj, 2000, 2002, 2004, All.
CS 405G: Introduction to Database Systems SQL III.
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
1 CSE 480: Database Systems Lecture 16: Relational Algebra.
1 Schema for Student Registration System Student Student (Id, Name, Addr, Status) Professor Professor (Id, Name, DeptId) Course Course (DeptId, CrsCode,
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2007.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries.
Subqueries CIS 4301 Lecture Notes Lecture /23/2006.
Chapter (6) The Relational Algebra and Relational Calculus Objectives
Relational Algebra Database Management Systems, 3rd ed., Ramakrishnan and Gehrke, Chapter 4.
Chapter 3 Introduction to SQL
Basic SQL Queries Go over example queries, like 10 > ALL.
Introduction to SQL.
SQL The Query Language R & G - Chapter 5
SQL: Structured Query Language DML- Queries Lecturer: Dr Pavle Mogin
Basic SQL Lecture 6 Fall
CS 405G: Introduction to Database Systems
CS 405G: Introduction to Database Systems
SQL: The Query Language Part 1
CMPT 354: Database System I
Chapter 2: Intro to Relational Model
Geo-Databases: lecture 4 Complex Queries in SQL
Presentation transcript:

SQL: Interactive Queries (1) John Ortiz

Lecture 11SQL: Interactive Queries (1)2 Basic Select Statement  Basic form of the select statement: select target-attribute-list from table-list where conditions;  Correspondence to relational algebra: select-clause  projection (  ) from-clause  Cartesian product (  ) where-clause  selection (  )

Lecture 11SQL: Interactive Queries (1)3 A Sample University Schema  Students(SID, Name, Age, Sex, Major, GPA)  Courses(Cno, Title, Hours, Dept)  Enrollment(SID, Cno, Year, Grade)  Offers(Cno, Year, FID)  Faculty(FID, Name, Rank, Dept, Salary)  Departments(Name, Location, ChairID)  Assume a natural choice of data types and foreign key constraints.

Lecture 11SQL: Interactive Queries (1)4 Single Table Queries  Find SID, Name and GPA of students with GPA higher than 3.8. SQL> select SID, Name, GPA 2 from Students 3 where GPA > 3.8;  Use shorthand * to select all columns. select * from Students where GPA > 3.8;  The where-clause is optional. select Name from Students;

Lecture 11SQL: Interactive Queries (1)5 Duplicate Removal  By default, duplicate rows are kept (why?).  How to remove duplicate rows?  Use key word distinct. select distinct SID, Cno from Enrollment;  Other means (set operations, key attri.) What is the problem with following query? select distinct SID, Name from Students;

Lecture 11SQL: Interactive Queries (1)6 A Multiple Table Query Find id of faculty members who taught Database I in 1998 select FID from Offers, Courses where Title = ‘Database I’ and Year = 1998 and Offers.Cno = Courses.Cno; Offers Courses

Lecture 11SQL: Interactive Queries (1)7 Conceptual Evaluation  Previous query can be understood through a conceptual evaluation of the query. 1.Find cross product of Courses & Sections. 2.Select rows satisfying where-clause 3.Project on FID, keeping duplicate rows. Offers  Courses Found! Answer

Lecture 11SQL: Interactive Queries (1)8 Conceptual Evaluation (cont.) In general, select distinct Ri.A, Rj.B,..., Rk.C from R1, R2,..., Rn where Conditions is interpreted by (up to duplicate elimination)  Ri.A, Rj.B,..., Rk.C (  Conditions (R1  R2 ...  Rn))

Lecture 11SQL: Interactive Queries (1)9 Tuple Variables  Tuple Variables (Relation Aliases) can simplify query specifications.  Find names and GPAs of students who take Database I. select Name, GPA from Students S, Enrollment E, Courses C where Title = ‘Database I’ and S.SID = E.SID and E.Cno = C.Cno;

Lecture 11SQL: Interactive Queries (1)10 When Are Aliases Necessary?  Find pairs of students who have same GPA. select s1.SID, s2.SID from Students s1, Students s2 where s1.GPA = s2.GPA and s1.SID < s2.SID  Why use “s1.SSN < s2.SSN”?  Find names of students with GPA higher than Tom's. select s1.Name from Students s1, Students s2 where s2.Name = `Tom' and s1.GPA > s2.GPA  Compare to all Tom’s or any one Tom?

Lecture 11SQL: Interactive Queries (1)11 String Matching Operators  Find numbers and titles of courses that have “systems” in the title. select Cno, Title from Courses where Title like `%systems%'  % matches 0 or more characters.  Find students with a six-letter name starting with an ‘M’. select * from Students where Name like `M_ _ _ _ _'  _ matches exactly one character

Lecture 11SQL: Interactive Queries (1)12 More Operators *  Find students whose name contain a _. select * from Students where Name like `%\_ %’ escape ‘\’  Escape character can be explicitly defined.  Operator for range conditions: Find names of students with GPA between 3.5 and 3.8. select Name from Students where GPA between 3.5 and 3.8;

Lecture 11SQL: Interactive Queries (1)13 Set Operations  SQL supports three set operations: union, intersect, except (Oracle uses minus)  Requires union compatibility. Recall that  they have same number of attributes;  corresponding attributes have same type.  Applied on (relations specified by) subqueries.  Set operations automatically removes duplicate rows. To keep duplicate in union, use union all.

Lecture 11SQL: Interactive Queries (1)14 Examples Using Set Operations  Find SID of students who either take Database I or major in CS. (select SID from Enrollment E, Courses C where E.Cno = C.Cno and Title = ‘Database I’) union (select SID from Students where Major = ‘CS’)  What do we get if use intersect or except?

Lecture 11SQL: Interactive Queries (1)15 Testing Set Membership *  Find students who are 20, 22, or 24 years old. select * from Students where Age in (20, 22, 24)

Lecture 11SQL: Interactive Queries (1)16 Nested (Sub)Query  Find names of students who take at least one course offered by CS department. (select Cno from Courses where Dept = 'CS') select Name from Students S, Enrollment E where S.SID = E.SID and E.Cno in Outer query Inner query

Lecture 11SQL: Interactive Queries (1)17 Correlated Nested Query  List SID and Cno pairs for which the student takes the course and has the same name as the instructor. correlation select SID, Cno from Students S, Enrollment E where S.SID = E.SID and (Cno, Year) in (select Cno, Year from Offers O, Faculty F where O.FID=F.FID and Name = S.Name)

Lecture 11SQL: Interactive Queries (1)18 Conceptual Evaluation 1.Compute cross product of outer relations. 2.For each tuple in the cross product that satisfy other conditions in outer query, compute the result of the inner query.  Non-correlated inner query only needs to be computed once.  In subqueries, “local” names take precedence over “global” names. 3.Evaluate the rest of conditions of the outer query and form the final result.

Lecture 11SQL: Interactive Queries (1)19 Flatten Nested Queries  Every nested query has equivalent flat queries.  The last query is equivalent to the following. select SID, Cno from Students S, Enrollment E, Offers O, Faculty F where S.SID = E.SID and E.Cno = O.Cno and E.Year = O.Year and O.FID=F.FID and F.Name = S.Name  Why nested query? Why flatten nested query?

Lecture 11SQL: Interactive Queries (1)20 Another Nested Query  Find enrollments where a 25-year-old student takes a CS course. select * from Enrollment where (SID, Cno) in (select S.SID, C.Cno from Students S, Courses C where S.Age = 25 and C.Dept = 'CS‘)

Lecture 11SQL: Interactive Queries (1)21 Another Nested Query (cont.) Other ways to write the query:  select * from Enrollment where SID in (select SID from Students where Age = 25) and Cno in (select Cno from Courses where Dept = 'CS')  select E.* from Enrollment E, Students S, Courses C where S.SID=E.SID and E.Cno=C.Cno and S.Age = 25 and C.Dept = ‘CS’

Lecture 11SQL: Interactive Queries (1)22 Quantified Comparisons  Find names of students who are 18 or younger with a GPA higher than the GPA of some students who are 25 or older. select Name from Students where Age some (select GPA from Students where Age >= 25)  Also =some, =some, <>some.  Can also use any (same as some). Also have all.

Lecture 11SQL: Interactive Queries (1)23 Meaning of Quantified Comparisons *  =some is equivalent to in  <>all is equivalent to not in.  <>some is equivalent to neither in nor not in Example: Let x = a and S = {a, b}. Then  x <>some S is true (x <> b);  x not in S is false (a is in S);  x <>all S is also false (x = a).

Lecture 11SQL: Interactive Queries (1)24 Quantified Subquery  Find students who take at least one course.  Rephrase: Find students such that there exist some courses taken by the students.  In SQL, use key word exists select * from Students s where exists (select * from Enrollment where SID = s.SID)  What would it mean if use not exists instead?

Lecture 11SQL: Interactive Queries (1)25 Quantified Subquery (cont.) * The previous query is equivalent to: (1) select s.* from Students s, Enrollment e where s.SID = e.SID (2) select * from Students where SID in (select SID from Enrollment)

Lecture 11SQL: Interactive Queries (1)26 Quantifiers: More Examples *  Find students who do not take CS374. select * from Students s where not exists (select * from Enrollment where SID = s.SID and Cno = 'CS374')  This query is equivalent to: select * from Students where SID not in (select SID from Enrollment where Cno = 'CS374')

Lecture 11SQL: Interactive Queries (1)27 Quantifiers: More Examples  Find students who take all CS courses. select * from Students s where not exists (select * from Courses c where Dept = ‘CS’ and not exists (select * from Enrollment where SID = s.SID and Cno = c.Cno))  A student takes all CS courses if and only if no CS course is not taken by the student.  Compare with division in relational algebra.

Lecture 11SQL: Interactive Queries (1)28 Quantifiers: More Examples *  Find name and GPA of students who take every course taken by the student with id select Name, GPA from Students s where not exists (select * from Courses c where Cno in (select Cno from Enrollment where SID = '1234') and not exists (select * from Enrollment where SID = s.SID and Cno = c.Cno))  Can you express it in other ways?

Lecture 11SQL: Interactive Queries (1)29 How Do You Ask This In SQL? *  Find names of faculty who did not teach any course in  Find names of students who only take courses taught by Prof. Goodman.  Find pairs of names of students who take the same course taught by the same faculty member in different years.  Find names of CS students who never take a CS course.  Find titles of courses taken by Bill Smith that are also taken by all students under 40.

Lecture 11SQL: Interactive Queries (1)30 Complex From-Clause  Many ways to specify tables in From-clause.  Find title of courses of a department located in SB (Science Building). select Title from Courses join Departments on Dept = Name where Location = ‘SB‘  Also available: join … using …, natural join, left [outer] join … on …, right join … using…, etc.  Can create tables using queries as well.

Lecture 11SQL: Interactive Queries (1)31 Specify Outerjoin In From  For every student list titles of courses the student took in select Name, Title from Students left join (Enrollment join Courses using Cno) using SID where Year = 1999  Why must an outer join be used?

Lecture 11SQL: Interactive Queries (1)32 Computation in SQL  Arithmetic computations are allowed in select and where clauses.  SQL supports a set of operators and built-in functions.  Operators include +, -, *, /.  Functions include char_length(x), lower(x), upper(x), x || y, substring(x from i to j).  Special functions to handle null values.

Lecture 11SQL: Interactive Queries (1)33 Examples of Computation  Find id, name and monthly salary of faculty (Faculty.Salary is 9-month salary). select FID, upper(Name), Salary/9 Mon-Sal from Faculty  Find names of male CS students and precede each name with the title ‘Mr.’. select ‘Mr.’ || Name from Students where lower(Sex) = ‘m’

Lecture 11SQL: Interactive Queries (1)34 Common Oracle SQL Functions *  ceil(x) : smallest integer >= x  floor(x) : largest integer <= x  mod(m,n) : remainder of m divided by n  power(x,y) : x raised to the power y  round(n,m) : round n to the m-th digit following the point  sign(x) : 0 if x = 0; 1 if x > 0; -1 if x < 0  sqrt(x) : the square root of x  initcap(s) : change the first char of each word in s to uppercase

Lecture 11SQL: Interactive Queries (1)35 Common Oracle SQL Functions *  lower(s) : change all chars in s to lowercase  replace(s,s1,s2) : replace each s1 by s2 in s  substr(s,m,n) : n-char substring of s starting at the m-th char  length(s) : the length of s  sysdate : the current date  last_day : the last day of current month  to_char(x) : convert x to char data type  to_number(x) : convert string x to numbers.  to_date(x) : convert x to date type

Lecture 11SQL: Interactive Queries (1)36 Case  List id and name of students together with a classification of “excellent”, “very good”, etc. select SID, Name, case when GPA < 2.5 then 'fair' when GPA < 3 then 'good' when GPA < 3.5 then 'very good' else 'excellent' end from Students  The output is from the first satisfied case.

Lecture 11SQL: Interactive Queries (1)37 The Decode Function  Assume Students has an attribute Year with possible values 1, 2, 3, & 4.  Find id and name of students together with a status (freshman, sophomore …). select SID, Name, decode(Year, 1, ‘freshman’, 2, ‘sophomore’, 3, ‘junior’, 4, ‘senior’) Status from Students

Lecture 11SQL: Interactive Queries (1)38 Using Null Value  Find names of students who have not declared a major. select Name from Students where Major is null  Any computation involving a null value yields a null value. Use nvl(exp1, exp2) to convert null value in exp1 to exp2. select Name, Salary + nvl(Bonus, 0) Total_wage from Employees  Assume Employees(EID, Name, Salary, Bonus)

Lecture 11SQL: Interactive Queries (1)39 Date Arithmetic in Oracle*  One may add/subtract days to/from a date.  Month and year boundaries will be taken care of automatically. select Name, Birthday + 20 from Students  Returns 12-JAN-96 if a student’s birthday is 23-DEC-95.