You are on page 1of 58

CONTENTS: SQL STATEMENTS INTRODUCTION NORMALIZATION -WHAT IS NORMALIZATION -WHERE IT CAN BE USED -RULES FOR 1st NORMAL FORM

-RULES FOR 2nd NORMAL FORM -RULES FOR 3rd NORMAL FORM -ADVANTAGE OF NORMALIZATION -WORKING EXAMPLE CAPABILITIES OF SQL SELECT STATEMENTS -PROJECTION -SELECTION -JOINING SYNTAX FOR SELECT NULL VALUE -DEFINING A NULL VALUE -EXAMPLE -WHAT MEAN BY NULL VALUE DEFINING A COLUMN ALIAS -USE OF COLUMN ALIAS -EXAMPLE WHERE CLAUSE -LIMITING ROWS USING A SELECTION COMPARISON CONDITIONS = > >= < <= <> BETWEEN ..AND.... IN(SET) LIKE ISNULL

LOGICAL CONDITIONS -AND -OR -NOT USING THE ORDER BY CLAUSE -ASC -DESC SQL BUILT IN FUNCTIONS -ASCII -LENGTH -INITCAP -CONCAT -LOWER AND UPPER FUNCTIONS -INSTR -LTRIM AND RTRIM -REPLACE -SUBSTR -TRANSLATE -DATE FUNCTIONS -TO_DATE -TO_CHAR -ADD_MONTHS -MONTHS_BETWEEN -LAST_DAY -NEXT_DAY -SYSTIMESTAMP -NUMERIC FUNCTIONS -ABS -CEIL AND FLOOR -POWER -ROUND -SQRT -MOD -COUNT -SUM -SIGN -CONVERSION FUNCTIONS -CONVERT -TO_NUMBER -LOB FUNCTIONS -CLOB -BLOB -MISCELLANEOUS FUNCTIONS ANALYTICAL FUNCTIONS

AGGREGATE FUNCTIONS -TYPES OF GROUP FUNCTIONS -AVG -COUNT -MAX -STDDEV -SUM -VARIANCE -GUIDELINES OF USING GROUP FUNCTIONS -USING THE AVG AND SUM FUNCTIONS -USING THE MIN AND MAX FUNCTIONS -USING THE DISTINCT KEYWORD -COUNT FUNCTIONS -GROUP FUNCTIONS AND NULL VALUES -USING THE GROUP BY CLAUSE -USING THE GROUP BY CLAUSE ON MULTIPLE COLUMNS -ILLEGAL QUERIES -USING THE HAVING CLAUSE JOINS -LEFT OUTER JOIN -RIGHT OUTER JOIN -FULL OUTER JOIN -CROSS JOIN -EQUI JOIN -NATURAL JOIN -NATURAL INNER JOIN -INNER JOIN PRIMARY KEY AND FOREIGN KEY SUBQUERY -DEFINITION -USING A SUBQUERY TO SOLVE A PROBLEM -TYPES OF SUBQUERY -SINGLE ROW SUBQUERY -MULTI ROW SUBQUERY -EXECUTING SINGLE ROW SUBQUERY -MULTIPLE ROW SUBQUERY -WHERE SUBQUERY REQUIRED -PLACES FOR USAGE OF SUBQUERY SET OPERATORS -WHAT IS SET OPERATORS -UNION -UNION ALL -INTERSECT -MINUS -SET OPERATORS GUIDELINES -MATCHING THE SELECT STATEMENT DATA MANIPULATION LANGUAGE EXERCISE

SQL STATEMENTS: INTRODUCTION DATA MANIPULATION LANGUAGE: Retrieves data from the database, enters new rows, changes existing rows, and removes unwanted rows from tables in the database,respectively. Collectively, known as Data Manipulation Language(DML) SELECT INSERT UPDATE DELETE MERGE DATA DEFINITION LANGUAGE: Sets up, changes, and removes data structures from tables. Collectively known as Data Definition Language CREATE ALTER DROP RENAME TRUNCATE COMMIT GIVES OR REMOVES ACCESS RIGHTS TO BOTH THE ORACLE DATABASE AND THE STRUCTURES WITH IT. GRANT REVOKE MANAGES THE CHANGES MADE BY DML STATEMENTS. CHANGES TO THE DATA CAN BE GROUPED TOGETHER INTO LOGICAL TRASACTIONS COMMIT ROLLBACK SAVEPOINT

NORMALIZATION: WHAT IS NORMALIZATION: It is the process of designing a data model to efficiently store data in a database. The end result is that redundant data is eliminated and only data related to the attribute is stored within the table. WHERE IT CAN BE USED: For ex, let's say we store city,state and zipcode data for customers in the same table as other customer data with this approach, we keep repeating the city, state and zipcode data for all customers in the same area. Instead of storing the same data again and again, we could normalize the data and create a related table called city. The city table could then store city,state and zipcode along with Ids that relate back to the customer table, and we can eliminate those three columns from the customer table and add the new Id column. Normalization rules have been broken down into several forms. People have often refer to the 3Nf when talking about database design. This is what most database designers try to achieve. In the conceptual stages, data is segmented and normalized as much as possible, but for practical purposes those segments are changed during the evolution of data model Various normal forms may be introduced for different parts of handle the unique situations you may face. Whether you have heard about normalization or not, your database most likely follows some of the rules, unless all of your data is stored in one giant table. Rules for 1st Normal Form: Eliminate repeating groups. This table contains repeating groups of data in the software column. Computer Software ----------------------------1 Word 2 Access,Word,Excel 3 Word,Excel

To follow the 1st Normal form, We store one type of software for each record. Computer Software ------------------------------1 Word 2 Access 2 Word 3 Excel 3 Word 3 Excel Rules for 2nd Normal form (2NF) Eliminate redaunt dataplus 1NF. This table contains the name of the software which is reduant data Computer Software 1 Word 2 Access 2 Word 3 Excel 3 Word 3 Excel To Eliminate the redaudant storage of data, we create two tables. The 1st table stores a reference software ID to our new table that has a unique list of software titles. Computer SoftwareID ------------------------------------1 1 2 2 2 1 3 3 3 1 3 3 SoftwareID Software ----------------------------------1 Word 2 Access 3 Excel

Rules for 3rd Normalization Form: Eliminate columns not dependent on key plus 1NF and 2NF. In this table, we have data that contains both data about the computer and the user. COMPUTER USERNAME USER HIRE DATE PURCHASE -------------------------------------------------------------------------------------------------1 Joe 4/1/2000 5/1/2003 2 Mike 9/5/2003 6/15/2004 To Eliminate columns not dependant on the key, we would create the following tables. Now the data stored in the computer table is only related to the computer, and the data stored in the user table is only related to the user.

COMPUTER PURCHASE -------------------------------------------1 5/1/2003 2 6/15/2004 USER USERNAME USERHIREDATE -------------------------------------------------------------------------1 Joe 5/1/2003 2 Mike 6/15/2004 COMPUTER USER ------------------------------------1 1 2 1 Advantages of Normalization: Smaller database. By Eliminating duplicate data, we will be able to reduce the overall size of the database. Better Performance Narrow Tables:Having more fine-tuned tables allows our tables to have less columns and allows us to fit more records per data page. Fewer Indexes Per table mean faster maintanence tasks such as index rebuilds. Only joins tables that u need. Disadvantages of Normalization: More Tables to Join:By spreading out our data into more tables, we increase the need to join tables. Tables contain codes instead of real data repeated data is stored as codes rather than meaning of data... there is always a need to go to the lookup tables for the value.

Data Model is optimized for application not for ad-hoc queries. 1st Normal Form : No Repeating elements or groups of elements. 2nd Normal Form : No Partial dependencies on a concatenated key. 3rd Normal Form : No Dependencies on Non-Key Attribute Working Example: 1st Normal Form: To get rid of repeating elements. Order_id ord_date Cust.no Cust.Name Cust.Address Cust.city Cust.state ---------------------------------------------------------------------------------------------------------------------125 9/13/02 56 Foo,Inc 23 Mainst Teleburg Telebuug TX 125 9/13/02 56 Foo,Inc 23 Mainst Teleburg Telebuug TX 125 9/13/02 56 Foo,Inc 23 Mainst Teleburg Telebuug TX 126 9/14/02 2 Free, R US 1600 Pennysula Washington DC 126 9/14/02 2 Free, R US 1600 Pennysula Washington DC (continues) ItemID ItemDescrip ItemQty ItemPrice ItemTotal OrderTotalPrice --------------------------------------------------------------------------------------------563 56'' BlueFree 4 $3.50 $14.00 $82.00 851 Spline End 32 $0.25 $8.00 $82.00 652 3''Red Free 5 $12.00 $60.00 $82.00 563 56''BlueFree 500 $3.50 $1,750.00 $10,750.00 652 3''RedFree 750 $12.00 $9,000.00 $10,750.00 Two columns that together uniquely identify each row are order_id and item_id. No two rows have the same combination of order_id and item_id Therefore together they qualify to be used as the table's primary key. Even though they are in 2 different table columns, they are treated as a single thing. We call them concatenation. A value that uniquely identifies a row is called a primary key. When this value is made up of 2 or more columns,it is referred to as concatenated primary key. Two Requirements in 1st Norm Form: Atomicity Uniqueness Second Normal Form: Now we Test each table for Partial dependencies on a concatenated key. Each column in the table that is not part of the primary key must depend upon the entire concatenated key. If any column only depends upon one part of the concatenated key, then we say the entire table failed in second norm form.

