SQL: Structured Query Language Instructor: Mohamed Eltabakh 1 Part II.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
CS4432: Database Systems II Query Operator & Algebraic Expressions 1.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
CS 405G: Introduction to Database Systems
1 Today’s Class  Relational Model  SQL CS F212 Database Systems.
E-R Diagram for a Banking Enterprise
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Ordering the Display of Tuples List in alphabetic order the names of all customers having.
Murali Mani SQL: Updates (DML) and Views (DDL). Murali Mani SQL DML (Updating the Data) Insert Delete Update.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
Nov 24, 2003Murali Mani SQL B term 2004: lecture 12.
CS3431 SQL : Query Language. CS3431 SELECT-FROM-WHERE SELECT * FROM Student WHERE sName=“Greg” AND address=“320 FL”  (sName=“Greg” AND address=“320 FL”)
SQL Neyha Amar CS 157A, Fall Inserting The insert statement is used to add a row of data into a table Strings should be enclosed in single quotes,
Murali Mani SQL. Murali Mani SELECT-FROM-WHERE SELECT * FROM Student WHERE sName=“Greg” AND address=“320 FL”  (sName=“Greg” AND address=“320 FL”) (Student)
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
Cs3431 SQL: Updates (DML) and Views (DDL). cs3431 SQL DML (Updating the Data) Insert Delete Update.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
Instructor: Mohamed Eltabakh
Database Systems More SQL Database Design -- More SQL1.
CIS552SQL1 Data Definition Language Insertions Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 3 Single-Table Queries
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE) Datalog.
Lecture 6 Structured Query Language SQL Lecture 6 Structured Query Language SQL Instructor: Haya Sammaneh.
Structured Query Language 2 Presented by: Annisa, M.Kom. Source: Database System Concepts 5 th edition.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Advanced SQL Murat Kantarcioglu Adapted from Silberchatz et al. slides.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE)
NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL.
Yufis Azhar – Teknik Informatika – UMM.  Aggregation function takes a collection of values (of a single attribute) and returns a single value as a result.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Advanced SQL: Triggers & Assertions
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Relational Algebra Instructor: Mohamed Eltabakh 1 Part II.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts Extended Relational-Algebra-Operations Generalized Projection Aggregate Functions Outer Join.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Relational Algebra Instructor: Mohamed Eltabakh 1.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Query Processing – Implementing Set Operations and Joins Chap. 19.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Subqueries CIS 4301 Lecture Notes Lecture /23/2006.
SQL: Structured Query Language Instructor: Mohamed Eltabakh 1.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Structured Query Language
More SQL: Complex Queries,
Slides are reused by the approval of Jeffrey Ullman’s
SQL Structured Query Language 11/9/2018 Introduction to Databases.
SQL : Query Language Part II CS3431.
SQL Views CS542.
SQL : Query Language CS3431.
SQL Views and Updates cs3431.
Instructor: Mohamed Eltabakh
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Access: SQL Participation Project
SQL: Structured Query Language
CS4222 Principles of Database System
SQL: Structured Query Language
SQL: Structured Query Language
SQL: Structured Query Language
SQL: Structured Query Language
SQL: Structured Query Language
Presentation transcript:

SQL: Structured Query Language Instructor: Mohamed Eltabakh 1 Part II

More on SQL SELECT 2

Cartesian Product in SQL SELECT * FROM Student, Professor; In Relation Algebra: R x S In SQL, add R and S to FROM clause No WHERE condition that links R and S SELECT sName, pNumber FROM Student, Professor; 3

Cross Product - Example sNumbersNameaddressprofessor 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddr 1MM141FL 2ER201FL Professor sNumbersNameaddressprofessorpNumberpNameaddr 1Dave320FL11MM141FL 1Dave320FL12ER201FL 2Greg320FL11MM141FL 2Greg320FL12ER201FL 3Matt320FL21MM141FL 3Matt320FL22ER201FL SELECT * FROM Student, Professor; 4

Theta Join in SQL SELECT * FROM Student, Professor WHERE Student.pNum = Professor.Number; In Relation Algebra: R ⋈ C S In SQL, add R and S to FROM clause WHERE condition that links R and S with the join condition C Join condition 5

