You are on page 1of 56

Education and Research

We enable you to leverage knowledge anytime, anywhere!

RDBMS Day 4

ER/CORP/CRS/DB07/003

Ver. No.: 4.0

Copyright 2008, Infosys Technologies Ltd.

Recap
 Introduction to SQL
 DDL Statements
 Create Table
 Alter Table
 Drop Table
 Truncate Table
 Create Index
 Merits & Demerits of Index
 Relational Operators
 DML Statements
 Insert into
 Delete from
 Select
 Update
Copyright 2008, Infosys Technologies Ltd.

Session Plan








Group By
Relational Algebra
Cartesian Product
Inner Join
Self Join
Outer Join
Independent Sub-queries

Copyright 2008, Infosys Technologies Ltd.

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Grouping Data with Group By

ER/CORP/CRS/DB07/003

Ver. No.: 4.0

Copyright 2008, Infosys Technologies Ltd.

SQL - Using GROUP BY


 Related rows can be grouped together by GROUP BY clause
by specifying a column as a grouping column.
 GROUP BY is associated with an aggregate function
 To retrieve the total loan-amount of all loans taken by each
Customer.

SELECT

Cust_ID,
FROM

SUM(Amount_in_Dollars)

Customer_Loan
GROUP BY

Copyright 2008, Infosys Technologies Ltd.

Cust_ID;

SQL Group By

Copyright 2008, Infosys Technologies Ltd.

SQL Group BY
To retrieve Number of Employees in each Department
SELECT

Department, COUNT (Employee_ID)


FROM

Employee_Manager
GROUP BY Department

Demo on Group By Single column


Copyright 2008, Infosys Technologies Ltd.

Retrieval using GROUP BY


Example:
Invalid SQL statement
SELECT Department, Manager_ID, COUNT(Employee_ID)
FROM Employee_Manager
GROUP BY Manager_ID;

Valid SQL Statement


SELECT Department, Manager_ID, COUNT(Employee_ID)
FROM Employee_Manager
GROUP BY Manager_ID, Department;

Copyright 2008, Infosys Technologies Ltd.

SQL Group By

Demo on Group By
more than one column
Copyright 2008, Infosys Technologies Ltd.

Retrieval using HAVING


List all customers who are having loans greater than 4000
SELECT Cust_ID,SUM(Amount_in_Dollars)
FROM Customer_Loan
GROUP BY Cust_ID

HAVING SUM(Amount_in_Dollars) > 4000.00;

Copyright 2008, Infosys Technologies Ltd.

10

Can you identify any error?


SELECT Cust_ID, SUM(Amount_in_Dollars)
FROM Customer_Loan
GROUP BY Cust_ID HAVING LOAN_NO > 4000.00;

Ans: The Having condition has to be based on some column that


appears in the group by list

Copyright 2008, Infosys Technologies Ltd.

11

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Relational Algebra Operations

ER/CORP/CRS/DB07/003

Ver. No.: 4.0

Copyright 2008, Infosys Technologies Ltd.

Retrieval using UNION


List all the customer who has either Fixed Deposit or Loan or
Both
SELECT Cust_ID
FROM Customer_Fixed_Deposit
Customer_Fixed
_Deposit

UNION

Customer_
Loan

SELECT Cust_ID
FROM Customer_Loan;

The UNION operation


Combines the rows from two sets of query results.
By default, the UNION operation eliminates duplicate rows as part of its
processing.

Copyright 2008, Infosys Technologies Ltd.

13

Union (Contd)

Copyright 2008, Infosys Technologies Ltd.

14

Union All
SELECT Cust_ID FROM Customer_Fixed_Deposit
UNION ALL
SELECT Cust_ID FROM Customer_Loan;

Copyright 2008, Infosys Technologies Ltd.

15

Union - Restrictions
 The SELECT statements must contain the same number of
columns
 Data type

 Each column in the first table must be the same as the


data type of the corresponding column in the second
table.
 Data width and column name can differ
 Neither of the two tables can be sorted with the ORDER BY clause.

 Combined query results can be sorted

