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.

2

Session Plan       

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

Copyright © 2008, Infosys Technologies Ltd.

3

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;

5

6 .SQL – Group By Copyright © 2008. Infosys Technologies Ltd.

Infosys Technologies Ltd. 7 .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.

COUNT(Employee_ID) FROM Employee_Manager GROUP BY Manager_ID. Department. Copyright © 2008. Manager_ID. Valid SQL Statement SELECT Department. COUNT(Employee_ID) FROM Employee_Manager GROUP BY Manager_ID. 8 . Infosys Technologies Ltd.Retrieval using GROUP BY Example: Invalid SQL statement SELECT Department. Manager_ID.

Infosys Technologies Ltd. 9 .SQL – Group By Demo on Group By more than one column Copyright © 2008.

10 .SUM(Amount_in_Dollars) FROM Customer_Loan GROUP BY Cust_ID HAVING SUM(Amount_in_Dollars) > 4000. Infosys Technologies Ltd.Retrieval using HAVING List all customers who are having loans greater than 4000 SELECT Cust_ID.00. Copyright © 2008.

Ans: The Having condition has to be based on some column that appears in the group by list Copyright © 2008. 11 . Infosys Technologies Ltd.Can you identify any error…? SELECT Cust_ID. SUM(Amount_in_Dollars) FROM Customer_Loan GROUP BY Cust_ID HAVING LOAN_NO > 4000.00.

No. Infosys Technologies Ltd. .Education and Research We enable you to leverage knowledge anytime. anywhere! Relational Algebra Operations ER/CORP/CRS/DB07/003 Ver.0 Copyright © 2008.: 4.

Copyright © 2008. the UNION operation eliminates duplicate rows as part of its processing.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. 13 . The UNION operation • Combines the rows from two sets of query results. Infosys Technologies Ltd. • By default.

14 . Infosys Technologies Ltd.Union (Contd…) Copyright © 2008.

Union All SELECT Cust_ID FROM Customer_Fixed_Deposit UNION ALL SELECT Cust_ID FROM Customer_Loan. Copyright © 2008. Infosys Technologies Ltd. 15 .

Infosys Technologies Ltd.  Combined query results can be sorted Copyright © 2008. 16 .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.Union .  Data width and column name can differ  Neither of the two tables can be sorted with the ORDER BY clause.

17 Customer_Loan . Copyright © 2008. Infosys Technologies Ltd. SELECT Cust_ID FROM Customer_Fixed_Deposit Customer_Fixed _Deposit INTERSECT SELECT Cust_ID FROM Customer_Loan.Retrieval using INTERSECT List all the customer who have both Fixed Deposit and Loan.

18 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.

Infosys Technologies Ltd.Other Relational Algebra operations  Restriction  Projection  Join Copyright © 2008. 19 .

20 . Copyright © 2008.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. Infosys Technologies Ltd.

Copyright © 2008. Infosys Technologies Ltd.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. 21 . name. salary FROM employee.

Infosys Technologies Ltd. 22 .JOINS     Cartesian Product Inner join Equi join Outer join  Left-outer join  Right-outer join  Self join Copyright © 2008.

Infosys Technologies Ltd. Copyright © 2008. 23 . Each row from the first table is combined with all rows from the second table Example SELECT * FROM Table1.Table2.Cartesian Product Or Cross Join  Returns All rows from first table.

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 .

Table2. 25 . Table2. Infosys Technologies Ltd. Copyright © 2008.Cust_ID. Table2 WHERE Table1.Retrieval from Multiple tables-Equi join Get all combinations of emp and cust information such that the emp and cust are co-located.City = Table2.City FROM Table1.Emp_ID.City. Table1. SELECT Table1.City.

DName FROM Emp E .DeptNo. Dept D WHERE E. SELECT EmpNo. Employee name and department name of the employees who are working for some department. Infosys Technologies Ltd.Equi join Display the Employee number.DeptNo = D. Demo on Equi Join Copyright © 2008.Retrieval from Multiple tables. 26 . EName.