Theta Join Example sNumbersNamepName 1DaveMM 2GregMM 3MattER sNumbersNameaddressprofNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddress 1MM141FL 2ER201FL Professor  sNumber,sName,pName (Student ⋈ (profNum=pNumber) Professor) SELECT sNumber, sName, pName FROM Student, Professor WHERE profNum = pNumber; 6

Theta Join Example sNumbersNameaddressprofNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddress 1MM141FL 2ER201FL Professor 7 If column names are the same  use relationName.attrName SELECT sName, pName, S.address FROM Student S, Professor P WHERE S.address = P.address;  sName,pName,S.address (ρ S (Student) ⋈ (S.address=P.address) ρ P (Professor))

Natural Join SELECT * FROM Student, Professor WHERE Student.pnumber = Professor.pnumber ; Student ⋈ Professor Reminder: Join columns must have same names in both relations (R ⋈ S) SELECT * FROM Student NATURAL JOIN Professor; Explicitly add the equality join condition 8

Difference between the two Queries below SELECT * FROM Student, Professor WHERE Student.pnumber = Professor.pnumber ; Student ⋈ Professor SELECT * FROM Student NATURAL JOIN Professor; Explicitly add the equality join condition 9 Common columns will appear once Common columns will appear twice

Natural Join - Example sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddr 1MM141FL 2ER201FL Professor sNumbersNameaddresspNumberpNameaddr 1Dave320FL1MM141FL 2Greg320FL1MM141FL 3Matt320FL2ER201FL Student ⋈ Professor 10 Must be the same name SELECT * FROM Student natural join Professor;

Example Queries SELECT * FROM loan WHERE amount > 1200 ; SELECT L.loan_number FROM loan L WHERE L.amount > 1200 ; 11

Example Queries SELECT customer_name FROM depositor Union SELECT customer_name FROM borrower; 12

Example Queries SELECT customer_name FROM borrower B, loan L WHERE B.loan_number = L.loan_number AND L.branch_name = “Perryridge”; DBMS is smart enough !!! (Select first, then joins) 13

Sorting: ORDER BY clause New optional clause that you can add to the SELECT statement called “ORDER BY” Allows sorting the returned records according to one or more fields SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber, sName; SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber ASC, sName DESC; Default is ascending order 14 -Order first based on the pNumber (ascending) -If many records exist with the same pNumber - order them based on sName (descending)

Sorting: ORDER BY clause sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber, sName DESC; sNumbersNameaddresspNumber 2Greg320FL1 1Dave320FL1 3Matt320FL2  (pNumber, sName DESC) (  (sNumber >= 1) (Student)) 15

Duplicate Elimination in SQL New optional keyword “DISTINCT” Added in the SELECT clause SELECT DISTINCT … FROM … … Eliminate any duplicates from the answer 16

Duplicate Elimination: Example SELECT DISTINCT sName, address FROM Student;  (  sName,address (Student))  (  (address) (  (sNumber > 1) (Student))) sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER Student address 320FL SELECT DISTINCT address FROM Student WHERE sNumber > 1; sNameaddress Dave320FL Greg320FL Matt320FL 17

Always Remember…. Only SELECT and FROM clauses are mandatory All the others are optional You can mix and match the optional ones But if you add a clause, then keep it in its order SELECT address FROM Student ORDER BY sNumber WHERE sNumber > 1; X SELECT address FROM Student ORDER BY sNumber; SELECT DISTINCT address FROM Student WHERE sNumber > 1; SELECT address FROM Student WHERE sNumber > 1 ORDER BY sNumber; 18

Aggregation + GroupBy 19

Possible Aggregations in SQL SELECT COUNT (*) FROM Student; SELECT COUNT (sNumber) FROM Student; SELECT MIN (sNumber) FROM Student; SELECT MAX (sNumber) FROM Student; SELECT SUM (sNumber) FROM Student; SELECT AVG (sNumber) FROM Student; 20

Grouping & Aggregation in SQL New optional clause called “GROUP BY” If the SELECT statement has “WHERE” Then WHERE conditions are evaluated first, then records are grouped SELECT pNumber, COUNT (sName), Min(gpa) FROM Student GROUP BY pNumber; First form groups for each pNumber 21 Then count the records in each group And get the minimum gpa for each group

