SQL: Structured Query Languageweb.cs.wpi.edu/~cs3431/c15/lectures/Week 5/sqlQueries3.pdf · SQL:...

Preview:

Citation preview

SQL: Structured Query Language

Instructor: Mohamed Eltabakh

meltabakh@cs.wpi.edu

1

Part -3

More in SELECT Statement

l  Special handling for NULL values

l  Queries inside Insert/Update/Delete

l  Temp Tables

l  Nested subqueries

2

Null Values l  Null means ‘unknown’ value

l  Any expression containing Null returns Null l  5 + null à null l  ‘ABC’ || null à null

l  Null in predicates returns UNKNOWN l  Predicates usually return TRUE or FALSE

3

Example

4

sNumber sName address pNumber 1 Dave 320FL 1

2 Greg null 1

3 Matt null 2

4 Jan 500MA 2

Student

SELECT sNumber FROM Student WHERE address = ‘320FL’;

sNumber 1

2

3 May or may not appear

Having Null in the data is problematic and needs special care…

Use of “IS NULL” or “IS NOT NULL”

l  Check if a value is null or not

5

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 l  NVL( exp1, exp2)

l  If exp1 is null return exp2, otherwise return expr1

l  Can be used in projection list or in predicates

6

SELECT sNumber FROM Student WHERE nvl(address, ‘n/a’) <> ‘n/a’ AND address ‘320FL’;

SELECT sNumber, nvl(address, ‘N/A’) FROM Student;

sNumber address 1 320FL

2 N/A

3 N/A

4 500MA

Null with Grouping & Aggregation

l  Aggregation l  Null is ignored with all aggregates, e.g., SUM, AVG, MIN,

MAX except COUNT()

l  Grouping l  Null is considered as a separate group

7

Example

8

sNumber sName address pNumber 1 Dave 320FL 1

2 Greg null 1

3 Matt null null

4 Jan 500MA 2

Student

SELECT address, sum(pNumber) as sum, count(*) as cnt FROM Student GROUP BY address;

address sum cnt 320FL 1 1

null 1 2

500MA 2 1

More in SELECT Statement

l  Special handling for NULL values

l  Queries inside Insert/Update/Delete

l  Temp Tables

l  Nested subqueries

9

Reminder About: Insert, Update, Delete l  This is performed using Data Manipulation

Language of SQL (DML)

l  Insertion l  Insert into Students values (‘1111’, …);!

l  Deletion l  Delete from Students;!l  Delete from Students Where sid = ‘1111’;!

l  Update l  Update Students Set GPA = GPA + 0.4;!l  Update Students Set GPA = GPA + 0.4 Where sid = ‘1111’;!

!10

Use of Select Inside Insert l  All records returned from the Select will be inserted

11

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

Number of columns and data types should match

Use of Select Inside Delete

12

Delete From Student Where sNumber in (Select sNumber from Registration Where grade = ‘F’);

sNumber sName address 1 Dave 320FL

2 Greg null

3 Matt null

4 Jan 500MA

sNumber courseID grade 4 DB1 A

2 DB1 F

3 DB2 A

4 DB2 F

Student Registration

l  Delete from Student all those who have grade ‘F’

Students number 2 & 4 will be deleted…

Use of Select Inside Delete

13

Delete From Student Where sNumber not in (Select sNumber from Registration);

sNumber sName address 1 Dave 320FL

2 Greg null

3 Matt null

4 Jan 500MA

sNumber courseID grade 4 DB1 A

2 DB1 F

3 DB2 A

4 DB2 F

Student Registration

l  Delete from Student all those who do not have registration

Student number 1 will be deleted…

Use of Select Inside Update

14

Update Registration Set grade = ‘B’ Where sNumber in (Select sNumber from Student Where sName =‘Matt’);

sNumber sName address 1 Dave 320FL

2 Greg null

3 Matt null

4 Jan 500MA

sNumber courseID grade 4 DB1 A

2 DB1 F

3 DB2 A

4 DB2 F

Student Registration

l  Update the grades of student ‘Matt’ to B

Remember…

15

Delete From Student Where sNumber not in (Select sNumber from Registration);

Update Registration Set grade = ‘B’ Where sNumber in (Select sNumber from Student Where sName =‘Matt’);

In Delete and Update - The ‘From’ clause always has one table - The subquery can be only added in the ‘Where’ clause

More in SELECT Statement

l  Special handling for NULL values

l  Queries inside Insert/Update/Delete

l  Temp Tables

l  Nested subqueries

16

Temp Tables

l  If a query is very complex, divide it into sub-queries

