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 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 . we create two tables. We store one type of software for each record.To follow the 1st Normal form. 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. Computer Software ------------------------------1 Word 2 Access 2 Word 3 Excel 3 Word 3 Excel Rules for 2nd Normal form (2NF) Eliminate redaunt dataplus 1NF. Only joins tables that u need.. and the data stored in the user table is only related to the user. By Eliminating duplicate data. 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. Now the data stored in the computer table is only related to the computer.. .Rules for 3rd Normalization Form: Eliminate columns not dependent on key plus 1NF and 2NF. we have data that contains both data about the computer and the user. Disadvantages of Normalization: More Tables to Join:By spreading out our data into more tables. In this table. 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. Tables contain codes instead of real data repeated data is stored as codes rather than meaning of data. we will be able to reduce the overall size of the database. we increase the need to join tables. 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. we would create the following tables. 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. Two Requirements in 1st Norm Form: Atomicity Uniqueness Second Normal Form: Now we Test each table for 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. 1st Normal Form : No Repeating elements or groups of elements.00 652 3''RedFree 750 $12.Name Cust.00 563 56''BlueFree 500 $3.00 $9.00 $82. they are treated as a single thing.00 652 3''Red Free 5 $12. A value that uniquely identifies a row is called a primary key. Each column in the table that is not part of the primary key must depend upon the entire concatenated key.50 $14.25 $8. When this value is made up of 2 or more columns. 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.00 $82.Address Cust.750. Even though they are in 2 different table columns.00 Two columns that together uniquely identify each row are order_id and item_id. We call them concatenation.00 $82.50 $1.750. 2nd Normal Form : No Partial dependencies on a concatenated key.00 $10.no Cust. R US 1600 Pennysula Washington DC 126 9/14/02 2 Free.00 851 Spline End 32 $0.Inc 23 Mainst Teleburg Telebuug TX 125 9/13/02 56 Foo. Order_id ord_date Cust.Inc 23 Mainst Teleburg Telebuug TX 125 9/13/02 56 Foo.Inc 23 Mainst Teleburg Telebuug TX 126 9/14/02 2 Free.000.it is referred to as concatenated primary key.state ---------------------------------------------------------------------------------------------------------------------125 9/13/02 56 Foo.city Cust. then we say the entire table failed in second norm form. If any column only depends upon one part of the concatenated key.00 $10. R US 1600 Pennysula Washington DC (continues) ItemID ItemDescrip ItemQty ItemPrice ItemTotal OrderTotalPrice --------------------------------------------------------------------------------------------563 56'' BlueFree 4 $3.750.00 $60. . 25 $12.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.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.50 125 851 Spline End 32 $0.Table:Order order_id order_date cust_id cust_name cust_addr cust_city cust_state ------------------------------------------------------------------------------------------------------------125 9/13/2002 56 Foo.00 563 851 652 563 652 4 32 5 500 750 .00 126 563 56'' Blue Freen 500 $3.50 126 652 3'' Red Freen 750 $12.25 125 652 3'' Red Freen 5 $12. Each item can be associated with any number of lines on any number of invoices. we did not bring a copy of the order_id column into the new table. Each Customer can make any number of orders including zero. 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 . This is knowledge of the orders they are part of. Each items can belong to many orders(Many-Many Relationship) This time. and only one customer. and only one. The order-items table takes care of remember this relationship via the order_id and item_id column.In 1st Pass. now stands. 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 order is made by one. Therefore. Third Normalization Form: The Problem of repeating customer information In our database. Taken together those columns comprise the primary key of order_items. 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. This is example for one-to-many relationships Each Order can have many items. 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. (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. we removed the item_id key from the order table because of one-to-many relationship between orders and order_items. but taken separately they are foreign keys or pointer to rows in other tables. Each Order_item is associated with one item. 25 $12.50 $0.Item_id 563 851 652 Item_Desc 56'' Blue Freen Spline End(Xtra Large) 3'' Red Freen Item_Price $3.00 . job_id. JOINING : Bring together data that is stored in different tables by specifying the link between them. salary. selects the named column or the expression gives selected columns different headings specifies the table containing the columns. SELECT * DISTINCT column/expression alias FROM table is a list of one or more columns selects all columns suppresses duplicates. SYNTAX FOR SELECT: SELECT *|{DISTINCT column | expression [alias].. NULL VALUE: DEFINING A NULL VALUE: A null is a value that is unavailable. Various criteria can be used to restrict the rows that are retrieved. 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.15 .2 Crant SA_REP 7000 0.3 Taylor SA_REP 8600 0. Choose a few or as many of the columns as needed..commission_pct From Employees. SELECTION : Choose the rows in a table that are returned by a query. FROM identifies the table containing those columns. SELECT identifies the columns to be displayed.} FROM table.. unknown or inapplicable A null is not the same as a zero or a blank space.2 Abel SA_REP 11000 0.CAPABILITIES OF SQL SELECT STATEMENTS PROJECTION : Choose the columns in a table that are returned by a query. unassigned.. EXAMPLE: QUERY: Select last_name. RESULT: NAME COMM ------------------------------Whalen (null) Harstein (null) Fay (null) QUERY: SELECT last_name “Name” .WHAT MEAN BY NULL VALUES? A null is not same as a zero or a space. commission_pct comm FROM employee. Zero is a number.) Requires double quotation marks if it contains spaces or special characters. or it is casesensitive. 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. NAME ANNUAL SALARY ---------------------------------------------Whalen 52800 Harstein 156000 Fay 72000 . However. Columns of any data type can contain nulls. salary*12 “Annual Salary” FROM employees. and a space is a character. EXAMPLE: QUERY: SELECT last_name AS name. last_name... department_id FROM employees WHERE department_id = 90. job_id........ 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 .. 178 Grant SA_REP (null) QUERY:(USING WHERE CLAUSE) SELECT employee_id...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 …. 500 and 3..201. use the IN condition.101.. 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...500 USING THE IN CONDITION: To test for values in a specified set of values.101. manager_id FROM employees WHERE manager_id IN(100... last names.COMPARISON CONDITIONS: OPERATOR MEANING --------------------------------------------------------------------= Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> Not equal to Between …. salary. . SELECT employee_id.And. 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.201). The IN condition is also known as membership condition. salaries. 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.. last_name. and manager's employee numbers for all the employees whose manager's employee number is 100. We cannot test with = because a null cannot be equal or unequal to any value. or inapplicable. To display last name. 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. job_id. SELECT first_name FROM employees WHERE first_name LIKE 'S%'. unassigned. LAST_NAME JOB_ID COMMISSION_PCT -------------------------------------------------------------------------Whalen AD_ASST (NULL) Hartstein MK_MAN (NULL) Fay MK_REP (NULL) Higgins AC_MGR (NULL) . SELECT last_name. commission_pct FROM employees WHERE commission_pct is NULL. _ denotes one character. job ID. unknown. use the following SQL statement. and commission for all employees who are not entitled to receive a commission.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. SELECT employee_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. LIKE. job_id FROM employees WHERE job_id NOT IN('IT_PROG'. last_name. 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.job_id. [NOT] IN 5 [NOT] BETWEEN 6 Not equal to 7 NOT logical condition 8 AND logical condition . 'ST_CLERK'. 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. job_id. 'SA_REP').LOGICAL CONDITIONS: AND requires both conditions to be true. last_name. department_id. SELECT last_name.USING THE ORDER BY CLAUSE: Sort retrieved rows with the ORDER BY clause: ASC : ascending order. job_id. hire_date FROM employees ORDER BY hire_date. default DESC : descending order The ORDER BY clause comes last in the SELECT statement. 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 . nam1)).Then it will return 52. BEGIN select ename into nam from emp where empno = 7844 dbms_output. BEGIN select ename into nam from emp where empno = 7876. END.If we pass empty string it will return NULL EXAMPLE DECLARE nam varchar2(20). nam1 varchar2(20) := 'Welcomes You'.put_line(initcap(nam)). END. 2. dbms_output. OUTPUT : Grade have value 4. END. CONCAT : The CONCAT function concatenates two strings passed as parameters.SQL BUILT-IN FUNCTIONS 1. : The functions accepts the string value and converts the first letter of the string to caps 3. OUTPUT: Vignesh(V caps) 4. BEGIN select grade into grad from salgrade where hisal=300 dbms_output. END. OUTPUT Vijay Welcomes You 5. LENGTH : The function returns length of a string. BEGIN select ename into nam from emp where empno = 7876. dbms_output. EXAMPLE DECLARE nam varchar2(20).put_line(ascii(grad)). ASCII : It returns ASCII value of a character EXAMPLE DECLARE grad number. Special charaters are also allowed. LOWER and UPPER Functions :This converts String into lower or upper case EXAMPLE .put_line(length(nam)).put_line(concat(nam. INITCAP EXAMPLE DECLARE nam varchar2(20). This function appends the first string and second string. dbms_output.put_line(plac). 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. BEGIN dbms_output.put_line(instr(plac. DECLARE nam varchar2(20):=' WELCOMES'.put_line(ltrim(nam)). dbms_output.put_line(instr(plac.1. dbms_output.This function returns zero in case the substring is not present in the main string.1. END. OUTPUT accounts SPARE PARTS 6.1)).'A')). nam1 varchar2(20). select dname into nam1 from dept where deptno = 50.put_line(rtrim(nam2)).'A'. INSTR : This function is used to find the position of a substring in the main string. dbms_output.DECLARE nam varchar2(20). 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. END. dbms_output.put_line(LOWER(nam)).'A'.put_line(instr(plac. DECLARE plac VARCHAR2(20).put_line(UPPER(nam1)). BEGIN select loc into plac from dept where deptno = 20. END OUTPUT: WELCOMES . BEGIN select dname into nam from dept where deptno = 20. nam2 varchar2(20):='HELLO '. dbms_output. dbms_output.2)). This function is useful when we need to search and replace a particular sequence of characters with any other sequence of characters. the result will be 1aBE1MAY DATE FUNCTIONS 1. BEGIN select job into e_job from emp where empno=7844.put_line(To_date(e_dat. EXAMPLE: DECLARE nam varchar2(20).2.put_line(substr(nam. EXAMPLE: DECLARE e_job varchar2(20). OUTPUT: If the Employee name is GANESH. dbms_output.HELLO 8 REPLACE : This function replaces all the occurrence of a substring with the replacement substring from main string. OUTPUT: CHICzGO 9 SUBSTR : The SUBSTR function fetches the substring from the main string.'SLN'.'A'. END.put_line(translate(e_job. OUTPUT : 15-DEC-88 2. END. The Result will be ANE TRANSLATE : The Translate replaces character set in a string with another set of characters.'mm/dd/yy')). END. dbms_output. dbms_output. TO_CHAR : Funtions accepts a number or a date along with the format 10 11 . BEGIN select ename into nam from emp where empno = 7844. DECLARE plac varchar2(20) BEGIN select loc into plac from dept where deptno=30.put_line(Replace(plac. 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'.'z')). END OUTPUT If job is SALESMAN. BEGIN dbms_output.4)).'1BY')). put_line(dat). DECLARE dat DATE. BEGIN select DOJ into dat from employee where e_no=7844. dbms_output.put_line(To_char(dat1. MONTHS_BETWEEN : Functions returns the difference between two dates. 5. END OUTPUT: Actual Result is 11-JULY-06 due to add months result becomes 11-OCT-06 4. ADD_MONTHS : Functions returns a new date with the specified number of months added to the date specified as input parameter.$9. dat1 NUMBER := 20070818. END OUTPUT: 11-JUN-06 11/07/2006 $2. dat1 DATE.put_line(add_months(dat. dbms_output. 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. dbms_output.put_line(last_day(dat)). dbms_output.put_line(dat). BEGIN select doj into dat from employee where e_no=7840.0818 3. select doj into dat1 from employee where e_no=7842.007.put_line(To_char(dat.'dd/mm/yyyy')).dat1)) END OUTPUT: Actual Result is 11-JULY-06 and 11-SEP-06 months between these dates becomes 2. BEGIN select dob into dat from employee where e_no=7840. .parameter specified as an argument. dbms_output.Needs the start date and end date DECLARE dat DATE.4)). dbms_output. BEGIN select doj into dat from employee where e_no=7840.put_line(months_between(dat. DECLARE dat DATE.9999')). dbms_output.999. put_line(floor(10. dbms_output.25.10.12)).25)). . CEIL AND FLOOR :CEIL function returns the smallest integer value greater than or equal to the value specified.25 15.95)).put_line(abs(-15.put_line(NEXT_DAY(dat. SYSTIMESTAMP : The Function returns the time including fractions of seconds and time zone according to local database BEGIN dbms_output.45)). END OUTPUT:14. DECLARE dat DATE.OMMITED) 2.put_line(abs(33.-66 POWER : The function returns the base value after calculating its power according to the other argument passed in this function.95)). dbms_output. ABS : The ABS function returns the absolute value of the given value BEGIN dbms_output. dbms_output.put_line(ceil(13. NEXT_DAY : Function returns the next day in the date to the day specified in the date string.-45.45(.put_line(ceil(-45. END OUTPUT: DOJ returns 15-AUG-07(WEDNESDAY). dbms_output. BEGIN Select DOJ into dat from Employee where e_no=7842.25)).187000000 PM +5. Next_day will calculate the date from wednesday to saturday. 3.END OUTPUT: 11-MAR-06 31-MAR-06 6.06.30 12.put_line(systimestamp). NUMERIC FUNCTIONS 1.put_line(floor(-65.Then it attains the output as 18-AUG-07 7. END OUTPUT: 27-OCT-07 3. END OUTPUT:33. FLOOR function returns the largest integer value less than or equal to the value specified BEGIN dbms_output. dbms_output.'SATURDAY')). First parameter is compulsory and second one is optional. END OUTPUT: 16 16.put_line(round(16. dbms_output. SUM : It returns the sum of the values specified in the expression as a parameters. dbms_output.put_line(t_sal). The number whose value has to be rounded by some specific decimal points specified as the second parameter. END. BEGIN Select count(*) into total from EMP.put_line(round(16.256 SQRT :Function returns the square root value of the argument passed. OUTPUT: 4 5. BEGIN dbms_output./* FLOAT VALUES ALSO CAN GIVE END OUTPUT:1 7.3)).25648.3)).put_line(power(6. SIGN : It returns 1 when number is greater than zero It returns 0 when number is less than zero .PUT_LINE(MOD(16. DECLARE Total NUMBER.BEGIN dbms_output.put_line(total).3. END 9. MOD :Function returns reminder.25648)). COUNT :It returns total number of rows based on a particular query. END. 6. OUTPUT:1000 9924.5)).PUT_LINE(SQRT(16)).put_line(power(10.Two arguments first argument is divident and second argument is divisor BEGIN DBMS_OUTPUT. dbms_output.36543 4. DECLARE t_sal NUMBER. dbms_output.3)). END 8. BEGIN select sum(sal) into t_sal from EMP. ROUND: Function can have one or two parameters. BEGIN DBMS_OUTPUT. o_charset).'9999999')). Lob has two parts. FUNCTION BFILENAME EMPTY_BLOB EMPTY_CLOB DESCRIPTION Intializes BFILE large object column in the database table Returns empty locator of BLOB type. dbms_output. LOB FUNCTIONS Lob function can store the value upto 4GB. CONVERT (val.n_charset. val represents the string value which has to be converted. BEGIN select e_sal into e_sign from from employee where e_no=7844. END OUTPUT:1. 14.put_line(sign(-4500)). 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.f_name). A database table stores the LOB locator which is in fact a pointer to the actual location on LOB value.put_line(to_number(to_char(con. o_charset represents character set of the val string value. EMPTY_BLOB: This Method is used because the blob can then modified by inserting this blob into . n_charset represents character set which string value has to converted. dbms_output. END.'99999999')).put_line(to_number(con1. CONVERSION FUNCTIONS: Conversion function used to convert one datatype into another.DECLARE e_sign NUMBER. dbms_output.-1 13.'ddmmyyyy'). one is LOB locator and another is LOB value. CONVERT:The Convert function can accept 2 or 3 parameters. dbms_output. con1 varchar2(50):='4567825' BEGIN Select hiredate into con from emp where empno=7900. Returns empty locator of CLOB type. dbms_output. 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.put_line(sign(e_sign)).put_line(con). 39)).20.put_line(least(sysdate.gif') BEGIN insert into employee(e_pic)values(pict).For Update EMPTY_BLOB .gif') END.put_line(greatest(10.45.2. update employee set e_pic = bfilename('e:\picture'.11..put_line(greatest(sysdate.'rose.'flower. OUTPUT: 50 07-JAN-2011 10 10-JAN-2000 USER. BEGIN dbms_output. EXAMPLE: DECLARE e_dat DATE.50)).put_line(sysdate)... UID : USER returns the name of current account. E-ADD CLOB := EMPTY_CLOB.'10-oct-2007'. dbms_output.where as UID function returns the integer value to identify the user.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. DECLARE pict bfile:=(bfilename('e:\picture'.'10-jan-2000')).5. dbms_output.1.put_line(least(21.'10-nov-2000') dbms_output.'10-dec-2007'.10. 15. MISCELLANEOUS FUNCTIONS GREATEST. such as scott or sys. LEAST: Greatest function fetches higher value which passed in the argument Least function fetches lower value which passed in the argument.25.the table and retrieving this blob into the table and retrieving it using select. END. . EMPTY_CLOB E_BIN BLOB := EMPTY_BLOB. dbms_output.. EXAMPLE: DECLARE user_1 varchar2(20).36. dbms_output.sal.uid _1 number.ename. order by.put_line(uid_1). END OUTPUT:SCOTT.00 1.00 30 ROW_NUMBER Function With an Ordering on Salary in Descending Order: Empno Ename HireDate Orig_Salary Curr_Salary R ------------------------------------------------------------------------------------------------------- .00 1.00 2.5 ANALYTICAL FUNCTIONS: Count(*) over Partition.00 3.00 3.00 99. select uid into uid_1 from emp where empno=7900.00 3.00 2.00 2.00 99.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. 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.put_line(user_1). dbms_output. BEGIN select user into user_1 from emp where empno=7900.00 RN 1. 21 Allen 1600 2073.Ename.21 Turner 1500 2073.21 Martin 1250 2073.21 King 5000 2073.21 Jones 2975 2073. RESULT: Ename Sal Avg(sal) Over() -------------------------------------------------------------Smith 800 2073.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.21 Ward 1250 2073.21 Adams 1100 2073.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. Sal.21 Blake 2850 2073.21 Miller 1300 2073.21 Ford 3000 2073.21 James 950 2073.Orig_salary.21 . Avg(Sal) over() from Emp.21 Scott 3000 2073.21 Clark 2450 2073. 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 .58 Turner 1500 2136.67 Jones 2975 2132.21 SELECT THE TOP5 QUERY: Select LastName.54 Ward 1250 2073.Sal.91 Smith 800 2189.Hire_Date From(Select Last_Name.Hire_Date From Employees where RowNum<6 Order by Hire_date Select LastName.78 Miller 1300 2247.50 Scott 3000 2315.14 King 5000 2490.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.63 Martin 1250 2352.AVERAGE ORDER BY QUERY: Select Ename. 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). TABLE: Emp_No Salary --------------------------------------1 3000 2 5000 3 9000 4 12000 5 15000 USING THE AVG AND SUM FUNCTIONS: SELECT AVG(salary).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. The default is ALL and therefore does not need to be specified. VARCHAR2. NUMBER. MAX(hire_date) . MIN(salary). or COALESCE functions. use the NVL. ALL makes it consider every value. including duplicates. All group functions ignore null values. NVL2. or DATE. The data types for the functions with an expr argument may be CHAR. To substitute a value for null values. MAX(salary). If a WHERE clause is included in the SELECT statement. COUNT(expr): It returns the number of non-null values that are in the column identified by expr.FROM employees. including duplicate rows and rows containing null values in any of the columns. non-null values that are in the column identified by expr. COUNT(DISTINCT expr): It returns the number of unique. 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. GROUP FUNCTIONS AND NULL VALUES: Emp_Id Commission_PCT 1 1000 2 4000 3 null 4 5000 . 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. COUNT(expr) returns the number of rows with non-null values for expr: SELECT COUNT(commission_pct) FROM employees WHERE department_id =80. SELECT COUNT(*) FROM employees WHERE department_id = 50. COUNT(*) returns the number of rows that satisfy the condition in the WHERE clause. SELECT AVG(commission_pct) FROM employees.333. The average is calculated based on all rows in the table. AVG(NVL(COMMISSION_PCT. regardless of whether null values are stored in the COMMISSION_PCT column. . AVG(COMMISSION_PCT) --------------------------------------3.job_id. SELECT AVG(NVL(commission_pct.Group functions ignore null values in the column. job_id. 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 total number of employees in the company (20). 2.0)) FROM employees. DEPARTMENT_ID AVG(SALARY) -----------------------------------------------------------(null) 7000 20 9500 90 19333.SUM(salary) FROM employees GROUP BY department_id.AVG(salary) FROM employees GROUP BY department_id. SELECT department_id.333333333333 10 4400 60 6400 USING THE GROUP BY CLAUSE ON MULTIPLE COULMNS: SELECT department_id dept_id. The average is calculated as the total commission that is paid to all employees divided by the number of employees receiving a commission(four).33333333333 110 10150 50 3500 80 10033.0)) ---------------------------------------------2500 DESCRIPTION OF QUERY: 1. USING THE GROUP BY CLAUSE: All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.33 The NVL function forces group functions to include null values. SELECT department_id. SELECT department_id. CORRECT METHOD: SELECT department_id. we must have a GROUP BY clause as well as the HAVING clause. COUNT(last_name) FROM employees. the rows are grouped by department number. 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. ILLEGAL QUERIES: Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary)>10000 DEPARTMENT_ID MAX(SALARY) ------------------------------------------------------------------ . count(last_name) FROM employees GROUP BY department_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. 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. the rows are grouped by job ID in the department number groups. Second. The columns in the joins condition need not also appear in the select list. we need to link the EMPLOYEES and DEPARTMENTS tables and access data from both of them. 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. The join condition compares 2 columns. 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. an arbitrary expression can contain one or more columns marked with the (+) operator.either in the from clause or in the where clause. Department Ids exist in both the EMPLOYEES and DEPARTMENTS tables. A where clause that contains a join condition can also contain other condition that refer to columns of only one table.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.Produce the report. JOIN CONDITIONS: Most join queries contain atleast 1 join condition. not to an arbitrary 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 . each from different table. However. EXAMPLE: Employee Ids exist in the EMPLOYEES table. To execute a join. To . USE OF + OPERATOR IN JOIN CONDITION: The (+) operator can be applied only to a column. each row containing one row from each table. oracle database combines pairs of rows. Department names exists in the DEPARTMENTS table. for which the join condition evaluates to true. These condition can further restrict the rows returned by join query. ename.even no matching record found in the table A. Right Outer joins: DEFINITION: It returns all records from Table B(table in the right side).jobtitle from Employee e. 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.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. which is the table on LEFT even if there is no match in the JOB table. SYNTAX Select column_list from Table A Right Outer Join Table B on Join Condition Where Row_Condition .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. job j where e. Left outer join returns all record from the Table A(left table )plus matching records in the tableB. j. plus matching records in the table A. SYNTAX SELECT column_list From table_A Full Outer join Table_B on join condition where row_condition Select e.jobtitle from Employee e.ename.empno(+) = j. It retrieves all rows in a Job table even if there is no match in the JOB table. j. 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. always include a valid join condition .QUERY: select e.ename. job j where e. which is the table on Right even if there is no match in the Employee tables. WHAT IS CROSS JOIN: A cross product if formed when: − A join condition is omitted. Full outer joins: DEFINITION: It combines both leftouter join and rightouter join therefore it returns all records from both tables.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.jobtitle from Employee e Full outer join job j using(empno).j. − 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 . Cross joins: Select * from Employees cross join job.DEFINITION: If 2 tables in a join query have no join condition. Oracle combines each row of one table with each row of the other. then oracle database return their cross product. 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 . we need to join the EMPLOYEES table to itself.Ename Ford Works For Jones Scott Works For Jones James Works For Blake Turner Works For Blake Martin Works For Blake .ename from emp e. To find the name of each employee's manager. or perform a self join. 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.empno JOINING A TABLE TO ITSELF: Sometimes we need to join a table to itself. emp m where e.ename||'Works for'||m.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.mgr = m. Result: Ename||'Works For'||M. Department.Start_Date.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 .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.Department Where Department.Dept_Name. Employee.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.Department_Id=Employee.Location From Employee. Department. An Equii join combines rows that have equivalent values for the specified columns.Employee_Id.Employee_Name. Employee_Id Employee_N Job Manager_Id Start_dat Salary Comm Dept. Employee. empname from empexam join emp on empexam. Natural Join: DEFINITION: .empexam.Mark.emp.empid=emp.empid where empexam.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.Mark.emp.Equi_Joins with where clause and order by clause: Select empexam.empid order by examid ExamId Mark EmpName -----------------------------------------------1 55 Tom 2 73 Tom 3 44 Jack 5 39 Jack 6 63 Jack Two-Table.mark>=80 order by examid.empid = emp.ExamId.empexam.name as empname from empexam join emp on empexam.ExamId. QUERY: Select Employee_ID.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 3 Wash Georgia 11.Natural join clause is based on all columns in the two tables that have the same name.50 1 4 Bush Dave 21.65 1 . an error is returned.65 1 5 Will Robin 24. It selects rows from the two tables that have equal values in all matched columns.Last_Name.75 2 2 Last First 7. If the columns having the same names have different data types. deptno=e.last_name.department_name from employees e inner join departments d on e.department_id=e.employee_id.department_id where e.employee e where d.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.e.deptname.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 .depart_name.last_name from departments d inner join employees e on d.lastname from department d.00 12.00 13.department_id where d.6 7 8 9 Pete Roke Horry Bar Mona John Tedi Candi 9 10.department_id=d.e.Last_Name from department natural inner join employee select d.department_id=1 Department_NA Last_Name ------------------------------------------------DataGroup Lawson DataGroup Dillson Inner join Primary key and foreign key: Select e.e.d.00 2 3 3 3 Select Dept_Name. 2 3 4 Purchasing Call center Communication RESULT: Employee_Id Last_Name Department_NA -------------------------------------------------------------------------1002 Wells Purchasing 1008 Oracle Communication . 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: . 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. We can solve this problem by combining the two queries. A Scalar subquery is a query that returns exactly one value.SUBQUERY: DEFINITION: A Subquery is a query that is nested inside a select. QUERY: SELECT last_name. A Subquery within a Statement must be executed before the parent query that calls it. 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. 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. placing one query inside the other query. EXECUTING SINGLE-ROW SUBQUERIES: SELECT last_name. A Scalar Subqueries can be used in most places in a Sql statement where we will use an expression or a literal value. with a single column.insert. The inner query(or subquery) returns a value that is used by the outer query (or main query). A single row. To solve this problem. and a second query to find who earns more than that amount. A Subquery can return a set of rows or just one row to its parent query.update or delete statement or inside another subquery. in order that the result of the subquery can be passed to the parent. job_id. we need two queries: one to find how much Abel earns. salary FROM employees WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel'). . USING THE ANY OPERATOR IN MULTIPLE-ROW SUBQUERIES: SELECT employee_id....job_id.last_name..salary FROM employees WHERE salary < ANY (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG'.. 206 Gietz AC_ACCOUNT 8300 176 Taylor SA_REP 8600 .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. EMPLOYEE_ID LAST_NAME JOB_ID SALARY -----------------------------------------------------------------------------------144 Vargas ST_CLERK 2500 143 Matos ST_CLERK 2600 ….... (Select count(*) from Departments)Dept_count. Write a query to identify all the employees who are managers. Write a query to identify the highest salary paid in each country. 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. 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)).Where Subquery Required? In the Select list used for column Projection. 4. 2.ename.empno =outer.location_id.mgr). 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. 5. Ename from emp outer where exists (select empno from emp inner where 3. This will require using a subquery in the From Clause Select Max(Salary). (Select count(*) from Employees)Emp_Count from dual.sal from emp outer where sal>(select avg(sal) from emp inner where inner. Write a query that uses subqueries in the column projection list. In the From clause In the Where clause In the Having clause Places For Usage of Subqueries: 1. The query will report on the current number of departments and staff. Country_id from (Select salary. . Select Sysdate . department_id. empno).Salary From Employee order by salary Desc) 7. Using NotExists with a Subquery: Select Empno. RESULT: EMPNO ENAME 7902 Ford 7698 Blake 7839 King 7566 Jones 7788 Scott 7782 Clark 6.78 4 05 Robert 2334.78 6 07 David 2334.inner.empno).Salary “Salary”. RESULT: ID FIRST_NAME SALARY RANK ---------------------------------------------------------------------04 Celia 2334.56 8 . 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#”.RowNum Rank from ( Select id.mgr=outer. Ename from emp outer where not exists (select empno from emp inner where inner.78 1 02 Alison 2334.78 7 08 Jason 1234.78 5 06 Linda 2334.78 3 08 James 2334.78 2 03 James 2334. First_Name.First_Name “Name”.mgr=outer. NULL values are not ignored during duplicate checking. The IN operator has a higher precedence than the UNION operator.job_id. The names of the columns need not be identical. UNION operates over all of the columns being selected. Operator Returns ----------------------------------------------------------------------------------------------------------UNION All distinct rows selected by either query. UNION ALL All rows selected by either query. DISPLAY EACH COMBINATION ONLY ONCE. job_id.department_id From Employees UNION Select Employee_id.department_id From job_history EMPLOYEE_ID JOB_ID DEPARTMENT_ID ----------------------------------------------------------------------------------200 AC_ACCOUNT 90 200 AD_ASST 10 200 AD_ASST 90 . By default. Queries containing set operators are called compound queries. Select Employee_id. the output is sorted in ascending order of the first column of the SELECT clause. Use the UNION operator to return all rows from multiple tables and eliminate any duplicate rows. USING THE UNION OPERATOR DISPLAY THE CURRENT AND PREVIOUS JOB DETAILS OF ALL EMPLOYEES. 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. 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.SET OPEATORS: what is set operators: Set operators combine the results of two or more component queries into one result. 78 04 Celia 2344.78 Jason 1234.78 06 Linda 4322.78 Celia 2344.. SELECT employee_id. 4071. department_id FROM employees UNION ALL SELECT employee_id.78 Linda 4322.78 David 7897.. Salary From Employee Union Select 'The Average …. including all duplications..78 QUERY: Select First_Name..7525 UNION ALL OPERATOR The UNION ALL operator returns results from both queries....78 Robert 2334.78 The Average ….UNION: Use To Connect Column data and Summary Data ID First_Name Salary --------------------------------------------------01 Jason 1234..78 05 Robert 2344. department_id FROM job_history ORDER BY employee_id.78 James 6544..78 James 1232.78 08 James 1232. First_Name Salary --------------------------------------Alison 6661. Average from (Select Avg(Salary) average From Employee)..'.78 03 James 6544. 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. . job_id..78 07 David 7897. GUIDELINES The guidelines for UNION and UNION ALL are the same. job_id.56 02 Alison 6661.. The names of the columns need not be identical. and MINUS operators in their WHERE clause must have the same number and type of columns in their SELECT list . QUERY: SELECT employee_id. INTERSECT does not ignore NULL values. or the positional notation . an alias.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.department_id FROM employees WHERE (employee_id. Will accept the column name. Queries that use UNION. department_id FROM job_history). Reversing the order of the intersected tables does not alter the result. For Example SELECT employee_id.INTERSECT. The ORDER BY clause: Can appear only at the very end of the statement.department_id FROM employees UNION SELECT employee_id. 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. 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.UNION ALL. department_id) IN(SELECT employee_id. The Column name or alias. display the employee ID.job ID. 0 FROM job_history. salary FROM employees UNION SELECT employee_id. Set operators can be used in subqueries. and salary of all employees SELECT employee_id. must be from the first SELECT list. job_id. job_id. if used in an ORDER BY clause. EMPLOYEE_ID JOB_ID SALARY -----------------------------------------------------------------100 AD_PRES 24000 101 AC_ACCOUNT 0 205 AC_MGR 12000 206 AC_ACCOUNT 8300 . MATCHING THE SELECT STATEMENT: Using the UNION operator. phone_number.NULL). salary. email. INSERT INTO departments(100. salary.NULL. Remove existing rows from a table. last_name. 205. last_name.6900.department_name)(30. COPYING FROM OTHER TABLES: Write our INSERT statement with a Subquery: QUERY: INSERT INTO sales reps(id. QUERY: INSERT INTO employees (employee_id.SYSDATE. A transaction consists of a collection of DML statements that form a logical unit of work.124. job_id. last_name. 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 . Match the number of columns in the INSERT clause to those in the Subquery.4567'.'Popp'. INSERT INTO departments (department_id.commission_pct) SELECT employee_id.hire_date. commission_pct WHERE job_id LIKE '%REP%' Do not use the VALUES clause.manager_id.'515.'AC_ACCOUNT'.DATA MANIPULATION LANGUAGE: A DML statement is executed when we: Add new rows to a table.salary. INSERTING SPECIAL VALUES: The SYSDATE function records the current date and time.department_id) VALUES(113.100).'LPOPP'. INSERTING ROWS WITH NULL VALUES: Implicit Method : Omit the column from the column list.commission_pct. first_name.'Finance'.'Louis'. Modify existing rows in a table.NULL.'Purchasing') Explicit Method : Specify the NULL keyword in the VALUES clause. .WHERE employee_id = 205) WHERE employee_id =114. DELETE FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE department_name LIKE '%Public%'). 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. init. bdate from Employees where bdate>(Select bdate from Employees where Ename='Jones') 2. 4. 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.score from MyTable order by score DESC)t where rownum<=10. How many Products by Department with Correlated Sub queries? Table Name: Department DepartmentID Name Description ------------------------------------------------------------------1 Software Coding 2 Hardware Building .score from(Select username. Extract a Subset of the Results: Select username.EXERCISE PRACTICAL WORK: 1. 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. 99 Mouse.CategoryID Where Category.jpg 0 0 3 Desk ComputerDesk 5.Name As “Department”.jpg 0 1 5 Mouse Wireless 9.99 Desk.Name)As “Products” from Department D. Product P where ProductID IN(Select ProductID from ProductCategory inner join category on Product category.Name order by D.99 Ruler.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.DepartmentID=D.3 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.jpg 0 1 4 Pc Notebook 45.99 Pc.COUNT(P.jpg 1 0 2 Ruler Long 14.jpg 1 0 6 Keyboard Keyboard 3.DepartmentID)Group by D.99 Pen.categoryId=Category. OUTPUT: Hardware 4 QA 1 Software 3 .75 Keyboard.Name. City. Au_Lname. “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. Last_name. State from Employees order by 4 asc. 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”.2 desc Au_Fname Au_Lname City ST --------------------------------------------------------------------- . State From Employees Orderby state Asc. 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. au_lname As “LastName . Sort By Index Ascending and Descending Select Au_Fname.'Unknown First name ') from employee 6. First_name. “LastName” Asc. NVL(First_name.5. First_Name From Employee RESULT: RowNum City ---------------------------------1 Toronto 2 Vancouver 3 Vancouver 4 Vancouver 5 Vancouver 6 Newyork .56 Toronto 02 Alison 6661.78 Newyork 7897.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.78 Newyork 4322.78 Vancouver 06 Linda 4322.78 Vancouver 04 Celia 2344.78 Vancouver 1232.78 Vancouver 05 Robert 2344.78 Newyork 08 James 1232.78 Vancouver 2344.78 Select city. Avg(Salary) “Avg_Salary” from Employee Group by salary orderby avg(salary) desc. Add Aggregate function in Order-by Clause: City Salary ---------------------------------Toronto 1234.78 Vancouver QUERY: Select Rownum. 9.78 Vancouver 03 James 6544.78 Vancouver 2344. ROWNUM ID FIRST_NAME SALARY CITY -------------------------------------------------------------------01 Jason 1234.56 Vancouver 6661.78 Newyork 07 David 7897.78 Vancouver 6544. mos_categories where mos_content.id . mos_categories.alias from mos_categories where id in (Select Distinct catid from mos_content) Using Join: Select distinct mos_content.catid = mos_categories.7 8 Newyork Vancouver JOINS ARE MORE FASTER THAN SUBQUERIES: Using Subquery: Select id.catid.alias from mos_content.