GROUP BY: Example I sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Jan500MA2 Student SELECT count(*) AS CNT FROM Student;  cnt  count(*) (Student) CNT 4 SELECT pNumber, count(*) AS CNT FROM Student WHERE sNumber > 1 GROUP BY pNumber; pNumberCNT  pNumber,cnt  count(*) (  (sNumber > 1) (Student)) 22

GROUP BY: Example II sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Jan500MA2 Student SELECT pNumber,address, count(sName) AS CNT, sum(sNumber) AS SUM FROM Student WHERE sNumber >= 1 GROUP BY pNumber, address; pNumberaddressCNTSUM 1320FL MA14  pNumber,address, CNT  count(sName), SUM  sum(sNumber) (  (sNumber > 1) (Student)) 23

Restrictions of GROUP BY If you group by A1, A2, …An, then any other column projected in SELECT clause must be inside an aggregation function SELECT pNumber, address, count(sName) AS CNT, sum(sNumber) AS SUM FROM Student WHERE sNumber > 1 GROUP BY pNumber, address; SELECT pNumber, address, sName, sum(sNumber) AS SUM FROM Student WHERE sNumber > 1 GROUP BY pNumber, address; X SELECT pNumber, count(sName) AS CNT, sum(sNumber) AS SUM FROM Student WHERE sNumber > 1 GROUP BY pNumber, address; 24

HAVING Clause: Putting Condition on Groups How to add conditions on each group? Select only the groups where the COUNT > 5 These conditions are after you build the groups (not before) Remember: WHERE conditions are executed before the groups are formed New optional clause called “HAVING”, added after the GROUP BY clause SELECT pNumber, COUNT (sName) FROM Student GROUP BY pNumber HAVING SUM(sNumber) > 2; Can reference aggregation inside HAVING 25

HAVING Clause: Example sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Jan500MA2 Student SELECT pNumber,address, count(sName) AS CNT, sum(sNumber) AS SUM FROM Student WHERE sNumber > 1 GROUP BY pNumber, address HAVING sum(sNumber) > 3; pNumberaddressCNTSUM 2500MA14  (SUM> 3) (  pNumber,address, CNT  count(sName), SUM  sum(sNumber) (  (sNumber > 1) (Student))) 26

SELECT Statement Clauses Optional clauses if added must be in the order above Order of execution FROM  Check which relations are used WHERE  Filter records based on conditions GROUP BY  Form groups HAVING  Filter groups based on conditions ORDER BY  Sort the data SELECT  Form the projection list (output columns) SELECT FROM WHERE GROUP BY HAVING ORDER BY ; optional 27

Questions SELECT FROM WHERE GROUP BY HAVING ORDER BY ; optional 28

More in SELECT Statement Special handling for NULL values Nested subqueries 29

Null Values Null means ‘unknown’ value Any expression containing Null returns Null 5 + null  null ‘ABC’ || null  null Null in predicates returns UNKNOWN Predicates usually return TRUE or FALSE 30

Example 31 sNumbersNameaddresspNumber 1Dave320FL1 2Gregnull1 3Mattnull2 4Jan500MA2 Student SELECT sNumber FROM Student WHERE address = ‘320FL’; sNumber May or may not appear

Truth Table (Including UNKNOWN) 32

Use of “IS NULL” or “IS NOT NULL” Check if a value is null or not 33 SELECT sNumber FROM Student WHERE address is not null AND address ‘320FL’; SELECT sNumber FROM Student WHERE address is null; Select student numbers where the address is null Remember: SELECT sNumber FROM Student WHERE address = null; X The returned value here is unknown

Use of “NVL” Function NVL( exp1, exp2) If exp1 is null return exp2, otherwise return expr1 Can be used in projection list or in predicates 34 SELECT sNumber FROM Student WHERE nvl(address, ‘n/a’) <> ‘n/a’ AND address ‘320FL’; SELECT sNumber, nvl(address, ‘N/A’) FROM Student; sNumberaddress 1320FL 2N/A MA

Null with Grouping & Aggregation Aggregation Null is ignored with all aggregates, e.g., SUM, AVG, MIN, MAX except COUNT(*) Grouping Null is considered as a separate group 35

