0% found this document useful (0 votes)
96 views

Chapter 8 SQL Complex Queries

The document discusses independent subqueries, correlated subqueries, EXISTS and NOT EXISTS operators, views in SQL, and granting and revoking permissions. It provides examples of how to write queries using these SQL features and explains what views are and how they can be created, updated, and dropped in a database.

Uploaded by

Jiawei Tan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Chapter 8 SQL Complex Queries

The document discusses independent subqueries, correlated subqueries, EXISTS and NOT EXISTS operators, views in SQL, and granting and revoking permissions. It provides examples of how to write queries using these SQL features and explains what views are and how they can be created, updated, and dropped in a database.

Uploaded by

Jiawei Tan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 51

RDBMS – Day 3

Copyright(C) 2014 INTI Education Group. All rights reserved.


Recap

• Normalization
– 1NF
– 2NF
– 3NF
• Merits and Demerits of Normalization
• Introduction to SQL
• DDL Statements
• Relational Operators
• DML Statements
• Group By and Having clause
• Joins

2
Session Plan

• Independent Subqueries
• Correlated Query
• Exists and Not Exists
• Views
• DCL Statements
• Grant
• Revoke

3
Independent subqueries

Copyright(C) 2014 INTI Education Group. All rights reserved.


Independent sub-queries

• Inner query is independent of outer query.

• Inner query is executed first and the results are stored.

• Outer query then runs on the stored results.

5
Retrieval using SUB QUERIES

To list the Cust_ID and Loan_No for all Customers who have taken a loan of
amount greater than the loan amount of Customer (Cust_ID = 104).

SELECT cust_ID, Loan_no


FROM Customer_Loan
WHERE amount_in_dollars >
(SELECT amount_in_dollars
FROM Customer_Loan
WHERE Cust_ID = 104);

Customer Data

6
Sub Query (Contd…)

7
Retrieval using SUB QUERIES

List customer names of all customers who have taken a loan > $3000.00.

SELECT Cust_Last_Name, Cust_Mid_Name, Cust_First_Name


FROM Customer_Details
WHERE Cust_ID
IN
( SELECT Cust_ID
FROM Customer_Loan
WHERE Amount_in_Dollars > 3000.00);

Customer Data

8
Retrieval using SUB QUERIES

List customer names of all customers who have the same Account_type as
Customer ‘Jones Simon’ .

SELECT Cust_Last_Name, Cust_Mid_Name, Cust_First_Name


FROM Customer_Account_Details
WHERE Account_Type
=
( SELECT Account_Type
FROM Customer_Details
WHERE Cust_Last_Name = ‘Jones’
AND Cust_First_Name = ‘Simon’);

Customer Data

9
Retrieval using SUB QUERIES

List customer names of all customers who do not have a Fixed Deposit.

SELECT Cust_Last_Name, Cust_Mid_Name, Cust_First_Name


FROM Customer_Account_Details
WHERE Cust_ID
NOT IN
( SELECT Cust_ID
FROM Customer_Fixed_Deposit);

Customer Data

10
Retrieval using SUB QUERIES

List customer names of all customers who have either a Fixed Deposit or a
loan but not both at any of Bank Branches. The list includes customers
who have no fixed deposit and loan at any of the bank branches.
SELECT Cust_Last_Name, Cust_Mid_Name, Cust_First_Name
FROM Customer_Details
WHERE Cust_ID
NOT IN
( SELECT Cust_ID
FROM Customer_Loan
WHERE Cust_ID
IN
(SELECT Cust_ID
FROM Customer_Fixed_Deposit ));

11
Correlated subqueries

Copyright(C) 2014 INTI Education Group. All rights reserved.


Correlated Sub Queries

• You can refer to the table in the FROM clause of the outer query in
the inner query using Correlated sub-queries.

• The inner query is executed separately for each row of the outer
query.
(i.e. In Co-Related Sub-queries, SQL performs a sub-query over
and over again – once for each row of the main query. )

13
Correlated Sub Queries

To list all Customers IDs who have a fixed deposit of amount less than the
sum of all their loans.

SELECT Cust_Id
FROM Customer_fixed_Deposit
WHERE amount_in_dollars
<
(SELECT sum(amount_in_dollars)
FROM Customer_Loan
WHERE Customer_Loan.Cust_Id =
Customer_Fixed_Deposit.Cust_ID);

14
Correlated Sub Queries

List customer details of all customers who have both a Fixed Deposit and a
loan at any of Bank Branches
SELECT Cust_ID,Cust_Last_Name
FROM Customer_Account_Details
WHERE Cust_ID
IN
(SELECT Cust_ID
FROM Customer_Loan
WHERE Customer_Loan.Cust_ID =
Customer_Account_Details.Cust_ID)

AND Cust_ID IN
(SELECT Cust_ID
FROM Customer_Fixed_Deposit
WHERE Customer_Fixed_Deposit.Cust_ID=Customer_
15
Account_Details.Cust_ID);
EXISTS Vs NOT EXISTS