Copyright 2008, Infosys Technologies Ltd.

16

Retrieval using INTERSECT


List all the customer who have both Fixed Deposit and Loan.
SELECT Cust_ID
FROM Customer_Fixed_Deposit
Customer_Fixed
_Deposit

INTERSECT
SELECT Cust_ID
FROM Customer_Loan;

Copyright 2008, Infosys Technologies Ltd.

17

Customer_Loan

Minus
 Get All the Customer who have not
taken loan
SELECT Cust_ID
FROM
Customer_Account_details

Customer_Accoynt_
Details

MINUS
SELECT Cust_Id
FROM Customer_loan;

Copyright 2008, Infosys Technologies Ltd.

18

Customer_Loan

Other Relational Algebra operations


 Restriction
 Projection
 Join

Copyright 2008, Infosys Technologies Ltd.

19

Restriction
 Restricts the rows that can be chosen from a relation using a
WHERE clause
 Takes a horizontal subset of values from the original relation
Example:
SELECT * FROM employee WHERE salary > 10000;

Copyright 2008, Infosys Technologies Ltd.

20

Projection
 Projection is projecting a set of attributes of a relation so that rows of
values corresponding to those columns will figure in the output
 This takes a vertical subset of the relation
Example:
SELECT empid, name, salary FROM employee;

Copyright 2008, Infosys Technologies Ltd.

21

JOINS





Cartesian Product
Inner join
Equi join
Outer join

 Left-outer join
 Right-outer join
 Self join

Copyright 2008, Infosys Technologies Ltd.

22

Cartesian Product Or Cross Join


 Returns All rows from first table, Each row from the first table is
combined with all rows from the second table
Example
SELECT

FROM Table1,Table2;

Copyright 2008, Infosys Technologies Ltd.

23

Inner Joins
 Common type of join
 An inner join between two (or more) tables is the Cartesian product
that satisfies the join condition in the WHERE clause

Copyright 2008, Infosys Technologies Ltd.

24

Retrieval from Multiple tables-Equi


join
Get all combinations of emp and cust information such that the emp and
cust are co-located.
SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
FROM Table1, Table2
WHERE Table1.City = Table2.City;

Copyright 2008, Infosys Technologies Ltd.

25

Retrieval from Multiple tables- Equi join


Display the Employee number, Employee name and department
name of the employees who are working for some department.
SELECT EmpNo, EName,DName
FROM Emp E , Dept D
WHERE E.DeptNo = D.DeptNo;

Demo on Equi Join

Copyright 2008, Infosys Technologies Ltd.

26

Retrieval from Multiple tables- Equi join


Display the First and Last Name of Customer who have taken Loan

SELECT a.Cust_Id,b.Cust_First_Name,b.Cust_Last_Name
FROM Customer_loan a, Customer_Account_details b
WHERE a.cust_id = b.cust_id;

Copyright 2008, Infosys Technologies Ltd.

27

Outer join
 Retrieve all rows that match the WHERE clause and also those that
have a NULL value in the column used for join.

Copyright 2008, Infosys Technologies Ltd.

28

Left / Right-Outer join


 Left outer joins include all records from the first (left) of two tables,
A = B (+)
 Right outer joins include all records from the second (right) of two
tables,
A (+) = B

Copyright 2008, Infosys Technologies Ltd.

29

Example of left-join
List all cities of Table1 if there is match in cities in Table2 & also unmatched
Cities from Table1
SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
FROM Table1, Table2
WHERE Table1.City

Copyright 2008, Infosys Technologies Ltd.

= Table2.City (+);

30

Example of Left Outer Join


 List all customer details and loan details if they have availed loans.
SELECT
Customer_details.Cust_id,Cust_Last_name,Loan_no,
Amount_in_dollars
FROM Customer_Account_details,Customer_loan
WHERE Customer_Account_details.Cust_id =
Customer_loan.Cust_id (+);