Table:Order order_id order_date cust_id cust_name cust_addr cust_city cust_state ------------------------------------------------------------------------------------------------------------125 9/13/2002 56 Foo,inc 22 Mainst Thorp Thorpleburg TX 126 9/14/2002 2 Freens RVS 1600 Penniysula Washington DC Table:Order_items Order_id Item_id Item_desc Item_qty Item_price 125 563 56'' Blue Freen 4 $3.50 125 851 Spline End 32 $0.25 125 652 3'' Red Freen 5 $12.00 126 563 56'' Blue Freen 500 $3.50 126 652 3'' Red Freen 750 $12.00 Second Normal Form:PhaseII Now the order has single primary key Order_items has a concatenated primary key. Order_Items Order_id Item_id Item_qty -----------------------------------------------------125 125 125 126 126 Items Item_id 563 851 652 Item_Description 56''Blue Freen Spline End 3''Red Freen Item_Price $3.50 $0.25 $12.00 563 851 652 563 652 4 32 5 500 750

In 1st Pass, we removed the item_id key from the order table because of one-to-many relationship between orders and order_items. Therefore, item_qty field had to follow item_id into the new table Item_id was not removed from order-items tables because of many-to-one relationship between order-items and items. Each item can be associated with any number of lines on any number of invoices. Each Order_item is associated with one item, and only one. This is example for one-to-many relationships Each Order can have many items; Each items can belong to many orders(Many-Many Relationship) This time, we did not bring a copy of the order_id column into the new table. This is knowledge of the orders they are part of. The order-items table takes care of remember this relationship via the order_id and item_id column. Taken together those columns comprise the primary key of order_items, but taken separately they are foreign keys or pointer to rows in other tables. Third Normalization Form: The Problem of repeating customer information In our database, now stands, if a customer places more than one order than we have to input all of that customer's contact information again. This is because there are columns in the order table that rely on non-key attribute Consider order_date column Order date is meaning less without an order. (Order_id is the Key Attribute because it is primary key of the table) The Relation ship that has been established between the orders and customers table. Each order is made by one, and only one customer. Each Customer can make any number of orders including zero. Order_id 125 126 Order_id 125 125 125 126 126 Cust_id 56 2 Cust_id 56 2 Item_id 563 851 652 563 652 Cust_Name Foo, Inc Freen R vs Order_date 9/13/02 9/14/02 Item_qty 4 32 5 500 750 Cust_addr 23 Main st 1600 Penniysula Cust_City Thorpleburg Washington Cust_state TX DC

Item_id 563 851 652

Item_Desc 56'' Blue Freen Spline End(Xtra Large) 3'' Red Freen

Item_Price $3.50 $0.25 $12.00

CAPABILITIES OF SQL SELECT STATEMENTS PROJECTION : Choose the columns in a table that are returned by a query. Choose a few or as many of the columns as needed. SELECTION : Choose the rows in a table that are returned by a query. Various criteria can be used to restrict the rows that are retrieved. JOINING : Bring together data that is stored in different tables by specifying the link between them.

SYNTAX FOR SELECT: SELECT *|{DISTINCT column | expression [alias],....} FROM table; SELECT identifies the columns to be displayed. FROM identifies the table containing those columns. SELECT * DISTINCT column/expression alias FROM table is a list of one or more columns selects all columns suppresses duplicates. selects the named column or the expression gives selected columns different headings specifies the table containing the columns.

NULL VALUE: DEFINING A NULL VALUE: A null is a value that is unavailable, unassigned, unknown or inapplicable A null is not the same as a zero or a blank space. EXAMPLE: QUERY: Select last_name, job_id, salary,commission_pct From Employees; RESULT: LAST_NAME JOB_ID SALARY COMMISSION_PCT ------------------------------------------------------------------------------------Whalen AD_ASST 4400 (NULL) Harstein MK_MAN 13000 (NULL) Fay MK_REP 6000 (NULL) Zlotkey SA_MAN 10500 0.2 Abel SA_REP 11000 0.3 Taylor SA_REP 8600 0.2 Crant SA_REP 7000 0.15

WHAT MEAN BY NULL VALUES? A null is not same as a zero or a space. Zero is a number, and a space is a character. Columns of any data type can contain nulls. However, some constraints(NOT NULL and PRIMARY KEY)prevent nulls from being used in the column

DEFINING A COLUMN ALIAS: USE OF COLUMN ALIAS: Renames a column heading Is useful with calculations Immediately follows the column name(There can also be the optional AS keyword between the coulmn name and alias.) Requires double quotation marks if it contains spaces or special characters, or it is casesensitive. EXAMPLE: QUERY: SELECT last_name AS name, commission_pct comm FROM employee; RESULT: NAME COMM ------------------------------Whalen (null) Harstein (null) Fay (null) QUERY: SELECT last_name Name , salary*12 Annual Salary FROM employees; NAME ANNUAL SALARY ---------------------------------------------Whalen 52800 Harstein 156000 Fay 72000

WHERE CLAUSE: LIMITING ROWS USING A SELECTION: EMPLOYEES Employee_Id Last_Name Job_Id Department_Id --------------------------------------------------------------------------------------200 Whalen AD_ASST 10 201 Harstein MK_MAN 20 202 Fay MK_REP 20 205 Higgins AC_MGR 110 206 Gietz AC_ACCOUNT 110 100 King AD_PRES 90 101 Kochar AD_VP 90 ............. 178 Grant SA_REP (null) QUERY:(USING WHERE CLAUSE) SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90; RESULT: Employee_Id Last_Name Job_Id Department_Id --------------------------------------------------------------------------------------100 King AD_PRES 90 101 Kochar AD_VP 90 102 De Haan AD_VP 90

COMPARISON CONDITIONS: OPERATOR MEANING --------------------------------------------------------------------= Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> Not equal to Between .And........ Between two values(inclusive) IN(set) Match any of a list of values LIKE Match a character pattern IS NULL Is a null value USING BETWEEN CONDITION: SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 and 3500 LAST_NAME SALARY -----------------------------------Raja 3500 Davies 3100 Matos 2600 Vargas 2500 QUERY DESCRIPTION: The select statement in the slide returns rows from the EMPLOYEES table for any employee whose salary is between 2,500 and 3,500 USING THE IN CONDITION: To test for values in a specified set of values, use the IN condition. The IN condition is also known as membership condition. SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN(100,101,201); Employee_id Last_Name Salary Manager_Id -------------------------------------------------------------------------------201 Harstein 13000 100 101 Kochhar 17000 100 200 Whalen 4400 101 205 Higgins 12000 101 202 Fay 6000 201 The example displays employee numbers, last names, salaries, and manager's employee numbers for all the employees whose manager's employee number is 100,101,201.

USING THE LIKE CONDITION: Use the like condition to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers: % denotes zero or many characters. _ denotes one character. SELECT first_name FROM employees WHERE first_name LIKE 'S%'; FIRST_NAME ----------------------Shelley Steven USING NULL CONDITIONS The NULL conditions include the IS NULL condition and the IS NOT NULL condition A null value means the value is unavailable, unassigned, unknown, or inapplicable. We cannot test with = because a null cannot be equal or unequal to any value. To display last name, job ID, and commission for all employees who are not entitled to receive a commission, use the following SQL statement. SELECT last_name, job_id, commission_pct FROM employees WHERE commission_pct is NULL; LAST_NAME JOB_ID COMMISSION_PCT -------------------------------------------------------------------------Whalen AD_ASST (NULL) Hartstein MK_MAN (NULL) Fay MK_REP (NULL) Higgins AC_MGR (NULL)

LOGICAL CONDITIONS: AND requires both conditions to be true. SELECT employee_id, last_name,job_id, salary FROM employees WHERE salary>=10000 AND job_id LIKE '%MAN%' EMPLOYEE_ID LAST_NAME JOB_ID SALARY -----------------------------------------------------------------------------------201 Harstein MK_MAN 13000 149 Zlotkey SA_MAN 10500 USING THE OR OPERATOR: OR requires either condition to be true SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 OR job_id LIKE '%MAN% EMPLOYEE_ID LAST_NAME JOB_ID SALARY --------------------------------------------------------------------------------201 Harstein MK_MAN 13000 205 Higgins AC_MGR 12000 100 King AD_PRES 24000 USING THE NOT OPERATOR SELECT last_name, job_id FROM employees WHERE job_id NOT IN('IT_PROG', 'ST_CLERK', 'SA_REP'); LAST_NAME JOB_ID ----------------------------------------De Haan AD_VP Fay MK_REP Gietz AC_ACCOUNT RULES OF PRECEDENCE: OPERATOR MEANING ------------------------------------------------------1 Arithmetic operators 2 Concatenation operator 3 Comparison conditions 4 IS [NOT] NULL, LIKE, [NOT] IN 5 [NOT] BETWEEN 6 Not equal to 7 NOT logical condition 8 AND logical condition