Copyright(C) 2014 INTI Education Group. All rights reserved.


Retrieval using EXISTS

List all Customers who have at least one Fixed Deposit more than $3000.00.

SELECT Cust_ID, Cust_Last_Name, Cust_Mid_Name,


Cust_First_Name
FROM Customer_Accounts_Details S
WHERE
EXISTS
(SELECT *
FROM Customer_Fixed_Deposit O
WHERE O.Amount_in_Dollars > 3000.00
AND O.Cust_ID = S.Cust_ID);

17
Retrieval using EXISTS

List all Cust_ID who have both a Fixed Deposit and a Loan at the Bank

SELECT Cust_ID
FROM Customer_Fixed_Deposit
WHERE EXISTS
(SELECT *
FROM Customer_Loan
WHERE Customer_Loan.Cust_ID =
Customer_Fixed_Deposit.Cust_ID);

18
Retrieval using NOT EXISTS

List all Customers who don’t have a single Fixed Deposit over $3000.00.

SELECT Cust_ID, Cust_Last_Name, Cust_Mid_Name,


Cust_First_Name
FROM Customer_Account_Details S
WHERE
NOT EXISTS
(SELECT *
FROM Customer_Fixed_Deposit O
WHERE O.Amount_in_Dollars > 3000.00
AND O.Cust_ID = S.Cust_ID);

19
Views

Copyright(C) 2014 INTI Education Group. All rights reserved.


What is a view to the DBMS

• We can use views in select statements like


• Select * from view_employees where age > 23;
• DBMS translates the request to an equivalent request to the source table

21
Create a view

CREATE VIEW view-name (column-name1, column-name2, ---------------- ) AS query

CREATE VIEW ViewCustomerDetails


AS SELECT *
FROM Customer_Details;

22
Assigning names to columns

CREATE VIEW vwCustDetails (CustCode,CustLname,CustFName)


AS SELECT Cust_Id,Cust_Last_Name,Cust_First_Name
FROM Customer_details;

23
A view can be modified by the DML command.
Updating a VIEW

CREATE VIEW View_Cust


AS SELECT *
FROM Customer_Details
WHERE CUST_ID IN (101,102,103);
--Insert Statement
INSERT INTO view_cust
VALUES (103,'Langer','G.','Justin',3421,'Savings','
Global Commerce Bank','[email protected]');

--Delete Statement
DELETE view_cust WHERE cust_id = 103;

--Update Statament
UPDATE view_cust
SET Cust_last_name = 'Smyth'
WHERE cust_id = 101;
Demos\Views.doc 24
Updating View

A view can be updated if the query that defines the view meets all of
these restrictions:

• DISTINCT must not be specified; that is, duplicate rows must not be
eliminated from the query results

• The FROM clause must specify only one updateable table; the view
must have a single underlying source table

• The SELECT list cannot contain expressions, calculated columns, or


column functions

• The WHERE clause must not include a sub query; only simple row-by-
row search conditions may appear

25
Dropping Views

Views are dropped similar to the way in which the tables are dropped.
However, you must own a view in order to drop it.

DROP VIEW <view name>;

DROP VIEW View_Cust;

26
Checking View Updates :– Check Option

CREATE VIEW view_customer AS

SELECT Cust_ID, Cust_Last_Name, Account_No, Account_Type, Bank_Branch

FROM Customer_Details

WHERE Bank_Branch = ‘Downtown’ ;

INSERT INTO view_customer

VALUES (115, ’Costner’, 107, ‘Savings’, ‘Bridgewater’);

Will it prevent insertion into Customer_details ?

27
Checking View Updates :– Check Option

SELECT Cust_ID, Cust_Last_Name, Bank_Branch

FROM view_customer;

Solution is :

CREATE VIEW view_customer AS

SELECT Cust_ID, Cust_Last_Name, Account_No, Account_Type, Bank_Branch

FROM Customer_Details

WHERE Bank_Branch = ‘Downtown’

With CHECK OPTION;

28
Advantages of views

• Security

• Query simplicity

• Structural simplicity

29
Disadvantages of views

• Performance

• Restrictions

30
Data Control Language (DCL)

Copyright(C) 2014 INTI Education Group. All rights reserved.


GRANT …. Tables or views

GRANT {
[ALTER[, ]]
[DELETE[, ]]
[INDEX[, ]]
[INSERT[, ]]
[SELECT[, ]]
[UPDATE [(column-name[,...])][, ]]
| ALL [PRIVILEGES]] }
ON [TABLE] {table-name[,...] | view-
name[,...]}
TO [AuthID][,...]
[WITH GRANT OPTION]

32
GRANT

GRANT SELECT, INSERT


ON Customer_Details
TO Edwin ;

GRANT ALL PRIVILEGES


ON Customer_Loan
TO JACK ;

GRANT ALL
ON Customer_Loan
TO PUBLIC ;

33
Grant

• With Grant Option

GRANT SELECT
EDWIN 1. WITH GRANT OPTION
ON Customer_Loan
TO EDWIN
WITH GRANT OPTION;