l  Store the intermediate results in “Temp Tables”

l  The got deleted automatically at the end of the session

17

Example

18

Create Global Temporary Table temp123 (x int, y varchar2(10));

Insert into temp123 Select …;

Temp table. Its data will be deleted at log out

Inserting some intermediate data

More selects that may reference temp123 …

Exit; intermediate data is automatically deleted

Reuse the intermediate data

More in SELECT Statement

l  Special handling for NULL values

l  Queries inside Insert/Update/Delete

l  Nested subqueries

19

Nested Subquery l  SQL provides a mechanism for the nesting of

subqueries.

l  A subquery is a SELECT statement expression that is nested within another query

l  Subquery can appear in FROM or WHERE

clauses

20

Nested Subquery in FROM Clause

l  Use the inner SELECT like any other table l  It is just built on the fly

l  Inner SELECT can be a full statement with all clauses l  ORDER BY clause does not make sense in the inner select

21

SELECT * FROM Student, (inner SELECT) AS q WHERE … Table built on the fly

Back to this Example

22

Report the output relation O(CustomerName, Num_Loans, Num_Accounts) only for customers who have loans and accounts

SELECT customer_name, count(Distinct loan_number), count(Distinct account_number) FROM Depositor D, Borrower B WHERE D.customer_name = B.customer_name GROUP BY customer_name;

Find another way ??

Back to this Example

23

Report the output relation O(CustomerName, Num_Loans, Num_Accounts) only for customers who have loans and accounts

SELECT D.customer_name, Num_Loan, Num_Acc FROM ( Select customer_name, count(*) As Num_Acc From Depositor Group By customer_name) As D,

( Select customer_name, count(*) As Num_Loan From Borrower Group By customer_name) As B WHERE D.customer_name = B.customer_name;

Nested Subquery in WHERE Clause

l  Since the predicates has = : l  The inner statement must return one record with one column l  In this case, DBMS will automatically convert the relation to a

single scalar value l  Otherwise an error is generated

24

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

sNumber sName address pNum

1 Dave 320FL 1

2 Greg 320FL 1

3 Matt 320FL 2

Student pNumber pName address

1 MM 141FL

2 ER 201FL

Professor

sNumber sName 1 Dave 2 Greg

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)

l  Predicates may include any of (OP above) : l  s in R à True if tuple s appears in R l  s not in R à True if tuple s does not appear in R l  s = R à R must return a single value (otherwise invalid op)

26

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

sNumber sName address pNum

1 Dave 320FL 1

2 Greg 320FL 1

3 Matt 320FL 2

4 Sam 30IN 3

Student pNumber pName address

1 MM 141FL

2 ER 201FL

3 XY 30WA

Professor

sNumber sName 1 Dave 2 Greg 3 Matt

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 3: Subqueries

sID courseID … …

1 CS101

2 CS300

1 CS202

4 CS500

4 CS203

1 CS303

Registration è R Q: Find the student ID taking the largest number of courses

sID CNT

1 3

2 1

4 2

SELECT sID, count(courseID) as CNT FROM R Group By sID;

Step 1

CS3431

Example 3: Subqueries

sID courseID … …

1 CS101

2 CS300

1 CS202

4 CS500

4 CS203

1 CS303

Registration è R Q: Find the student ID taking the largest number of courses

SELECT sID, count(courseID) as CNT FROM R Group By sID Having count(courseID) =

( SELECT Max(CNT) As Max From (SELECT count(courseID) As CNT

FROM R Group By sID) q

) CNT

3

1

2

Step 2

Max

3

sID CNT

1 3

sID CNT

1 3

2 1

4 2

Comparison Using ALL and ANY

l  We took: Exists, IN, NOT IN

l  s > ALL R à True if s > all values in R l  s > ANY R à True if s > any value in R l  ‘>’ can be any of the other comparison operators, e.g., <, <=, >=, =, <> l  R must be relation with single column

30

SELECT sNumber, sName FROM Student WHERE pNum OP

(SELECT pNumber FROM Professor WHERE pName=‘MM’);

Inner Select (R)

Outer Select (S)

Example

sNumber sName address pNum

1 Dave 320FL 1

2 Greg 320FL 1

3 Matt 320FL 2

4 Sam 30IN 3

Student pNumber pName address

1 MM 141FL

2 ER 201FL

3 XY 30WA

Professor

sNumber sName 3 Matt 4 Sam

SELECT sNumber, sName FROM Student WHERE pNum >= ALL

(SELECT pNumber FROM Professor WHERE address Like ‘%FL’);

This inner select returns 1 , 2

Recommended