USING THE ORDER BY CLAUSE: Sort retrieved rows with the ORDER BY clause: ASC : ascending order, default DESC : descending order The ORDER BY clause comes last in the SELECT statement. SELECT last_name, job_id,department_id, hire_date FROM employees ORDER BY hire_date; LAST_NAME JOB_ID DEPARTMENT_ID HIRE_DATE -------------------------------------------------------------------------------------------------King AD_PRES 90 17-JUN-87 Whalen AD_ASST 10 17-SEP-87 Kochhar AD_VP 90 21-SEP-89 Hunold IT_PROG 60 03-JAN-90

SQL BUILT-IN FUNCTIONS 1. ASCII : It returns ASCII value of a character EXAMPLE DECLARE grad number; BEGIN select grade into grad from salgrade where hisal=300 dbms_output.put_line(ascii(grad)); END; OUTPUT : Grade have value 4.Then it will return 52. 2. LENGTH : The function returns length of a string. Special charaters are also allowed.If we pass empty string it will return NULL EXAMPLE DECLARE nam varchar2(20); BEGIN select ename into nam from emp where empno = 7844 dbms_output.put_line(length(nam)); END; : The functions accepts the string value and converts the first letter of the string to caps

3.

INITCAP

EXAMPLE DECLARE nam varchar2(20); BEGIN select ename into nam from emp where empno = 7876; dbms_output.put_line(initcap(nam)); END; OUTPUT: Vignesh(V caps) 4. CONCAT : The CONCAT function concatenates two strings passed as parameters. This function appends the first string and second string.

EXAMPLE DECLARE nam varchar2(20); nam1 varchar2(20) := 'Welcomes You'; BEGIN select ename into nam from emp where empno = 7876; dbms_output.put_line(concat(nam,nam1)); END; OUTPUT Vijay Welcomes You 5. LOWER and UPPER Functions :This converts String into lower or upper case EXAMPLE

DECLARE nam varchar2(20); nam1 varchar2(20); BEGIN select dname into nam from dept where deptno = 20; dbms_output.put_line(LOWER(nam)); select dname into nam1 from dept where deptno = 50; dbms_output.put_line(UPPER(nam1)); END; OUTPUT accounts SPARE PARTS 6. INSTR : This function is used to find the position of a substring in the main string.This function returns zero in case the substring is not present in the main string. DECLARE plac VARCHAR2(20); BEGIN select loc into plac from dept where deptno = 20; dbms_output.put_line(plac); dbms_output.put_line(instr(plac,'A')); dbms_output.put_line(instr(plac,'A',1,1)); dbms_output.put_line(instr(plac,'A',1,2)); END; OUTPUT: DALLAS 2 2 5 ARGUMENTS OF INSTR FIRST ARGUMENT : STRING SECOND ARGUMENT : SUBSTRING THIRD ARGUMENT : STARTING POSITION FOURTH ARGUMENT : OCCURENCE OF THE SUBSTRING 7. LTRIM and RTRIM : LTRIM removes the empty space from the left side of the string RTRIM removes the empty space to the right side of the string. DECLARE nam varchar2(20):=' WELCOMES'; nam2 varchar2(20):='HELLO '; BEGIN dbms_output.put_line(ltrim(nam)); dbms_output.put_line(rtrim(nam2)); END OUTPUT: WELCOMES

HELLO 8 REPLACE : This function replaces all the occurrence of a substring with the replacement substring from main string.

This function is useful when we need to search and replace a particular sequence of characters with any other sequence of characters. DECLARE plac varchar2(20) BEGIN select loc into plac from dept where deptno=30; dbms_output.put_line(Replace(plac,'A','z')); END; OUTPUT: CHICzGO 9 SUBSTR : The SUBSTR function fetches the substring from the main string. EXAMPLE: DECLARE nam varchar2(20); BEGIN select ename into nam from emp where empno = 7844; dbms_output.put_line(substr(nam,2,4)); END; OUTPUT: If the Employee name is GANESH. The Result will be ANE TRANSLATE : The Translate replaces character set in a string with another set of characters. EXAMPLE: DECLARE e_job varchar2(20); BEGIN select job into e_job from emp where empno=7844; dbms_output.put_line(translate(e_job,'SLN','1BY')); END OUTPUT If job is SALESMAN, the result will be 1aBE1MAY DATE FUNCTIONS 1. TO_DATE : Function accepts a string and a format parameter as arguments and converts a string into date according to the format parameter DECLARE e_dat varchar2(20) :='121588'; BEGIN dbms_output.put_line(To_date(e_dat,'mm/dd/yy')); END; OUTPUT : 15-DEC-88 2. TO_CHAR : Funtions accepts a number or a date along with the format

10

11