Copyright 2008, Infosys Technologies Ltd.

31

Example of right outer join


SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
FROM Table1, Table2
WHERE Table1.City (+) = Table2.City;

Copyright 2008, Infosys Technologies Ltd.

32

Self join-Joining a table with itself


To list all the Employees along with their Managers
SELECT
Emp.Employee_ID

as

Emp.Employee_Last_Name

as

Employee Last Name,

Emp.Manager_Id

as

Manager ID,

Manager.Employee_Last_Name

as

Manager Last Name,

FROM employee_Manager

Emp, employee_Manager

WHERE Emp.Manager_ID

Copyright 2008, Infosys Technologies Ltd.

Employee ID,

33

Manager

Manager.Employee_ID;

Self Join (Contd)

Demo on Self join


Copyright 2008, Infosys Technologies Ltd.

34

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Independent Sub-Queries

ER/CORP/CRS/DB07/003

Ver. No.: 4.0

Copyright 2008, Infosys Technologies Ltd.

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.

Copyright 2008, Infosys Technologies Ltd.

36

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

Copyright 2008, Infosys Technologies Ltd.

37

Sub Query (Contd)

Copyright 2008, Infosys Technologies Ltd.

38

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_Account_Details
WHERE Cust_ID
IN
( SELECT Cust_ID
FROM Customer_Loan
WHERE Amount_in_Dollars > 3000.00);

Customer Data

Copyright 2008, Infosys Technologies Ltd.

39

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_Account_Details
WHERE Cust_Last_Name = Jones
AND Cust_First_Name = Simon);

Customer Data
Copyright 2008, Infosys Technologies Ltd.

40

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

Copyright 2008, Infosys Technologies Ltd.

41

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_Account_Details
WHERE Cust_ID
NOT IN
( SELECT Cust_ID
FROM Customer_Loan
WHERE Cust_ID
IN
(SELECT Cust_ID
FROM Customer_Fixed_Deposit ));
Copyright 2008, Infosys Technologies Ltd.

42

Summary
 The result of a query can be grouped based on a grouping column
 While checking for conditions after grouping by a column , Having is
used instead of where
 Grouped queries help look at data category wise
 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
 Relational algebra operations like union, intersect, difference,
restriction, projection and join help us get different combinations of data
from more than one table

Copyright 2008, Infosys Technologies Ltd.

43

Thank You

The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may
not be disclosed in whole or in part at any time, to any third party without the prior written consent of
Infosys Technologies Ltd.
2008 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this
document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted,
abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the
prior written consent of Infosys Technologies Ltd.

Copyright 2008, Infosys Technologies Ltd.

44

Education and Research


We enable you to leverage knowledge anytime, anywhere!

APPENDIX-- SQL Functions

ER/CORP/CRS/DB07/003

Ver. No.: 4.0

Copyright 2008, Infosys Technologies Ltd.

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;

Copyright 2008, Infosys Technologies Ltd.

46

SQL Functions - 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;
Copyright 2008, Infosys Technologies Ltd.

47

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;

Copyright 2008, Infosys Technologies Ltd.

48

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;
Copyright 2008, Infosys Technologies Ltd.

49

SQL Functions - 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;
Copyright 2008, Infosys Technologies Ltd.

50

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;

Copyright 2008, Infosys Technologies Ltd.

51

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;

Copyright 2008, Infosys Technologies Ltd.

52

SQL Functions - 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%';

Copyright 2008, Infosys Technologies Ltd.

53

Pseudocolumns
 Behaves like a table column
 Not stored in table
 Cannot change value of pseudocolumn

Copyright 2008, Infosys Technologies Ltd.

54

Pseudocolumns
 ROWID
 ROWNUM

Copyright 2008, Infosys Technologies Ltd.

55

Examples
 SELECT ROWID, ENAME FROM EMP;
 SELECT ROWNUM, ENAME FROM EMP ORDER BY ename;

Copyright 2008, Infosys Technologies Ltd.

56

You might also like