Example 36 sNumbersNameaddresspNumber 1Dave320FL1 2Gregnull1 3Mattnull 4Jan500MA2 Student SELECT address, sum(pNumber) as sum, count(*) as cnt FROM Student GROUP BY address; addresssumcnt 320FL11 null12 500MA21

More in SELECT Statement Special handling for NULL values Nested subqueries 37

Nested Subquery SQL provides a mechanism for the nesting of subqueries. A subquery is a SELECT statement expression that is nested within another query Subquery can appear in FROM or WHERE clauses 38

Nested Subquery in WHERE Clause Since the predicates has = : The inner statement must return one record with one column In this case, DBMS will automatically convert the relation to a single scalar value Otherwise an error is generated 39 SELECT * FROM Student WHERE pNumber = (SELECT pNumber FROM Professor WHERE pName = ‘Mike’); 1- Execute this statement first to get the pNumber (inner SELECT) 2- Then, execute this statement once pNumber from the first step is known (outer SELECT)

CS3431 Example: Subqueries Retuning Scalar Value sNumbersNameaddresspNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddress 1MM141FL 2ER201FL Professor sNumbersName 1Dave 2Greg Select students of professor ‘MM’ SELECT sNumber, sName FROM Student WHERE pNum = (SELECT pNumber FROM Professor WHERE pName=‘MM’);

SubQuery Returning a Relation (General Case) Predicates may include any of (OP above) : Exists R  True if R is not empty s in R  True if tuple s appears in R s not in R  True if tuple s does not appear in R 41 SELECT sNumber, sName FROM Student WHERE pNum OP (SELECT pNumber FROM Professor WHERE pName=‘MM’); Inner Select (R) Outer Select (S)

CS3431 Example 1: Subqueries Returning Relations sNumbersNameaddresspNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Sam30IN3 Student pNumberpNameaddress 1MM141FL 2ER201FL 3XY30WA Professor sNumbersName 1Dave 2Greg 3Matt Select students of professors with address like ‘%FL’ SELECT sNumber, sName FROM Student WHERE pNum IN (SELECT pNumber FROM Professor WHERE address Like ‘%FL’);

CS3431 Example 2: Subqueries Returning Relations sNumbersNameaddresspNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Sam30IN3 Student pNumberpNameaddress 1MM141FL 2ER201FL 3XY30WA Professor sNumbersName 1Dave 2Greg 3Matt 4Sam SELECT sNumber, sName FROM Student WHERE Exists (SELECT pNumber FROM Professor WHERE address Like ‘%FL’); Always true because it is not empty

Example 3: Subqueries Returning Relations 44 Multi-column tuples

Comparison Using ALL and ANY We took: Exists, IN, NOT IN s > ALL R  True if s > all values in R s > ANY R  True if s > any value in R ‘>’ can be any of the other comparison operators, e.g., =, =, <> R must be relation with single column 45 SELECT sNumber, sName FROM Student WHERE pNum OP (SELECT pNumber FROM Professor WHERE pName=‘MM’); Inner Select (R) Outer Select (S)

Example sNumbersNameaddresspNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Sam30IN3 Student pNumberpNameaddress 1MM141FL 2ER201FL 3XY30WA Professor sNumbersName 3Matt 4Sam SELECT sNumber, sName FROM Student WHERE pNum >= ALL (SELECT pNumber FROM Professor WHERE address Like ‘%FL’); This inner select returns 1, 2

Correlated Selects If the “inner” select references the “outer” select  correlated In this case, the inner select is executed with each record from the outer select 47 Reference to the outer select Meaning: For each supplier, execute the inner select, and then evaluate the WHERE clause Returns: suppliers who do not have orders

Use of Inner Select with DML Commands Inner select can be used with Insert, Update, Delete commands 48 INSERT INTO suppliers (supplier_id, supplier_name) SELECT account_no, name FROM externals Where code = 1; Notice that there is no keyword “values” in this case

Nested Subquery in FROM Clause Use the inner SELECT like any other table It is just built on the fly Inner SELECT can be a full statement with all clauses ORDER BY clause does not make sense in the inner select 49 SELECT * FROM Student, (inner SELECT) AS q WHERE … Table built on the fly

Example 50 Subquery 1 is computed on the fly It is treated as a normal table after that

Questions Special handling for NULL values Nested subqueries 51