Retrieval from Multiple tables. 27 .b. Copyright © 2008.b.cust_id.Cust_First_Name. Customer_Account_details b WHERE a.cust_id = b.Cust_Id.Cust_Last_Name FROM Customer_loan a. Infosys Technologies Ltd.Equi join Display the First and Last Name of Customer who have taken Loan SELECT a.

Infosys Technologies Ltd. 28 . Copyright © 2008.Outer join  Retrieve all rows that match the WHERE clause and also those that have a NULL value in the column used for join.

Infosys Technologies Ltd. A = B (+)  Right outer joins include all records from the second (right) of two tables.Left / Right-Outer join  Left outer joins include all records from the first (left) of two tables. A (+) = B Copyright © 2008. 29 .

Table2 WHERE Table1.City Copyright © 2008.Cust_ID. Table2.City FROM Table1.Emp_ID.City (+). Infosys Technologies Ltd. Table2.Example of left-join List all cities of Table1 if there is match in cities in Table2 & also unmatched Cities from Table1 SELECT Table1. 30 .City. Table1. = Table2.

Cust_id = Customer_loan. Amount_in_dollars FROM Customer_Account_details.Cust_Last_name.Cust_id. Infosys Technologies Ltd.Customer_loan WHERE Customer_Account_details.Example of Left Outer Join  List all customer details and loan details if they have availed loans. SELECT Customer_details.Cust_id (+).Loan_no. 31 . Copyright © 2008.

Table2.Emp_ID. Table2 WHERE Table1.Example of right outer join SELECT Table1.Cust_ID. Table2.City.City. 32 . Table1.City (+) = Table2. Copyright © 2008.City FROM Table1. Infosys Technologies Ltd.

= 33 Manager Manager. Emp.Employee_Last_Name as “Employee Last Name”.Employee_Last_Name as “Manager Last Name”.Self join-Joining a table with itself To list all the Employees along with their Managers SELECT Emp.Employee_ID as Emp. FROM employee_Manager Emp. “Employee ID”.Manager_Id as “Manager ID”. .Employee_ID. employee_Manager WHERE Emp. Manager. Infosys Technologies Ltd.Manager_ID Copyright © 2008.

Self Join (Contd…) Demo on Self join Copyright © 2008. 34 . Infosys Technologies Ltd.

.: 4.Education and Research We enable you to leverage knowledge anytime. anywhere! Independent Sub-Queries ER/CORP/CRS/DB07/003 Ver. Infosys Technologies Ltd.0 Copyright © 2008. No.

 Outer query then runs on the stored results. 36 . Infosys Technologies Ltd. Copyright © 2008.  Inner query is executed first and the results are stored.Independent sub-queries  Inner query is independent of outer query.

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). Infosys Technologies Ltd. 37 . Customer Data Copyright © 2008.

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. 39 . Infosys Technologies Ltd. SELECT Cust_Last_Name. Cust_First_Name FROM Customer_Account_Details WHERE Cust_ID IN ( SELECT Cust_ID FROM Customer_Loan WHERE Amount_in_Dollars > 3000. Cust_Mid_Name.00).00. Customer Data Copyright © 2008.

Retrieval using SUB QUERIES List customer names of all customers who have the same Account_type as Customer ‘Jones Simon’ . 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. SELECT Cust_Last_Name. 40 .

Cust_First_Name FROM Customer_Account_Details WHERE Cust_ID NOT IN ( SELECT Cust_ID FROM Customer_Fixed_Deposit). Cust_Mid_Name. Customer Data Copyright © 2008. 41 . SELECT Cust_Last_Name. Infosys Technologies Ltd.Retrieval using SUB QUERIES List customer names of all customers who do not have a Fixed Deposit.

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 )). Infosys Technologies Ltd. The list includes customers who have no fixed deposit and loan at any of the bank branches. Copyright © 2008.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. SELECT Cust_Last_Name. 42 .

restriction. 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.Summary  The result of a query can be grouped based on a grouping column  While checking for conditions after grouping by a column . projection and join help us get different combinations of data from more than one table Copyright © 2008. difference. Infosys Technologies Ltd. Having is used instead of where  Grouped queries help look at data category wise  When the query consists of more than one component. intersect. 43 .

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