2. GRANT
JACK

BORIS

34
Taking PRIVILIGES away

The syntax of REVOKE command is patterned after GRANT, but with a


reverse meaning.

REVOKE{
[ALTER[, ]]
[DELETE[, ]]
[INDEX[, ]]
[INSERT[, ]]
[SELECT[, ]]
[UPDATE [(column-name[,...])][, ]]
| ALL [PRIVILEGES] }
ON [TABLE] {table-name[,...] | view-name [,...]}
FROM AuthID[,...]

35
Revoke

REVOKE SELECT, INSERT


ON Customer_Details
FROM Edwin ;

REVOKE ALL PRIVILEGES


ON Customer_Loan
FROM JACK ;

REVOKE ALL
ON Customer_Loan
FROM PUBLIC ;

36
Revoke

1. WITH GRANT OPTION

EDWIN

3. REVOKE

2. GRANT

JACK

BORIS

37
Summary

• When the query consists of more than one component, it is


implemented in the form of a nested query depending on the nature of
the query
• Sub queries help split a problem involving different levels of data
• Views create a window into the table thereby allowing restricted access

• Index helps speed up the search process

38
Appendix - SQL Functions

Copyright(C) 2014 INTI Education Group. All rights reserved.


DUAL - The Dummy table

• Automatically created table, which is part of the data dictionary


• Contains one row and one column(varchar2(1): value = ‘X’)
• Can be used to return constants once, with a SELECT statement
• Belongs to SYS schema, accessible to all

Example:
SELECT SYSDATE FROM DUAL;

40
SQL Functions - Decode

Decode

– DECODE ( expr , search , result [, search , result]... [, default] )

– A DECODE function compares expr to each search value one by one. If expr
is equal to a search, Oracle returns the corresponding result. If no match is
found, Oracle returns default, or, if default is omitted, returns null.

– This example decodes the value warehouse_id. If warehouse_id is 1, the


function returns 'Southlake'; if warehouse_id is 2, it returns 'San Francisco';
etc. If warehouse_id is not 1, 2, 3, or 4, the function returns 'Non-domestic'.

SELECT product_id, DECODE (warehouse_id, 1, 'Southlake',


2, 'San Francisco', 3, 'New Jersey', 4, 'Seattle', 'Non-
domestic') quantity_on_hand FROM inventories;

41
SQL Functions - Trim

Trim

Syntax:

TRIM ({Leading/Trainiling/Both} trim_character FROM trim_source)

TRIM enables you to trim leading or trailing characters (or both) from a
character string. If trim_character or trim_source is a character literal, you
must enclose it in single quotes.

SELECT TRIM (0 FROM 0009872348900) "TRIM Example" FROM


DUAL;

42
SQL Functions - Substr

Substr

Syntax:

SUBSTR (string, position, substring_length)

– The substring functions return a portion of string, beginning at character


position, substring_length characters long. SUBSTR calculates lengths using
characters as defined by the input character set. SUBSTRB uses bytes
instead of characters.

SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL;

43
SQL Functions - TRANSLATE

TRANSLATE

– TRANSLATE ( 'char' , 'from_string' , 'to_string' )

– TRANSLATE returns char with all occurrences of each character in


from_string replaced by its corresponding character in to_string. Characters
in char that are not in from_string are not replaced.

– The following statement translates a license number. All letters 'ABC...Z' are
translated to 'X' and all digits '012 . . . 9' are translated to '9':

SELECT TRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX') "License"
FROM DUAL;

44
SQL Functions – TO_CHAR

TO_CHAR

– TO_CHAR ( date , fmt )

– TO_CHAR converts date of DATE to a value of VARCHAR2 datatype in the


format specified by the date format fmt.

SELECT TO_CHAR(ts_col, 'DD-MON-YYYY HH24:MI:SS')


FROM my_tab;

45
SQL Functions – TO_DATE

TO_DATE

– To_date( char , fmt )

– TO_DATE converts char in the format specified to a value of DATE datatype

SELECT TO_DATE ('14/05/2007','dd/mm/yyyy') FROM DUAL;

46
SQL Functions - NVL

NVL

– NVL ( expr1 , expr2 )

– If expr1 is null, NVL returns expr2. If expr1 is not null, NVL returns expr1.

– The following example returns a list of employee names and commissions,


substituting "Not Applicable" if the employee receives no commission:

SELECT last_name,
NVL(TO_CHAR(commission_pct), 'Not Applicable')
"COMMISSION"
FROM employees
WHERE last_name LIKE 'B%';

47
Pseudocolumns

• Behaves like a table column


• Not stored in table
• Cannot change value of pseudocolumn

48
Pseudocolumns

• ROWID
• ROWNUM

49
Examples

• SELECT ROWID, ENAME FROM EMP;

• SELECT ROWNUM, ENAME FROM EMP ORDER BY ename;

50
Thank You

Copyright(C) 2014 INTI Education Group. All rights reserved.

You might also like