parameter specified as an argument. DECLARE dat DATE; dat1 NUMBER := 20070818; BEGIN select dob into dat from employee where e_no=7840; dbms_output.put_line(dat); dbms_output.put_line(To_char(dat,'dd/mm/yyyy')); dbms_output.put_line(To_char(dat1,$9,999,9999')); END OUTPUT: 11-JUN-06 11/07/2006 $2,007,0818 3. ADD_MONTHS : Functions returns a new date with the specified number of months added to the date specified as input parameter. DECLARE dat DATE; BEGIN select doj into dat from employee where e_no=7840; dbms_output.put_line(add_months(dat,4)); END OUTPUT: Actual Result is 11-JULY-06 due to add months result becomes 11-OCT-06 4. MONTHS_BETWEEN : Functions returns the difference between two dates.Needs the start date and end date DECLARE dat DATE; dat1 DATE; BEGIN select doj into dat from employee where e_no=7840; select doj into dat1 from employee where e_no=7842; dbms_output.put_line(months_between(dat,dat1)) END OUTPUT: Actual Result is 11-JULY-06 and 11-SEP-06 months between these dates becomes 2. 5. LAST_DAY : Function accepts a date as a parameter and returns the last day of the month on the basis that parameter DECLARE dat DATE; BEGIN select DOJ into dat from employee where e_no=7844; dbms_output.put_line(dat); dbms_output.put_line(last_day(dat));

END OUTPUT: 11-MAR-06 31-MAR-06 6. NEXT_DAY : Function returns the next day in the date to the day specified in the date string. DECLARE dat DATE; BEGIN Select DOJ into dat from Employee where e_no=7842; dbms_output.put_line(NEXT_DAY(dat,'SATURDAY')); END OUTPUT: DOJ returns 15-AUG-07(WEDNESDAY). Next_day will calculate the date from wednesday to saturday.Then it attains the output as 18-AUG-07 7. SYSTIMESTAMP : The Function returns the time including fractions of seconds and time zone according to local database BEGIN dbms_output.put_line(systimestamp); END OUTPUT: 27-OCT-07 3.25.06.187000000 PM +5.30 12. NUMERIC FUNCTIONS 1. ABS : The ABS function returns the absolute value of the given value BEGIN dbms_output.put_line(abs(33.25)); dbms_output.put_line(abs(-15.45)); END OUTPUT:33.25 15.45(- OMMITED) 2. CEIL AND FLOOR :CEIL function returns the smallest integer value greater than or equal to the value specified. FLOOR function returns the largest integer value less than or equal to the value specified BEGIN dbms_output.put_line(ceil(13.25)); dbms_output.put_line(ceil(-45.95)); dbms_output.put_line(floor(10.12)); dbms_output.put_line(floor(-65.95)); END OUTPUT:14,-45,10,-66 POWER : The function returns the base value after calculating its power according to the other argument passed in this function.

3.

BEGIN dbms_output.put_line(power(10,3)); dbms_output.put_line(power(6.3,5)); END; OUTPUT:1000 9924.36543 4. ROUND: Function can have one or two parameters. First parameter is compulsory and second one is optional. The number whose value has to be rounded by some specific decimal points specified as the second parameter. BEGIN dbms_output.put_line(round(16.25648)); dbms_output.put_line(round(16.25648,3)); END OUTPUT: 16 16.256 SQRT :Function returns the square root value of the argument passed. BEGIN DBMS_OUTPUT.PUT_LINE(SQRT(16)); END; OUTPUT: 4

5.

6. MOD :Function returns reminder.Two arguments first argument is divident and second argument is divisor BEGIN DBMS_OUTPUT.PUT_LINE(MOD(16,3));/* FLOAT VALUES ALSO CAN GIVE END OUTPUT:1 7. COUNT :It returns total number of rows based on a particular query. DECLARE Total NUMBER; BEGIN Select count(*) into total from EMP; dbms_output.put_line(total); END 8. SUM : It returns the sum of the values specified in the expression as a parameters. DECLARE t_sal NUMBER; BEGIN select sum(sal) into t_sal from EMP; dbms_output.put_line(t_sal); END 9. SIGN : It returns 1 when number is greater than zero It returns 0 when number is less than zero

DECLARE e_sign NUMBER; BEGIN select e_sal into e_sign from from employee where e_no=7844; dbms_output.put_line(sign(e_sign)); dbms_output.put_line(sign(-4500)); END OUTPUT:1,-1 13. CONVERSION FUNCTIONS: Conversion function used to convert one datatype into another. CONVERT:The Convert function can accept 2 or 3 parameters. CONVERT (val,n_charset,o_charset); val represents the string value which has to be converted. n_charset represents character set which string value has to converted. o_charset represents character set of the val string value. TO_NUMBER:The function accepts the string value and returns the number value according to the format specified in the second argument EXAMPLE DECLARE con date; con1 varchar2(50):='4567825' BEGIN Select hiredate into con from emp where empno=7900; dbms_output.put_line(con); dbms_output.put_line(to_number(to_char(con,'ddmmyyyy'),'99999999')); dbms_output.put_line(to_number(con1,'9999999')); END; 14. LOB FUNCTIONS Lob function can store the value upto 4GB. Lob has two parts, one is LOB locator and another is LOB value. A database table stores the LOB locator which is in fact a pointer to the actual location on LOB value. FUNCTION BFILENAME EMPTY_BLOB EMPTY_CLOB DESCRIPTION Intializes BFILE large object column in the database table Returns empty locator of BLOB type. Returns empty locator of CLOB type.

BFILENAME The BFILENAME function is used to intialize the column of large object type in a database table to a point an external file or it returns the BFILE locator for the LOB binary file BFILENAME(dir_name,f_name); EMPTY_BLOB: This Method is used because the blob can then modified by inserting this blob into

the table and retrieving this blob into the table and retrieving it using select...For Update EMPTY_CLOB: This Method is used because the clob can then modified by inserting this clob into the table and retrieving this clob into the table and retrieving it using select...For Update EMPTY_BLOB , EMPTY_CLOB E_BIN BLOB := EMPTY_BLOB; E-ADD CLOB := EMPTY_CLOB; DECLARE pict bfile:=(bfilename('e:\picture','rose.gif') BEGIN insert into employee(e_pic)values(pict); update employee set e_pic = bfilename('e:\picture','flower.gif') END; 15. MISCELLANEOUS FUNCTIONS GREATEST, LEAST: Greatest function fetches higher value which passed in the argument Least function fetches lower value which passed in the argument. EXAMPLE: DECLARE e_dat DATE; BEGIN dbms_output.put_line(sysdate); dbms_output.put_line(greatest(10,5,20,36,2,1,50)); dbms_output.put_line(greatest(sysdate,'10-dec-2007','10-nov-2000') dbms_output.put_line(least(21,25,45,11,10,39)); dbms_output.put_line(least(sysdate,'10-oct-2007','10-jan-2000')); END; OUTPUT: 50 07-JAN-2011 10 10-JAN-2000 USER, UID : USER returns the name of current account, such as scott or sys,where as UID function returns the integer value to identify the user. EXAMPLE: DECLARE user_1 varchar2(20);

uid _1 number; BEGIN select user into user_1 from emp where empno=7900; select uid into uid_1 from emp where empno=7900; dbms_output.put_line(user_1); dbms_output.put_line(uid_1); END OUTPUT:SCOTT,5 ANALYTICAL FUNCTIONS: Count(*) over Partition, order by, Range unbounded Preceding Empno Ename Job Mgr Hiredate Sal comm Deptno -----------------------------------------------------------------------------------------------------------------7369 Smith Clerk 7962 17-Dec-80 800 20 7499 Alen Salesman 7698 20-Feb-81 1600 300 30 7521 Ward Salesman 7698 22-Feb-81 1250 500 7566 Jones Manager 7839 02-Apr-81 2975 20 7654 Martin Salesman 7698 28-Sep-81 1250 1400 30 7698 Blake Manager 7839 01-May-81 2850 7782 Clark Manager 7839 09-Jan-81 2450 10 7788 Scott Analyst 7566 09-Dec-82 3000 20 7739 King President 17-Nov-81 5000 30 7844 Turner Salesman 7698 08-sep-81 1500 20 7876 Adams Clerk 7788 12-jan-83 1100 20 7900 James Clerk 7698 03-Dec-81 950 30 7902 Ford Analyst 7566 03-Dec-81 3000 20 7934 Miller Clerk 7782 23-Jan-82 1300 10 QUERY: select * from (select deptno,ename,sal,rownumber() over(Partition by deptno order by sal desc)RN from emp)where rn<=3 RESULT: Deptno Ename Sal 10 King 5000 Clark 2450 Miller 1300 20 Scott Ford Jones Allen Blake Martin 3000 3000 2975 99.00 99.00 99.00 RN 1.00 2.00 3.00 1.00 2.00 3.00 1.00 2.00 3.00

30

ROW_NUMBER Function With an Ordering on Salary in Descending Order: Empno Ename HireDate Orig_Salary Curr_Salary R -------------------------------------------------------------------------------------------------------

1 2 3 4 5 6 7 8 9

Jason John Joe Tom Jane James Jodd Joke Jack

25-Jul-96 15-Jul-97 25-Jan-86 13-Sep-06 17-Apr-05 18-Jul-04 20-Jul-03 01-Jan-02 29-Aug-01

1234 2341 4321 2413 7654 5619 5438 8765 7896

8767 3456 5654 6787 4345 6546 7658 4543 1232

E W E W E W E W E

QUERY: Select Empno,Ename,Orig_salary,Row_Number() Over(Order By Orig_Salary DESC) toprank from Employee RESULT: Empno Ename Orig_Salary ToPrank -------------------------------------------------------------------8 Joke 8765 1 9 Jack 7896 2 5 Jane 7654 3 6 James 5679 4 7 Jodd 5438 5 3 Joe 4321 6 4 Tom 2413 7 2 John 2341 8 1 Jason 1234 9 AVG OVER AND AVG OVER ORDER BY: QUERY: Select Ename, Sal, Avg(Sal) over() from Emp; RESULT: Ename Sal Avg(sal) Over() -------------------------------------------------------------Smith 800 2073.21 Allen 1600 2073.21 Ward 1250 2073.21 Jones 2975 2073.21 Martin 1250 2073.21 Blake 2850 2073.21 Clark 2450 2073.21 Scott 3000 2073.21 King 5000 2073.21 Turner 1500 2073.21 Adams 1100 2073.21 James 950 2073.21 Ford 3000 2073.21 Miller 1300 2073.21

AVERAGE ORDER BY QUERY: Select Ename,Sal,Avg(sal) over(Order by Ename) From Emp Order by Ename RESULT: Ename Sal Avg(sal)Over(Order by Ename) --------------------------------------------------------------------------------------Adams 1100 1100 Allen 1600 1350 Blake 2850 1850 Clark 2450 2000 Ford 3000 2200 James 950 1991.67 Jones 2975 2132.14 King 5000 2490.63 Martin 1250 2352.78 Miller 1300 2247.50 Scott 3000 2315.91 Smith 800 2189.58 Turner 1500 2136.54 Ward 1250 2073.21 SELECT THE TOP5 QUERY: Select LastName,Hire_Date From Employees where RowNum<6 Order by Hire_date Select LastName,Hire_Date From(Select Last_Name,Hire_Date From Employees Order By Hire_Date) Where RowNum<=5 LastName Hire_Date ----------------------------------------------Kyte 16-Jun-98 Lawson 01-Jan-02 Wells 01-Jan-02 Bliss 01-Jan-02 Viper 13-Jun-08

AGGREGATE DATA USING THE GROUP FUNCTIONS TYPES OF GROUP FUNCTIONS: AVG COUNT MAX MIN STDDEV SUM VARIANCE GUIDELINES OF USING GROUP FUNCTIONS DISTINCT makes the function consider only nonduplicate values; ALL makes it consider every value, including duplicates. The default is ALL and therefore does not need to be specified. The data types for the functions with an expr argument may be CHAR, VARCHAR2, NUMBER, or DATE. All group functions ignore null values. To substitute a value for null values, use the NVL, NVL2, or COALESCE functions. TABLE: Emp_No Salary --------------------------------------1 3000 2 5000 3 9000 4 12000 5 15000 USING THE AVG AND SUM FUNCTIONS: SELECT AVG(salary), MAX(salary), MIN(salary),SUM(salary) FROM employees WHERE job_id LIKE '%REP%' AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY) ------------------------------------------------------------------------------------------------------------8800 15000 3000 44000 TABLE: Emp_No Salary Hire_Date -------------------------------------------------------------1 3000 17-JUN-87 2 5000 29-JAN-2000 3 9000 28-JUN-99 4 12000 15-JAN-90 5 15000 20-JUN-89 USING THE MIN AND MAX FUNCTIONS: SELECT MIN(hire_date), MAX(hire_date)

FROM employees;

MIN(HIRE_DATE) MAX(HIRE_DATE) ---------------------------------------------------------------------17-JUN-87 29-JAN-2000 USING THE DISTINCT KEYWORD: COUNT(*) returns the number of rows in a table. SELECT COUNT(*) FROM employees WHERE department_id = 50; COUNT(expr) returns the number of rows with non-null values for expr: SELECT COUNT(commission_pct) FROM employees WHERE department_id =80; COUNT FUNCTION: The COUNT function has three formats: COUNT(*) COUNT(expr) COUNT(DISTINCT expr) COUNT(*): Returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the columns. If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfy the condition in the WHERE clause. COUNT(expr): It returns the number of non-null values that are in the column identified by expr. COUNT(DISTINCT expr): It returns the number of unique, non-null values that are in the column identified by expr. GROUP FUNCTIONS AND NULL VALUES: Emp_Id Commission_PCT 1 1000 2 4000 3 null 4 5000

Group functions ignore null values in the column. SELECT AVG(commission_pct) FROM employees; AVG(COMMISSION_PCT) --------------------------------------3,333.33 The NVL function forces group functions to include null values. SELECT AVG(NVL(commission_pct,0)) FROM employees; AVG(NVL(COMMISSION_PCT,0)) ---------------------------------------------2500 DESCRIPTION OF QUERY: 1. The average is calculated based on only those rows in the table where a valid value is stored in the COMMISSION_PCT column. The average is calculated as the total commission that is paid to all employees divided by the number of employees receiving a commission(four). 2. The average is calculated based on all rows in the table, regardless of whether null values are stored in the COMMISSION_PCT column. The average is calculated as the total commission that is paid to all employees divided by the total number of employees in the company (20). USING THE GROUP BY CLAUSE: All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. SELECT department_id,AVG(salary) FROM employees GROUP BY department_id; DEPARTMENT_ID AVG(SALARY) -----------------------------------------------------------(null) 7000 20 9500 90 19333.33333333333 110 10150 50 3500 80 10033.333333333333 10 4400 60 6400 USING THE GROUP BY CLAUSE ON MULTIPLE COULMNS: SELECT department_id dept_id,job_id,SUM(salary) FROM employees GROUP BY department_id, job_id;

DEPT_ID JOB_ID SUM(SALARY) -----------------------------------------------------------------110 AC_ACCOUNT 8300 90 AD_VP 34000 50 ST_CLERK 11700 80 SA_REP 19600 QUERY DESCRIPTION: The SELECT clause specifies the column to be retrieved: Department number in the EMPLOYEES table. Jobid in the Employees table The sum of all the salaries in the group that we specified in the GROUP BY clause The FROM clause specifies the tables that the database must access: the EMPLOYEES table. The GROUP BY clause specifies how we must group the rows First, the rows are grouped by department number. Second, the rows are grouped by job ID in the department number groups. ILLEGAL QUERIES: Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. SELECT department_id, COUNT(last_name) FROM employees; CORRECT METHOD: SELECT department_id, count(last_name) FROM employees GROUP BY department_id; DEPARTMENT_ID COUNT(LAST_NAME) -------------------------------------------------------------------------(null) 1 20 2 90 3 110 2 50 5 80 3 10 1 60 3 USING THE HAVING CLAUSE: If we restrict rows based on the result of a group function, we must have a GROUP BY clause as well as the HAVING clause. SELECT department_id, MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary)>10000 DEPARTMENT_ID MAX(SALARY) ------------------------------------------------------------------

20 90 110 80 JOINS

13000 24000 12000 11000

WHEN JOINS CAN BE USED? Sometimes we need to use data from more than one table. EXAMPLE: Employee Ids exist in the EMPLOYEES table. Department Ids exist in both the EMPLOYEES and DEPARTMENTS tables. Department names exists in the DEPARTMENTS table. To .Produce the report, we need to link the EMPLOYEES and DEPARTMENTS tables and access data from both of them. JOIN CONDITIONS: Most join queries contain atleast 1 join condition,either in the from clause or in the where clause. The join condition compares 2 columns, each from different table. To execute a join, oracle database combines pairs of rows, each row containing one row from each table, for which the join condition evaluates to true. The columns in the joins condition need not also appear in the select list. To execute a join of 3 or more tables oracle 1st joins 2 of the tables based on the join condition comparing their columns and then join the result to another table based on join condition containing columns of the joined tables and the new table. A where clause that contains a join condition can also contain other condition that refer to columns of only one table. These condition can further restrict the rows returned by join query. USE OF + OPERATOR IN JOIN CONDITION: The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can contain one or more columns marked with the (+) operator. A Where condition contain the + operator cannot be combined with other condition using the logical operator A where condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an expression. TableName:Employee Empno Ename 122 Alison 123 James 104 Celia 105 Robert 116 Linda 117 David 108 Jode

Hiredate 21-mar-96 12-dec-78 24-Oct-82 15-Jan-84 30-Jul-87 31-Dec-90 17-Sep-96

Orig_Salary 45000 23000 53000 31000 43000 78000 21000

Curr_salary 48000 32000 58000 36000 53000 85000 29000

R E W E W E W E

TableName:job Empno JobTitle 101 Painter 122 Tester 123 Dedicator 104 Chemist 105 Accountant 116 Manager 117 Programmer 108 Developer

Left outer joins: DEFINITION: Suppose we join 2 tables A and B. Left outer join returns all record from the Table A(left table )plus matching records in the tableB. It means the result of the SQL left outer join always contain the records in the Table A even no matching record found in the table B plus matching records in the tableB. SYNTAX Select * from Table A Left Outer Join Table B on Join Condition Where Row_Condition QUERY: select e.ename, j.jobtitle from Employee e, job j where e.empno = j.empno(+) Result Ename Jobtitle Alison Tester James Dedicator Celia Chemist Robert Accountant Linda Manager David Programmer Jode Developer DESCRIPTION OF QUERY: Retrieves all rows from EMPLOYEE table, which is the table on LEFT even if there is no match in the JOB table. Right Outer joins: DEFINITION: It returns all records from Table B(table in the right side),even no matching record found in the table A, plus matching records in the table A. SYNTAX Select column_list from Table A Right Outer Join Table B on Join Condition Where Row_Condition

QUERY: select e.ename, j.jobtitle from Employee e, job j where e.empno(+) = j.empno Result: Ename Alison James Celia Robert Linda David Jode Jobtitle Tester Dedicator Chemist Accountant Manager Programmer Developer Painter DESCRIPTION OF QUERY: Retrieves all rows from JOB table, which is the table on Right even if there is no match in the Employee tables. Full outer joins: DEFINITION: It combines both leftouter join and rightouter join therefore it returns all records from both tables. SYNTAX SELECT column_list From table_A Full Outer join Table_B on join condition where row_condition Select e.ename,j.jobtitle from Employee e Full outer join job j using(empno); Result: Ename JobTitle Alison Tester James Dedicator Celia Chemist Robert Accountant Linda Manager David Programmer Jode Developer Painter DESCRIPTION OF QUERY: It retrieves all rows in a Employee table even if there is no match in the EMPLOYEE table. It retrieves all rows in a Job table even if there is no match in the JOB table. WHAT IS CROSS JOIN: A cross product if formed when: A join condition is omitted. A join condition is invalid All rows in the first table are joined to all rows in the second table To avoid a cross product , always include a valid join condition

DEFINITION: If 2 tables in a join query have no join condition, then oracle database return their cross product. Oracle combines each row of one table with each row of the other. Cross joins: Select * from Employees cross join job; Empno Ename Hiredate Orig_Salary Curr_salary R Empno JobTitle --------------------------------------------------------------------------------------------------------------122 Alison 21-mar-96 45000 48000 E 101 Painter 123 James 12-dec-78 23000 32000 W 101 Painter 104 Celia 24-Oct-82 53000 58000 E 101 Painter 105 Robert 15-Jan-84 31000 36000 W 101 Painter 116 Linda 30-Jul-87 43000 53000 E 101 Painter 117 David 31-Dec-90 78000 85000 W 101 Painter 108 Jode 17-Sep-96 21000 29000 E 101 Painter 122 Alison 21-mar-96 45000 48000 E 122 Tester 123 James 12-dec-78 23000 32000 W 122 Tester 104 Celia 24-Oct-82 53000 58000 E 122 Tester 105 Robert 15-Jan-84 31000 36000 W 122 Tester 116 Linda 30-Jul-87 43000 53000 E 122 Tester 117 David 31-Dec-90 78000 85000 W 122 Tester 108 Jode 17-Sep-96 21000 29000 E 122 Tester 122 Alison 21-mar-96 45000 48000 E 123 Dedicator 123 James 12-dec-78 23000 32000 W 123 Dedicator 104 Celia 24-Oct-82 53000 58000 E 123 Dedicator 105 Robert 15-Jan-84 31000 36000 W 123 Dedicator 116 Linda 30-Jul-87 43000 53000 E 123 Dedicator 117 David 31-Dec-90 78000 85000 W 123 Dedicator 108 Jode 17-Sep-96 21000 29000 E 123 Dedicator 122 Alison 21-mar-96 45000 48000 E 104 Chemist 123 James 12-dec-78 23000 32000 W 104 Chemist 104 Celia 24-Oct-82 53000 58000 E 104 Chemist 105 Robert 15-Jan-84 31000 36000 W 104 Chemist 116 Linda 30-Jul-87 43000 53000 E 104 Chemist 117 David 31-Dec-90 78000 85000 W 104 Chemist 108 Jode 17-Sep-96 21000 29000 E 104 Chemist 122 Alison 21-mar-96 45000 48000 E 105 Accountant 123 James 12-dec-78 23000 32000 W 105 Accountant 104 Celia 24-Oct-82 53000 58000 E 105 Accountant 105 Robert 15-Jan-84 31000 36000 W 105 Accountant 116 Linda 30-Jul-87 43000 53000 E 105 Accountant 117 David 31-Dec-90 78000 85000 W 105 Accountant 108 Jode 17-Sep-96 21000 29000 E 105 Accountant 122 Alison 21-mar-96 45000 48000 E 116 Manager 123 James 12-dec-78 23000 32000 W 116 Manager 104 Celia 24-Oct-82 53000 58000 E 116 Manager 105 Robert 15-Jan-84 31000 36000 W 116 Manager 116 Linda 30-Jul-87 43000 53000 E 116 Manager

117 108 122 123 104 105 116 117 108 122 123 104 105 116 117 108

David Jode Alison James Celia Robert Linda David Jode Alison James Celia Robert Linda David Jode

31-Dec-90 17-Sep-96 21-mar-96 12-dec-78 24-Oct-82 15-Jan-84 30-Jul-87 31-Dec-90 17-Sep-96 21-mar-96 12-dec-78 24-Oct-82 15-Jan-84 30-Jul-87 31-Dec-90 17-Sep-96

78000 21000 45000 23000 53000 31000 43000 78000 21000 45000 23000 53000 31000 43000 78000 21000

85000 29000 48000 32000 58000 36000 53000 85000 29000 48000 32000 58000 36000 53000 85000 29000

W E E W E W E W E E W E W E W E

116 116 117 117 117 117 117 117 117 108 108 108 108 108 108 108

Manager Manager Programmer Programmer Programmer Programmer Programmer Programmer Programmer Developer Developer Developer Developer Developer Developer Developer

Self Joins DEFINITION:Self Join is a join of table to itself. Empno Ename Job Mgr Hiredate Sal Comm 7369 Smith Clerk 7902 1980-Dec-17 800 7499 Allen Salesman 7698 1981-Feb-20 1600 300 7521 Ward Salesman 7698 1981-Feb-22 1250 500 7566 Jones Manager 7839 1981-Apr-02 2975 7654 Martin Salesman 7698 1981-Sep-28 1250 1400 7698 Blake Manager 7839 1981-May-01 2850 7782 Clark Manager 7839 1981-Jun-09 2450 7788 Scott Analyst 7566 1982-Dec-09 3000 7839 King President 1981-Nov-11 5000 7844 Turner Salesman 7698 1981-Sep-08 1500 0 7876 Adams Clerk 7788 1981-Jan-12 1100 7900 James Clerk 7698 1981-Dec-03 950 7902 Ford Analyst 7566 1981-Dec-03 3600 7934 Miller Clerk 7782 1982-Jan-23 1300

Deptno 20 30 30 20 30 30 10 20 10 30 20 30 20 10

QUERY: Select e.ename||'Works for'||m.ename from emp e, emp m where e.mgr = m.empno JOINING A TABLE TO ITSELF: Sometimes we need to join a table to itself. To find the name of each employee's manager, we need to join the EMPLOYEES table to itself, or perform a self join. Result: Ename||'Works For'||M.Ename Ford Works For Jones Scott Works For Jones James Works For Blake Turner Works For Blake Martin Works For Blake

Ward Allen Miller Adams Clark Blake Jones Smith

Works For Blake Works For Blake Works For Clark Works For Scott Works For king Works For king Works for king Works for Ford

EQUI JOIN DEFINITION: An Equi join is a join with a join condition containing an equality operator. An Equii join combines rows that have equivalent values for the specified columns. Employee_Id Employee_N Job Manager_Id Start_dat Salary Comm Dept.Id ---------------------------------------------------------------------------------------------------------------------7369 Smith Clerk 7902 17-Dec-80 800 20 7499 Allen Salesman 7698 20-Feb-81 1600 300 30 7521 Ward Manager 7698 22-Feb-81 1250 500 30 7566 Jones Manager 7839 02-Apr-81 2975 20 7654 Martin Salesman 7698 28-Sep-81 1250 1400 30 7698 Blake Manager 7839 01-May-81 2850 30 7782 Clark Manager 7839 09-Jun-81 2450 10 7788 Scott Analyst 7566 09-Dec-82 3000 20 7839 King President 17-Nov-81 5000 10 7844 Turner Salesman 7698 08-Sep-81 1500 30 7876 Adams Clerk 7788 12-Jan-83 1100 20 7900 James Clerk 7698 03-Dec-81 950 30 7902 Ford Analyst 7566 03-Dec-81 3000 20 7934 Miller Clerk 7782 23-Jan-82 1300 10 Department_Id Department_Name Location ------------------------------------------------------------------------10 Accounting Newyork 20 Research Dallas 30 Sales Chicago 40 Operations Boston Query: Select Employee.Employee_Id, Employee.Start_Date, Employee.Employee_Name, Department.Dept_Name, Department.Location From Employee,Department Where Department.Department_Id=Employee.Department_Id Result: Employee_Id Start_Date Employee_N Dept_Name Location ------------------------------------------------------------------------------------------7369 17-Dec-80 Smith Research Dallas 7499 20-Feb-81 Allen Sales Chicago 7521 22-Feb-81 Ward Sales Chicago

7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

02-Apr-81 28-Sep-81 01-May-81 09-Jun-81 09-Dec-82 17-Nov-81 08-Sep-81 12-Jan-83 03-Dec-81 03-Dec-81 23-Jan-82

Jones Martin Blake Clark Scott King Turner Adams James Ford Miller

Research Sales Sales Accounting Research Accounting Sales Research Sales Research Accounting

Dallas Chicago Chicago Newyork Dallas Newyork Chicago Dallas Chicago Dallas Newyork

Two-Table Equi-Joins For Ids: Table:Emp Emp_Id (Primary) Name -----------------------------------------------1 Tom 2 Jack 3 Mary 4 Bill 5 Cat 6 Victor Table:Empexam Employee_Id(Primary) Exam_Id(Primary) Mark Taken Comment --------------------------------------------------------------------------------------------------------1 1 55 1 Satisfactory 1 2 73 1 Good Result 2 3 44 1 Hard 2 5 39 0 Simple 2 6 63 1 QUERY: Select empexam.ExamId,empexam.Mark,emp.empname from empexam join emp on empexam.empid=emp.empid order by examid ExamId Mark EmpName -----------------------------------------------1 55 Tom 2 73 Tom 3 44 Jack 5 39 Jack 6 63 Jack Two-Table,Equi_Joins with where clause and order by clause: Select empexam.ExamId,empexam.Mark,emp.name as empname from empexam join emp on empexam.empid = emp.empid where empexam.mark>=80 order by examid; Natural Join: DEFINITION:

Natural join clause is based on all columns in the two tables that have the same name. It selects rows from the two tables that have equal values in all matched columns. If the columns having the same names have different data types, an error is returned. QUERY: Select Employee_ID,Last_Name,Department_Name from Employees natural join departments where department_name='purchasing' (Primary key) (Foreign key) Employee_ID Last_Name Hire_Date Job_ID Department_ID ------------------------------------------------------------------------------------------------------1001 Lawson 01-Jan-02 MGR 1 1002 Wells 01-Jan-02 DBA 2 1003 Bliss 01-Jan-02 PROG 3 1004 Kyte 13-Jun-98 MGR 4 1005 Viper 10-Jun-08 PROG 1 1006 Beck 10-Jun-08 PROG 2 1007 Java 10-Jun-08 PROG 3 1008 Oracle 10-Jun-08 DBA 4 (Primary key) Department_ID Department_NA ----------------------------------------------------1 Data Group 2 Purchasing 3 Call center 4 Communication RESULT: Employee_Id Last_Name Department_NA ------------------------------------------------------------------------1002 Wells Purchasing 1006 Beck Purchasing

NATURAL INNER JOIN: Dept_No Dept_Name Mgr_No --------------------------------------------------------1 Design 1 2 Sales 1 3 Development 1 EmpNo LastName FirstName Salary Deptno -----------------------------------------------------------------------------------1 Anderson Nancy 3.75 2 2 Last First 7.75 2 3 Wash Georgia 11.50 1 4 Bush Dave 21.65 1 5 Will Robin 24.65 1

6 7 8 9

Pete Roke Horry Bar

Mona John Tedi Candi

9 10.00 13.00 12.00

2 3 3 3

Select Dept_Name,Last_Name from department natural inner join employee select d.deptname,e.lastname from department d,employee e where d.deptno=e.deptno Dept_Name Sales Sales Design Design Design Sales Development Development Development Last_Name Anderson Last Wash Bush Will Pete Roke Horry Bar

Three Inner Join Query: Select d.depart_name,e.last_name from departments d inner join employees e on d.department_id=e.department_id where d.department_id=1 Department_NA Last_Name ------------------------------------------------DataGroup Lawson DataGroup Dillson Inner join Primary key and foreign key: Select e.employee_id,e.last_name,d.department_name from employees e inner join departments d on e.department_id=d.department_id where e.job_id='DBA' (Primary key) (Foreign key) Employee_ID Last_Name Hire_Date Job_ID Department_ID --------------------------------------------------------------------------------------------------------1001 Lawson 01-Jan-02 MGR 1 1002 Wells 01-Jan-02 DBA 2 1003 Bliss 01-Jan-02 PROG 3 1004 Kyte 13-Jun-98 MGR 4 1005 Viper 10-Jun-08 PROG 1 1006 Beck 10-Jun-08 PROG 2 1007 Java 10-Jun-08 PROG 3 1008 Oracle 10-Jun-08 DBA 4 (Primary key) Department_ID Department_NA ----------------------------------------------------1 Data Group

2 3 4

Purchasing Call center Communication

RESULT: Employee_Id Last_Name Department_NA -------------------------------------------------------------------------1002 Wells Purchasing 1008 Oracle Communication

SUBQUERY: DEFINITION: A Subquery is a query that is nested inside a select,insert,update or delete statement or inside another subquery. A Subquery can return a set of rows or just one row to its parent query. A Scalar subquery is a query that returns exactly one value; A single row, with a single column. A Scalar Subqueries can be used in most places in a Sql statement where we will use an expression or a literal value. A Subquery within a Statement must be executed before the parent query that calls it, in order that the result of the subquery can be passed to the parent. Using a Subquery to Solve a Problem: Suppose we want to write a query to find out who earns a salary greater than Abel's Salary. To solve this problem, we need two queries: one to find how much Abel earns, and a second query to find who earns more than that amount. We can solve this problem by combining the two queries, placing one query inside the other query. The inner query(or subquery) returns a value that is used by the outer query (or main query). Using a subquery is equivalent to performing two sequential queries and using the result of the first query as the search value in the second query. QUERY: SELECT last_name, salary FROM employees WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel'); TYPES OF SUBQUERIES: Single-Row Subquery : Queries that return only one row from the inner SELECT statement Multi-Row Subquery : Queries that return more than one row from the inner SELECT statement. EXECUTING SINGLE-ROW SUBQUERIES: SELECT last_name, job_id, salary FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE employee_id = 141) AND salary > (SELECT salary FROM employees WHERE employee_id = 143) RESULT:

LAST_NAME JOB_ID SALARY ---------------------------------------------------------Raja ST_CLERK 3500 Davies ST_CLERK 3100 MULTIPLE ROW SUBQUERIES: Return More than one row Use multiple-row comparison operators Operator Meaning ---------------------------------------------------------------------------------------------IN Equal to any member in the list ANY Compare value to each value returned by the subquery ALL Compare value to every value returned by the subquery. USING THE ANY OPERATOR IN MULTIPLE-ROW SUBQUERIES: SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary < ANY (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG'; EMPLOYEE_ID LAST_NAME JOB_ID SALARY -----------------------------------------------------------------------------------144 Vargas ST_CLERK 2500 143 Matos ST_CLERK 2600 .......... 206 Gietz AC_ACCOUNT 8300 176 Taylor SA_REP 8600

Where Subquery Required? In the Select list used for column Projection. In the From clause In the Where clause In the Having clause Places For Usage of Subqueries: 1. Write a query that uses subqueries in the column projection list. The query will report on the current number of departments and staff. Select Sysdate , (Select count(*) from Departments)Dept_count, (Select count(*) from Employees)Emp_Count from dual; 2. Write a query to identify all the employees who are managers. This will Require using a subquery in the where clause to select all the employees whose Employee_Id appears as a Manager_Id Select Last_Name from Employees where (Employee_Id in (Select Manager_id from Employees)); Write a query to identify the highest salary paid in each country. This will require using a subquery in the From Clause Select Max(Salary), Country_id from (Select salary, department_id,location_id, country_id from Employees Natural Join Departments Natural join locations)group by country_id A Corrleated Subquery Reference one or more columns in a outer query: Select empno,mgr,ename,sal from emp outer where sal>(select avg(sal) from emp inner where inner.empno =outer.mgr); Using Exists with a Corrleated Subquery: Empno Ename Job MGR 7369 Smith Clerk 7902 7499 Allen Salesman 7698 7521 Ward Salesman 7698 7566 Jones Manager 7839 7654 Martin Salesman 7698 7698 Blake Manager 7839 7782 Clark Manager 7839 7788 Scott Analyst 7566 7839 King President 7844 Turner Salesman 7698 7876 Adams Clerk 7788 7900 James Clerk 7698 7902 Ford Analyst 7566 7934 Miller Clerk 7782 Select Empno, Ename from emp outer where exists (select empno from emp inner where

3.

4.

5.

inner.mgr=outer.empno); RESULT: EMPNO ENAME 7902 Ford 7698 Blake 7839 King 7566 Jones 7788 Scott 7782 Clark 6. Using NotExists with a Subquery: Select Empno, Ename from emp outer where not exists (select empno from emp inner where inner.mgr=outer.empno); RESULT: EMPNO ENAME 7844 Turner 7521 Ward 7654 Martin 7499 Allen 7934 Miller 7369 Smith 7876 Adams 7900 James Select From Virtual Table(Subquery) With Rownum QUERY: Select id Emp#,First_Name Name,Salary Salary,RowNum Rank from ( Select id, First_Name,Salary From Employee order by salary Desc)

7.

RESULT: ID FIRST_NAME SALARY RANK ---------------------------------------------------------------------04 Celia 2334.78 1 02 Alison 2334.78 2 03 James 2334.78 3 08 James 2334.78 4 05 Robert 2334.78 5 06 Linda 2334.78 6 07 David 2334.78 7 08 Jason 1234.56 8

SET OPEATORS: what is set operators: Set operators combine the results of two or more component queries into one result. Queries containing set operators are called compound queries. Operator Returns ----------------------------------------------------------------------------------------------------------UNION All distinct rows selected by either query. UNION ALL All rows selected by either query, including all duplicates INTERSECT All distinct rows selected by both queries MINUS All distinct rows that are selected by the first SELECT statement and not selected in the second SELECT statement UNION OPERATOR: The Union operator returns all rows that are selected by either query. Use the UNION operator to return all rows from multiple tables and eliminate any duplicate rows. GUIDELINES: The number of columns and the data types of the columns being selected must be identified in all the SELECT statements used in the query. The names of the columns need not be identical. UNION operates over all of the columns being selected. NULL values are not ignored during duplicate checking. The IN operator has a higher precedence than the UNION operator. By default, the output is sorted in ascending order of the first column of the SELECT clause. USING THE UNION OPERATOR DISPLAY THE CURRENT AND PREVIOUS JOB DETAILS OF ALL EMPLOYEES. DISPLAY EACH COMBINATION ONLY ONCE. Select Employee_id, job_id,department_id From Employees UNION Select Employee_id,job_id,department_id From job_history EMPLOYEE_ID JOB_ID DEPARTMENT_ID ----------------------------------------------------------------------------------200 AC_ACCOUNT 90 200 AD_ASST 10 200 AD_ASST 90

UNION: Use To Connect Column data and Summary Data ID First_Name Salary --------------------------------------------------01 Jason 1234.56 02 Alison 6661.78 03 James 6544.78 04 Celia 2344.78 05 Robert 2344.78 06 Linda 4322.78 07 David 7897.78 08 James 1232.78 QUERY: Select First_Name, Salary From Employee Union Select 'The Average ........', Average from (Select Avg(Salary) average From Employee); First_Name Salary --------------------------------------Alison 6661.78 Celia 2344.78 David 7897.78 James 1232.78 James 6544.78 Jason 1234.78 Linda 4322.78 Robert 2334.78 The Average ........ 4071.7525 UNION ALL OPERATOR The UNION ALL operator returns results from both queries, including all duplications. GUIDELINES The guidelines for UNION and UNION ALL are the same, with the following two exceptions that pertain to UNION ALL Unlike UNION, duplicate rows are not eliminated and the output is not sorted by default The DISTINCT keyword cannot be used. SELECT employee_id, job_id, department_id FROM employees UNION ALL SELECT employee_id, job_id, department_id FROM job_history ORDER BY employee_id;

EMPLOYEE_ID JOB_ID DEPARTMENT_ID ----------------------------------------------------------------------------100 AD_PRES 90 101 AD_VP 90 200 AD_ASST 10 200 AC_ACCOUNT 90 200 AD_ASST 90 206 AC_ACCOUNT 110 INTERSECT OPERATOR: INTERSECT operator to return all rows that are common to multiple queries. GUIDELINES: The number of columns and the datatypes of the columns being selected by the SELECT statements in the queries must be identical in all the SELECT statements used in the query. The names of the columns need not be identical. Reversing the order of the intersected tables does not alter the result. INTERSECT does not ignore NULL values. QUERY: SELECT employee_id, job_id FROM employees INTERSECT SELECT employee_id, job_id FROM job_history EMPLOYEE_ID JOB_ID ---------------------------------------------176 SA_REP 200 AD_ASST SET OPERATOR GUIDELINES: The expressions in the select lists of the queries must match in number and datatype. Queries that use UNION,UNION ALL,INTERSECT, and MINUS operators in their WHERE clause must have the same number and type of columns in their SELECT list . For Example SELECT employee_id,department_id FROM employees WHERE (employee_id, department_id) IN(SELECT employee_id,department_id FROM employees UNION SELECT employee_id, department_id FROM job_history); The ORDER BY clause: Can appear only at the very end of the statement. Will accept the column name, an alias, or the positional notation

The Column name or alias, if used in an ORDER BY clause, must be from the first SELECT list. Set operators can be used in subqueries. MATCHING THE SELECT STATEMENT: Using the UNION operator, display the employee ID,job ID, and salary of all employees SELECT employee_id, job_id, salary FROM employees UNION SELECT employee_id, job_id, 0 FROM job_history; EMPLOYEE_ID JOB_ID SALARY -----------------------------------------------------------------100 AD_PRES 24000 101 AC_ACCOUNT 0 205 AC_MGR 12000 206 AC_ACCOUNT 8300

DATA MANIPULATION LANGUAGE: A DML statement is executed when we: Add new rows to a table. Modify existing rows in a table. Remove existing rows from a table. A transaction consists of a collection of DML statements that form a logical unit of work. INSERTING ROWS WITH NULL VALUES: Implicit Method : Omit the column from the column list. INSERT INTO departments (department_id,department_name)(30,'Purchasing') Explicit Method : Specify the NULL keyword in the VALUES clause. INSERT INTO departments(100,'Finance',NULL,NULL); INSERTING SPECIAL VALUES: The SYSDATE function records the current date and time. QUERY: INSERT INTO employees (employee_id, first_name, last_name, email, phone_number,hire_date, job_id,salary,commission_pct,manager_id,department_id) VALUES(113,'Louis','Popp','LPOPP','515.124.4567',SYSDATE,'AC_ACCOUNT',6900,NULL, 205,100); COPYING FROM OTHER TABLES: Write our INSERT statement with a Subquery: QUERY: INSERT INTO sales reps(id, last_name, salary,commission_pct) SELECT employee_id, last_name, salary, commission_pct WHERE job_id LIKE '%REP%' Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the Subquery. UPDATE STATEMENTS: UPDATING TWO COLUMNS WITH A SUBQUERY: Update employee 114's job and salary to match that of employee 205 UPDATE employees SET job_id = (SELECT job_id FROM employees WHERE employee_id =205), salary = (SELECT salary FROM employees

WHERE employee_id = 205) WHERE employee_id =114;

DELETING ROWS FROM A TABLE DELETING ROWS BASED ON ANOTHER TABLE Use subqueries in DELETE statements to remove rows from a table based on values from another table. DELETE FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE department_name LIKE '%Public%');

EXERCISE PRACTICAL WORK: 1. List all Employees younger than Jones? Ename Bdate ---------------------------------------Jason 1965-12-18 Jerry 1966-11-19 Jord 1967-09-22 Mary 1986-09-22 Jones 1969-08-23 QUERY: Select ename, init, bdate from Employees where bdate>(Select bdate from Employees where Ename='Jones') 2. List all Employees who attended SQL Course and JAVA course? Attendee Course BeginDate --------------------------------------------------------------Ganesh SQL 1999-04-12 Vignesh SQL 1999-12-13 Ramesh SQL 1999-12-13 Ganesh Java 1999-08-10 Ramesh Java 1999-12-13 QUERY: Select attendee from registrations where course='JAVA' and attendee in(Select Attendee from registers where course='SQL') 3. Extract a Subset of the Results: Select username,score from(Select username,score from MyTable order by score DESC)t where rownum<=10; 4. How many Products by Department with Correlated Sub queries? Table Name: Department DepartmentID Name Description ------------------------------------------------------------------1 Software Coding 2 Hardware Building

QA

Testing

Table Name:Category CategoryID DepartmentID Name Description -------------------------------------------------------------------------------1 1 Local InTown 2 1 Remote Telecommute 3 2 Masks By bits 4 3 Wireless Not Connected 5 3 Wired Connected Table Name:Product ProductID Name Description Price ImagePath Soldout Promotion -------------------------------------------------------------------------------------------------------------------1 Pen Ball pen 5.99 Pen.jpg 1 0 2 Ruler Long 14.99 Ruler.jpg 0 0 3 Desk ComputerDesk 5.99 Desk.jpg 0 1 4 Pc Notebook 45.99 Pc.jpg 0 1 5 Mouse Wireless 9.99 Mouse.jpg 1 0 6 Keyboard Keyboard 3.75 Keyboard.jpg 0 0 ProductID CategoryID -------------------------------------1 3 2 1 2 3 3 3 4 1 5 2 6 3 6 4 7 4 8 5 QUERY: Select D.Name As Department,COUNT(P.Name)As Products from Department D, Product P where ProductID IN(Select ProductID from ProductCategory inner join category on Product category.categoryId=Category.CategoryID Where Category.DepartmentID=D.DepartmentID)Group by D.Name order by D.Name. OUTPUT: Hardware 4 QA 1 Software 3

5. How do u tell the difference between a Null value and a blank string if a retrieve all the rows? ID FIRST_NAME LAST_NAME ---------------------------------------------------------01 Jason Martin 02 Alison Mathews 03 James Smith 04 Celia Rice 05 Robert Black 06 Linda Green 07 David Larry 08 Cat Select id, First_name, Last_name, NVL(First_name,'Unknown First name ') from employee 6. Reference alias name in order-by clause: au_id au_fname au_lname state ---------------------------------------------------------------A01 S B NY A02 W H CO A03 H H CA A04 K H CA A05 C K NY A06 K CA A07 P O FL Select au_fname As FirstName, au_lname As LastName , State From Employees Orderby state Asc, LastName Asc, FirstName Asc First_Name Last_Name ST -------------------------------------------------H H CA K H CA K CA W H CO P O FL S B NY C K NY 7. Sort By Index Ascending and Descending Select Au_Fname, Au_Lname, City, State from Employees order by 4 asc,2 desc Au_Fname Au_Lname City ST ---------------------------------------------------------------------

K H W P C S

K H H H O K B

Palo Alto San Francisco San Francisco Boston Sarasota Newyork Boston

CA CA CA CO FL NY NY

8. Add Aggregate function in Order-by Clause: City Salary ---------------------------------Toronto 1234.56 Vancouver 6661.78 Vancouver 6544.78 Vancouver 2344.78 Vancouver 2344.78 Newyork 4322.78 Newyork 7897.78 Vancouver 1232.78 Select city, Avg(Salary) Avg_Salary from Employee Group by salary orderby avg(salary) desc; 9. ROWNUM ID FIRST_NAME SALARY CITY -------------------------------------------------------------------01 Jason 1234.56 Toronto 02 Alison 6661.78 Vancouver 03 James 6544.78 Vancouver 04 Celia 2344.78 Vancouver 05 Robert 2344.78 Vancouver 06 Linda 4322.78 Newyork 07 David 7897.78 Newyork 08 James 1232.78 Vancouver QUERY: Select Rownum, First_Name From Employee RESULT: RowNum City ---------------------------------1 Toronto 2 Vancouver 3 Vancouver 4 Vancouver 5 Vancouver 6 Newyork

7 8

Newyork Vancouver

JOINS ARE MORE FASTER THAN SUBQUERIES: Using Subquery: Select id,alias from mos_categories where id in (Select Distinct catid from mos_content) Using Join: Select distinct mos_content.catid, mos_categories.alias from mos_content,mos_categories where mos_content.catid = mos_categories.id

You might also like