No.Education and Research We enable you to leverage knowledge anytime. Infosys Technologies Ltd.: 4.0 Copyright © 2008. .SQL Functions ER/CORP/CRS/DB07/003 Ver. anywhere! APPENDIX-.

46 . Infosys Technologies Ltd.DUAL . which is part of the data dictionary  Contains one row and one column(varchar2(1): value = ‘X’)  Can be used to return constants once. Copyright © 2008. accessible to all Example: SELECT SYSDATE FROM DUAL.The Dummy table  Automatically created table. with a SELECT statement  Belongs to SYS schema.

4. DECODE (warehouse_id. 2. search . if default is omitted. 1. 3. Copyright © 2008. If warehouse_id is 1. 2. Oracle returns default.SQL Functions . the function returns 'Non-domestic'. result]. 3.  This example decodes the value warehouse_id. If no match is found.Decode  DECODE ( expr . it returns 'San Francisco'. If warehouse_id is not 1. if warehouse_id is 2. SELECT product_id. If expr is equal to a search. 'San Francisco'. 'Southlake'. 'New Jersey'. 'Seattle'.. default] )  A DECODE function compares expr to each search value one by one.. 47 . or 4. Oracle returns the corresponding result. 'Non-domestic') quantity_on_hand FROM inventories. the function returns 'Southlake'. result [. Infosys Technologies Ltd. etc. or. [. search . returns null.

48 . Copyright © 2008.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. Infosys Technologies Ltd. SELECT TRIM (0 FROM 0009872348900) "TRIM Example" FROM DUAL. you must enclose it in single quotes. If trim_character or trim_source is a character literal.

SELECT SUBSTR('ABCDEFG'. substring_length)  The substring functions return a portion of string.SQL Functions . substring_length characters long.Substr Substr Syntax: SUBSTR (string. beginning at character position. SUBSTRB uses bytes instead of characters. position. Copyright © 2008.4) "Substring" FROM DUAL.3. Infosys Technologies Ltd. SUBSTR calculates lengths using characters as defined by the input character set. 49 .

 The following statement translates a license number. 50 . Copyright © 2008. All letters 'ABC. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'. . . Characters in char that are not in from_string are not replaced.Z' are translated to 'X' and all digits '012 .. '9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX') "License" FROM DUAL. 9' are translated to '9': SELECT TRANSLATE('2KRW229'.. 'from_string' . Infosys Technologies Ltd.SQL Functions . 'to_string' )  TRANSLATE returns char with all occurrences of each character in from_string replaced by its corresponding character in to_string.TRANSLATE  TRANSLATE ( 'char' .

51 . Infosys Technologies Ltd. fmt )  TO_CHAR converts date of DATE to a value of VARCHAR2 datatype in the format specified by the date format fmt. Copyright © 2008.SQL Functions – TO_CHAR TO_CHAR  TO_CHAR ( date . SELECT TO_CHAR(ts_col. 'DD-MON-YYYY HH24:MI:SS') FROM my_tab.

'dd/mm/yyyy') FROM DUAL. Infosys Technologies Ltd.SQL Functions – TO_DATE TO_DATE  To_date( char . 52 . fmt )  TO_DATE converts char in the format specified to a value of DATE datatype SELECT TO_DATE ('14/05/2007'. Copyright © 2008.

NVL returns expr2. 'Not Applicable') "COMMISSION" FROM employees WHERE last_name LIKE 'B%'.SQL Functions . substituting "Not Applicable" if the employee receives no commission: SELECT last_name. NVL returns expr1. Infosys Technologies Ltd. expr2 )  If expr1 is null. 53 .  The following example returns a list of employee names and commissions. If expr1 is not null. NVL(TO_CHAR(commission_pct). Copyright © 2008.NVL  NVL ( expr1 .

Infosys Technologies Ltd.Pseudocolumns  Behaves like a table column  Not stored in table  Cannot change value of pseudocolumn Copyright © 2008. 54 .

Infosys Technologies Ltd.Pseudocolumns  ROWID  ROWNUM Copyright © 2008. 55 .

Infosys Technologies Ltd. 56 .  SELECT ROWNUM. ENAME FROM EMP ORDER BY ename. ENAME FROM EMP. Copyright © 2008.Examples  SELECT ROWID.