Sie sind auf Seite 1von 144

DATA QUERY LANGUAGE (DQL) COMMANDS IN DBMS

INTRODUCTION: SELECT COMMANDS


It is used to retrieve information from the table.

GLOBAL DATA EXTRACT:


To perform a query we use a select command. The query is the request for information. It is the most common database operation used. We can either display all columns in a table or only specify column from the table. Syntax: Select * from tablename; This query selects all rowsfrom the table.

THE RETRIEVAL OF SPECIFIC COLUMNS FROM A TABLE:

Syntax: Select column_name1, ..,column_namen from table name;

ELIMINATION OF DUPLICATES FROM THE SELECT CLAUSE:

Syntax: Select DISTINCT col1, col2 from table name;

DQL SELECTION Introduction:


The DQL Selection is performed using the following Betweenand In Not in Like Relational Operators Logical Operators

DATA QUERY LANGUAGE (DQL) COMMANDS AIM:


To write DQL commands to restrict and retrieve information from the database using various criteria

SELECTING ROWS AND COLUMNS:


1.Write a query to display all columns and rows from departments table

SELECT* FROM departments ;

2.Write a query to display all the department _id and location_id from the departments table

SELECT dept_id,loc_id FROM departments;

3.Write a query to display all department_id before location_id from the departmets table.

SELECT loc_id,dept_id FROM departments;

4.Write a query to display all last_name,hire_date and salary from employees table.

SELECT last_name,hire_date,salary FROM employes;

5.Write a query to display all the last_name,job_id,salary and comm_pct from the employees table.

SELECT last_name,job_id,salary,comm_pct FROM employees;

SELECTING ROWS USING ARITHMETIC OPERATIONS


6.Write a query to calculate a salary increase of Rs.300/- for all employees and display a new salary + 300 column in the output.

SELECT last_name,salary,salary+300 FROM employees;

7.Write a query to display all the employees last_name,salary and annual compensation as 12multiplied by the monthly salary,plus one time bonus of Rs.1000/-.

SELECT last_name, salary, (12*salary) +1000 FROM employees;

SELECTING ROWS USING COLUMN ALIASES:


8. Write a query to display the last_name,salary,and the scommission percentage of all the employees with aliases name.

SELECT last_name AS Name,salarysalary,comm_pct comm FROM employees;

9.Write a query to display the last_name,annual salay of all the employees with aliases Annual salary.

SELECT last_name,salary AS Annual salary FROM employees;

10.Write a query to concatenate the last_name and job_id of all employees with the aliases Employees.

SELECT last_name || job_id AS Employees FROM employees;

11.Write a query to concatenate the last_name and job_id of all employees with aliases Employee details.also improve the readability of the output.

SELECT last_name || job_id AS employee details FROM employees;

SELECTING ROWS WITH NO DUPLICATION USING DISTINCT KEYWORD:


12.Write a query to display the entire department_id without any duplication from the employees table.

SELECT DISTINCT dept_id FROM employees;

SELECING ROWS USING WHERE CLAUSE:


13. Write a query to retrieve the last_name,job_id and department_id of all employees whose job_id is SA_REP.

SELECT last_name,job_id,dept_id FROM departments WHERE job_id=SA_REP.

14. Write a query to retrieve the employee_id,last_name,job_id and department_id of all employees whose department_id is 90.

SELECT emp_id,last_name,job_id,dept_id FROM employees WHERE dept_id=90;

SELECTING ROWS USING COMPARISON CONDITION:


15. Write a query to retrieve the last_name and salary of all employees whose salary is less then or equal to Rs.3000/-.

SELECT last_name,salary FROM employees WHERE salary <=3000;

SELECTING ROWS USING BETWEEN... AND KEYWORD:


16. Write a query to retrieve the last_name,salary of all employees whose salary is between Rs.2500 and Rs.3500.

FROM employees WHERE salary BETWEEN 2500 AND 3500;

SELECTING ROWS USING IN CONDITION:


17. Write a query to retrieve the employee_id,last_name,salary and manager_id of all employees whose manager employee_id is 100,101,201.

SELECT employee_id,name,salary,manager_id FROM employees WHERE manager_id IN(100,101,201);

SELECTING ROWS USING LIKE KEYWORD WITH % AND _ SYMBOLS:


18. Write a query to retrieve the last_name of all employees whose last_name begin withk

SELECT last_nameFROM employees WHERE last_name LIKE K%;

19. Write a query to retrieve the names of all employees where the 3rd letter of the name is an a.

SELECT first_name FROM employees WHERE first_name LIKE__a;

SELECTING ROWS WITH LIKE KEYWOARD USING ESCAPE OPTION:


20. Write a query to retrieve the employee_id,last_name and job_id of all employees whose job employee_id is AD_ using LIKE with ESCAPE option.

SELECT emp_id,last_name,job_id FROM employees WHERE job_id LIKE %AD\_ESCAPE\;

SELECTING ROWS USING IS NULL OPERATOR:


21. Write a query to retrieve the last_name,job_id and commission percentage of all employees who are not entitled to get a commission.

SELECT last_name,job_id,comm_pct FROM employees WHERE comm_pct ISNULL;

22. Write a query to retrieve the department_id,department_name and manager_id whose manager_id IS NULL.

SELECT dept_id,dept_name,manager_id FROM employees WHERE manager_id IS NULL;

SELECTING ROWS WITH LOGICAL CONDITION:AND,OR & NOT OPERATOR


23. Write a query to retrieve the employee_id,last_name,job_id and salary of all employees who have a job_title that contains the string MAN or earn rs.10000/- or more.

SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary >=10000 OR job_id<LIKE%MAN%;

24. Write a query to retrieve the employe_id,name,job_id and salary of all employees who have job_title that contains the string MAN and earn Rs.10000/- or more.

SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary >= 10000 AND job_id LIKE %MAN%;

25. Write a query to retrieve the last_name and salary of all employees whose salary is not between Rs.10000/- and 15,000/-

SELECT last_name,salary FROM employees WHERE salary NOT BETWEEN 10000 AND 15000; 26. Write a query to retrieve the last_name,job_id and salary of all employees if an employee is a president or a sales representative,and if the employee earn more than Rs.15000/-.

SELECT last_name,job_id,salary FROM employees WHERE job_id=AD_PRES OR job_id=SA_REP AND salary >15000;

27. Write a query to retrieve the last_name and salary of all employees who earn between Rs.5000/- and Rs.12000/- and are in department 20 or 50.

SELECT last_name,salary FROM employees WHERE salary BETWEEN 5000 AND 12000 AND (dept_id=20 OR dept_id=50);

SELECTING ROWS USING ORDER BY CLAUSE WITH ASC AND DESC KEYWORD:
28. Write a query to retrieve the last_name,job_id,department_id and hire_date of all employees and sort the result by hired employees.

SELECT last_name,job_id,department_id,hire_date FROM employees ORDER BY hire_date;

29. Write a query to retrieve the last_name,job_id,department_id and hire_date of employees and sort the result by the most recently hired employees.

SELECT last_name,job_id,dept_id,hire_date FROM employees ORDER BY hire_date DESC;

30. Write a query to retrieve the last_name,job_id,hire_date of all employees hired between February 20,2008 and may1,2008.

SELECT last_name,job_id,hire_date FROM employees WHERE hire_date BETWEEN 20-feb-08 AND 1-may-08;

31. Write a query to retrieve the last_name,salary and commission for all employees who earn commissions and sort the result in descending order of salary and commission percentage. SELECT last_name,salary,comm_pct FROM employees WHERE comm_pct IS NOT NULL ORDER BY salary DESC comm_pct;

32. Write a query to retrieve the last_name and hire_date of every employee who was hired in 1997.

SELECT last_name,hire_date FROM employees WHERE hire_date LIKE %97%;

SINGLE ROW FUNCTIONS


AIM:
To write a DQL commands to restrict and retrieves information from the database using various single row functions.

SELECTING ROWS USING CASE-MANIPULATION FUNCTIONS:UPPER,LOWER,INITCAP


1.Write a query to display the last name and job title of all employees in the following format. Emloyee Details The job id for KUMAR is ad_vp SELECT The job id for|| UPPER(last_name)|| LOWER(job_id) AS Employee Details FROM employees; 2. Write a query to display the employee id, last name, department id whose last name is higgins. of all employees

SELECT emp_id, last_name , dept_id FROM employees WHERE last_name=Higgins; 3. Write a query to display the employee id , last namejob title of all employees whose job title is starts with capital letter following small letters.

SELECT emp_id, last_name, job_id FROM employees WHERE job_id=INIT CAP(job_id);

SELECTING ROWS USING CHARACTER MANIPULATION FUNCTIONS:CONCAT, SUBSTR, LENGTH ,INSTR,LPAD,RPAD,TRIM AND REPLACE
4.write a query to display the employee id , first and last names joined together and job title for all employees who have the string REP contained in the job id starting at the fourth position of the job title. SELECT emp_id,CONCAT(first_name,last_name) AS NAME,job_id FROM employees WHERE SUBSTR(job_id,4)=REP;

5.Write a query to display the employee id ,last name ,length of the employee last_name,job title for all employees who have the string PROG contained in the job id starting at the third position of the job title. SELECT emp_id, last_name, length(last_name), job_id FROM employees WHERE SUBSTR(job_id.4)=PROG;

6. Write a query to display the employee id , last name and the numeric position of the letter a in the last name for all employes whose last names end with an r SELECT emp_id, last_name INSTR (last_name,a) FROM employees WHERE last_name LIKE %r;

7. Write a query to diplay the salary value as right justified for a length 10 of all employees. SELECT RPAD (select,10,*) FROM employees; 8. Write a query the salary value as left justified for a length 10 of all employees. SELECT LPAD (salary,10,*) FROM employees; 9.Write a query to trim and display the letter H from the Hello World

SELECT TRIM (H FROM HELLO WORLD) FROM DUAL;

SELECTING ROWS USING NUMBER FUNCTIONS FROM DUAL TABLE: ROUND, TRUNCATE AND MOD
10. Write a query to round the value 45.923 into 45.9246 and 50. SELECT ROUND (45.923) ,ROUND (45.9230),ROUND(45.923,-1) FROM DUAL 11. Write a query to truncate the value 45.923 into 45.9245 AND 0. SELECT TRUNCATE(45.923,2), TRUNCATE(45.923,0), TRUNCATE (45.923,-1) FROM DUAL; 12.Write a query to display last name, salary and calculate the remainder of the salary after divinding it by RS. 5000/- for all employees whose job title is SA_REP. SELECT last_name, salary,MOD (salary,5000) FROM employees WHERE job_id=SA_REP; ;

SELECTING ROWS WITH DATE FUNCTIONS:MONTHS_BETWEEN, ADD_MONTHS,NETX_DAY,LAST_DAY, ROUND, TRUNCATE


13. Write a query to display system date. Label the column System Date. SELECT SYSDATE AS system date FROM DUAL;

14. Write a query to display last name and the number of weeks employed for all employees in the department 90. Label the column Weeks. SELECT last_name,(SYSDATE-hire_date)/7 AS weeks FROM employees WHERE dept_id =90;

15. Write a query to display the employee id , hire date and number of months employed of all employees. Label the column Tenure.

SELECT emp_id , hire_date, MONTHS_BETWEEN (SYS DATE,hire_date) AS TENURE FROM employees;

16.Write a query to display the employee id,hire date,current date and six months review date from the current date f all employees, Label the column Review. SELECT emp_id, hire_date,sysdate,ADD_MONTHS(SYSDATE,B) AS REVIEW FROM employees;

17. Write a query to display the employe id , hire date and first Friday after hire date of all employees fewer than 20 months. SELECT emp_id ,hire_date,NEXT_DAY (hire_date,FRIDAY ) FROM employees WHERE MOTHS_BETWEEN(sysdate,hiredate)/20;

18.Write a query to display the employee id,hire date and last day of hire month for all employees fewer than 36 months. SELECT emp_id,hire_date, LAST_DAY(hire_date) FROM employees WHERE MONTHS_BETWEEN (sysdate,hire_date)/36;

19. Write a query to display the system date and round it to month. SELECT SYSDATE, ROUND (SYSDATE,year) FROM DUAL;

20. Write a query to display the system date and truncate it to year. SELECT SYSDATE , TRUNC(SYSDATE, year) FROM DUAL;

21. Write a query to display the employee id , the hire date and start month using round and truncate functions of all employees whose hired date started in 2007.

SELECT emp_id , hire_date ROUND(hire_date,month) trunk(hire_date,month) FROM employees WHERE hire_date LIKE %2007;

SELECTING ROWS WITH DATA CONVERSION FUNCTIONS:TO_CHAR, TO_NUMBER, TO_DATE


22. Write a query to display the system date and date in the following format: DD/MON/YYYY. Label the column date. SELECT sysdate, TO_CHAR(sysdate,DD/MON/YYYY) AS DATE FROM DUAL;

23.Write a query to display the system date and year to be spelled out. Lable the column year. SELECT sysdate, TO_CHAR(sysdate,year) AS year FROM DUAL;

25. Write a query to display the system date, full name of the month, three-letter abbreviation of the day of week. Label the columns Month and Day. SELECT sysdate,TO_CHAR(sysdate,MONTH) ASMONTH, TO_CHAR(sysdat,DAY) As DAY ROM DUAL; 26. Write a query to display the employe id ,hired date and month on which the employee started. Label the column MONTH_HIRED of all employees whose last_name is Kumar. SELECT emp_id,hire_date, TO_CHAR(hire_date,MONTH) AS MONTH_HIRED FROM employees WHERE last_name=Kumar; 27. Write a query to display the last name,hire date, and day of the week on which the employee started . Label the column DAY. Order the results by the day of the week starting with Monday. SELECT last_name , hire_date, TO_CHAR(hire_date,DAY) AS DAY FROM employees ORDER BY day; 28. Write a query to display the salary of all employees in the following format: $6000.00

SELECT TO_CHAR(salary,$99,999.00) SALARY FROM employees;

29. Write a query to convert the character string 01/jan/2008 to a date format. SELECT TO_DATE (01/JAN/2008,DD-MON-YY) FROM DUAL;

30.Wite a query to display last_name and employees hired prior to 1999. Hint : Use the RR format in TO_DATE function SELECT last_name,TO_CHAR(hire_date,DD-MON-YYYY) FROM employees WHERE hire_date<TO_DATE(01-JAN-99,DD-MON-RR);

SELECTING ROWS WITH GENERAL FUNCTIONS: NVL,NVL2,NULLIF, COALESCE


31. Write a query to display the last name and manager id of all employees, also replace the null value of manager id with a text string No manager. SELECT last_name,NVL(TO_CHAR(manager_id), NO manager) FROM employees;

32. Write a query to display last name and commission of all employees. If an employee does not earn commission, put the value 0. Label the column commission SELECT last_name, NVL(TO_char (comm._pct),ZERO) AS COMMISSION FROM employees;

33. Write a query to display the last name , salary,commission percentage of all employees , and if commission percentage is detected , then return string Salary + Commission else return Salary as aliass Income whose department id is 50 and 80. SELECT last_name,salary, comm._pct,NVL2(comm._pct,Salary + commission, salary) AS Income FROM employees WHERE department id IN (50,80); 34. Write a query to display the first name ,length of the first name, last name, length of the last name and if length of both first and last name are equal, then return null else return length of the first name of all employees.

SELECT first_name , LENGTH(first_name)expr1,last_name LENGTH(last_name)expr2, NULLIF (LENGTH(last_name)) Result FROM employees; 35. Write a query to display the last name, commission percentage or manager id or *** based on the following conditions and order the result by commission. Label the column commission a. If the employee earns commission, then commission percentage should be shown. b. If the employee does not earn commission , hen the manager id should be shown. c. If the employee does not earn comm.. and have no manager , then display ***(3 star) SELECT last_name, COALESCE (comm._pct, manager_id,***) AS Commission FROM employees ORDER BY comm._pct;

SELECTING ROWS USING CONDITIONAL EXPRESSIONS:CASE, DECODE


36. Write a query to display the last name, job id, salary and revised salary in whole number based on the following condition of all employees. Label the column Revised Salary. a. If the employees job id is IT_PROG, then the salary increase is 10%. b. If the employees job id is ST_CLERK, then the salary increase is 15%. c. If the employees job id is SA_REP, then the salary increase is 20%. SELECT last_name,job_id,salary, CASE job_id WHEN IT_PROG THEN 1.10*salary WHEN ST_CLERK THEN 1.15 * salary WHEN SA_REP THEN 1.20 * salary ELSE salary END revise Salary FROM employees;

37. Write a query to display the last name, job id , salary and revised salary in whole number based on the following condition of all employees. Label the column Revised salary. a. If the employees job id is IT_PROG, then the salary increase is 10%. b. If the employees job id is ST_CLERK, then the salary increase is 15%. c. If the employees job id is SA_REP, then the salary increase is 20%. SELECT last_name,job_id,salary, DECODE( job_id, IT_PROG , 1.10*salary , ST_CLERK, 1.15 * salary, SA_REP, 1.20 * salary, Salary)Revise Salary FROM employees;

38. Write a query to display the last name, salary and the applicable tax rate for each employee in department 80. Label the column Tax Rate. Hint: Divide the salary by RS.2000/- Based on the remainder assign tax rate. Remainder: 00.00, 10.09, 20.20, 3 0.30, 40.40,50.42, 60.44, default 0.45 SELECT last_name , salary, DECODE (TRUNC (salary/2000, 0), 0, 0.00, 1, 0.09, 2, 0.20, 3, 0.30, 4, 0.40, 5, 0.42, 6,0.44, 0.45) AS Tax rate FROM employees WHERE dept_id=80;

EXAMPLES
Select command with conditions To select specific rows from a table we include where clause in the select command. It can appear only after the from clause.

EMPLOYEE TABLE: ENO ENAME SAL


1 2 3 4 sayee rama meera sayee 2890 5000 6000 4536

AGE
19 20 20 20

----------------------------------------------------

bala

7780

20

SELECT SINGLE COLUMN: SQL> select ename from employee; ENAME ----------------------------------------------sayee rama meera sayee bala SELECT MULTICOLUMN: SQL> select eno,ename,sal from employee; ENO ENAME
1 2 3 4 5 sayee rama meera sayee bala

SAL
2890 5000 6000 4536 7780

SELECT ALL: SQL> select * from employee; ENO ENAME


1 2 3 4 5 sayee rama meera sayee bala

SAL

AGE
2890 5000 6000 4536 7780 19 20 20 20 20

SELECTION WITH ARITHMETIC OPERATION: SQL> select eno,ename,sal+1000 from employee; ENO ENAME
1 2 3

SAL+1000
3890 6000 7000

sayee rama meera

4 5

sayee bala

5536 8780

SELECTION WITH ALIAS: SQL> select eno,ename ,sal+1000 withbonus from employee; ENO ENAME
1 2

WITHBONUS
3890 6000

sayee rama

3 4 5

meera sayee bala

7000 5536 8780

SQL> select eno,ename,sal+1000 withbonus from employee; ENO ENAME


1 2 3 4 5

withbonus
3890 6000 7000 5536 8780

sayee rama meera sayee bala

SQL> select ename,eno,sal+1000 as withbonus from employee; ENAME ENO WITHBONUS

sayee rama

1 2

3890 6000

meera sayee bala

3 4 5

7000 5536 8780

RENAME: SQL> select sal salary from employee; salary 2890 5000 6000 4536 7780 SELECTION WITH CONCATENATION OPERATOR: SQL> select eno || ename from employee;

ENO||ENAME 1sayee 2rama 3meera 4sayee 5bala SELECTION WITH LITERAL CHARACTER STRINGS: SQL> select ename || || getting || || sal from employee; ENAME|| || GETTING || ||SAL sayeegetting2890 ramagetting5000 meeragetting6000 sayeegetting4536 balagetting7780

SELECT DISTINCT: SQL> select distinct ename from employee;

ENAME meera bala sayee SQL> select distinct eno from employee; ENO 1 2 4 5 3

RESULT:

DATA MANIPULATION LANGUAGE[DML] OR TRANSACTION CONTROL STATEMENTS[TCS]COMMANDS

AIM:
To write DML commands to insert,update and delete data in various table and perform TCS commands such as commit,rollback and savepoint.

DATA MANIPULATION LANGUAGE[DML]:


Data manipulation language consist of three operations namely; 1. insert 2.update 3.delete

SYNTAX FOR THE OPERATIONS OF DML: INSERT:

INSERT INTO tablename VALUES(&column name1,&column name2);

UPDATE:
UPDATE tablename SET newfield=newvalue WHERE oldfield=oldvalue;

DELETE:
DELETE FROM tablename WHERE field=value;

INSERTING NEW ROWS AND ROLLBACK:


1.Write a query to insert a new row containing values for each column into the regions table Commit and verify it.

a.INSERT INTO regions(region_id,region_name) VALUES (1,'Europe'); 1 row created. b.INSERT INTO regions(region_id,region_name) VALUES (2, 'Americas'); 1 row created. ROLLBACK; Rollback complete. Verify by: SQL> SELECT * FROM countries;

2.Write a query to insert a new row containing values for each column into the countriestable, Commit and verify it. a.INSERT INTO countries(country_id,country_name,region_id) VALUES(&country_id,&country_name,&region_id); Enter the value for country_id=CA Enter the name for country_id=Canada Enter the value for region_id=2 1 row inserted.

Verify by: SQL> SELECT * FROM countries;

3.Write a query to insert a new row containing values for each column into the locationstable, Commit and verify it. a.INSERT INTO locations VALUES(1400, '18A,Rajaji St,Perambur', '600011', 'Chennai', 'Tamilnadu','IND'); 1 row inserted. b.INSERT INTO locations VALUES(1500, '2011,Interior Blvd', '9236' , 'South San Francisco', 'California', 'USA'); 1 row inserted. COMMIT; Commit complete. Verify by: SQL> SELECT * FROM locations;

4. Write a query to insert a new row containing values for each column into the jobs table, Commit and verify it. a. INSERT INTO jobs VALUES('AD_PRES', 'President', 20000, 40000); 1 row inserted. b. INSERT INTO jobs VALUES('AD_VP', 'Administration Vice President', 15000, 30000); 1 row inserted. COMMIT; Commit complete. Verify by: SQL> SELECT * FROM jobs;

5. Write a query to insert a new row containing values for each column into the departments table and verify it.

a.INSERT INTO departments VALUES( 10, Administration, 200, 1700); 1 row inserted. b.INSERT INTO departments VALUES(20, Marketing, 201, 1800); 1 row inserted. COMMIT; Commit complete. Verify by: SQL> SELECT * FROM departments;

6.Write a query to insert a new row containing values for each column into the job_history table and verify it.

a.INSERT INTO job_history VALUES(102, TO_DATE('JAN 13,08','MON DD,YY'), TO_DATE('JUL 24,08','MON DD,YY'), 'IT_PROG',60); 1 row inserted. b. INSERT INTO job_history VALUES(1101,TO_DATE('SEP 21,99','MON DD,YY'), TO_DATE('OCT 27,03','MON DD,YY'), 'AC_ACCOUNT, 110 ); 1 row inserted. COMMIT; Commit complete. Verify by: SQL> SELECT * FROM job_history;

7. Write a query to insert a new row containing values for each column into the employees table and verify it. a.INSERT INTO employees VALUES(100,'steven','king', sking@gmail.com ', '9941765849',TO_DATE('JUN 17,97','MON DD,YY'),'AD_PRES',24000,null,null,90); 1 row created. b. INSERT INTO employees VALUES(101,'Neen','Kumar', nkumar@yahoo.com ', '9876578768',TO_DATE('SEP 21,99','MON DD,YY'),'AD_VP',17000,100,100,90); 1 row created. SQL> COMMIT; Commit complete. Verify by: SQL> SELECT * FROM employees; 8. Write a query to insert a new row containing values for each column into the job_grades table and verify it. a.INSERT INTO job_grades VALUES(A, 1000, 2999); 1 row created. b.INSERT INTO job_grades VALUES(B, 3000, 5999); 1 row created. SQL> COMMIT; Commit complete Verify by: SQL> SELECT * FROM job_grades;

UPDATING ROWS IN A TABLE AND ROLLBACK:


1.Write a query to update the mark4 column to 75 whose rollno is 001,set the savepoint S1 and verify it. UPDATE students SET mark4= 75 WHERE roll_no=001; 1 row updated. SAVEPOINT s1; Savepoint created. Verify by: SQL> SELECT * FROM students WHERE roll_no=001;

2.Write a query to update the mark3 colum to 98 whose rollno is 005,set the savepoint S1 and verify it. UPDATE students SET mark3=98 WHERE roll_no=005; 1 row updated. SAVEPOINT s1; Verify by: SELECT * FROM students WHERE roll_no=005;

3.Write a query to set the mark1,mark2,mark3,mark4 for all

total

column

as

sum

of

the students,set the savepoint s3 and verify it. UPDATE students SET total=mark1+mark2+mark3+mark4; 3 rows updated. SAVEPOINT s3;

Savepoint created.

Verify by: SELECT * FROM students;

4.Write a query to set the average column as average of total marks for all the students, set the savepoint s4 and verify it. UPDATE students SET average=total/4; 3 rows updated. SAVEPOINT s4; Savepoint created Verify by: SELECT * FROM students;

DELETING ROWS FROM A TABLE:


1.Write a query to delete the record from the students table whose rollno is 003,set the Savepoint s5 and verify it. DELETE FROM students WHERE roll_no=003; 1 row deleted. SAVEPOINT s5; Savepoint created Verify by: SELECT * FROM students WHERE roll_no=003;

2.Write a query to delete the record from thestudentstable whose roll no is 003,set the Savepoint s6 and verify it. DELETE FROM students WHERE roll_no=003; 1 row deleted.

SAVEPOINT s6; Savepoint created. Verify by: SELECT * FROM students WHERE roll_no=003;

ROLLBACK TO SAVEPOINT OPTION:


3.Write a query to rollback to savepoint s6 and verify it. ROLLBACK TO s6; Rollback complete. Verify by: SELECT * FROM students;

4.Write a query to rollback to savepoint s4 and verify it. ROLLBACK TO s4; Rollback complete. Verify by: SELECT * FROM students;

5.Write a query to savepoint s1 and verify it. ROLLBACK TO s1; Rollback complete. Verify by: SELECT * FROM students;

SQL > Create Table Cust(cname varchar2(15),cid number(5),caddr char(10), caccno number(5),cacctype varchar2(10),cbalance float,

Primary key(cid),unique(cname),unique(caccno),check(cbalance>=1000));

Table created SQL> desc cust; Name Null? Type

----------------------------------------- -------- ---------------------------CNAME CID CADDR CACCNO CACCTYPE CBALANCE VARCHAR2(15) NOT NULL NUMBER(5) CHAR(10) NUMBER(5) VARCHAR2(10) FLOAT(126)

INSERT:
SQL> insert into cust values('Anitha',01,'Chennai',1001,'savings',15000); 1 row created. SQL> insert into cust values('Shriram',02,'Pondy',1002,'savings',25000); 1 row created. SQL> insert into cust values('Chamundi',03,'Salem',1003,'fd',36200); 1 row created. SQL> insert into cust values ('&cname', &cid,'&caddr', &caccno, '&cacctype',&cbalance); Enter value for cname: Subha Enter value for cid: 04 Enter value for caddr: Salem

Enter value for caccno: 1009 Enter value for cacctype: 5000 Enter value for cbalance: 5000

Old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance) New 1: insert into cust values('Subha',04,'Salem',1009,'RD',5000) 1 row created.

SQL> / Enter value for cname: Madhan Enter value for cid: 4 Enter value for caddr: Salem Enter value for caccno: 1004 Enter value for cacctype: checkings Enter value for cbalance: 5000 old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance) new 1: insert into cust values('Madhan',4,'Salem',1004,'checkings',5000) 1 row created.

SQL> / Enter value for cname: Subha Enter value for cid: 5 Enter value for caddr: Trichy Enter value for caccno: 1005 Enter value for cacctype: checkings

Enter value for cbalance: 10000 old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance) new 1: insert into cust values('Subha',5,'Trichy',1005,'checkings',10000) 1 row created.

SQL> / Enter value for cname: Sridharan Enter value for cid: 7 Enter value for caddr: Kanchi Enter value for caccno: 1007 Enter value for cacctype: fd Enter value for cbalance: 22000

old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance) new 1: insert into cust values('Sridharan',7,'Kanchi',1007,'fd',22000) 1 row created.

SELECT:
SQL> select * from cust; CNAME CID CADDR CACCNO CACCTYPE CBALANCE

--------------- ---------- ---------- ---------- ---------- ----------------------------------Anusha 15000 Shriram 25000 Chamundi 1 2 3 Chennai Pondy Salem 1001 1002 1003 savings savings fd 36200

Madhan Subha Jayashree Sridharan 7 rows selected.

4 5 6 7

Salem Trichy Pondy Kanchi

1004 1005 1006 1007

checkings checkings fd fd

5000 10000 15000 22000

UPDATE:
SQL> update cust set caccno=1111 where cname='Chamundi'; 1 row updated SQL> select * from cust; CNAME CID CADDR CACCNO CACCTYPE CBALANCE

--------------- ---------- ---------- ---------- ---------- -------------------------------------Anusha 15000 Shriram 25000 Chamundi Madhan Subha 10000 Jayashree Sridharan 7 rows selected. 1 2 3 4 5 6 7 Chennai Pondy Salem Salem Trichy Pondy Kanchi 1001 1002 1111 1004 1005 1006 1007 savings savings fd checkings checkings fd fd 15000 22000 36200 5000

DELETE:
SQL>delete from cust where cacctype='fd'; 3 row deleted

SQL> select * from cust;

CNAME CBALANCE

CID CADDR

CACCNO CACCTYPE

--------------- ---------- ---------- ---------- ---------- ------------------------------------Anusha 15000 Shriram 25000 Madhan Subha 10000 1 2 4 5 Chennai Pondy Salem Trichy 1001 1002 1004 1005 savings savings checkings checkings 5000

4 rows selected.

RESULT:

DATA DEFINITON LANGUAGE (DDL) COMMANDS

AIM:
To write DDL commands to create alter, delete, rename and truncate the various tables and create constraint to column.

DATA DEFINITION LANGUAGE (DDL):


Data definition language consists of five operations. They are Create Alter Drop Truncate Rename

SYNTAX FOR THE OPERATIONS OF DDL: CREATE:

CREATE TABLE TABLENAME {column name1 data type column name n data type};

ALTER:

ALTER TABLE TABLENAME ADD {column name1 data type}; (OR) ALTER TABLE TABLENAME MODIFY {column name2 data type};

DROP:

DROP TABLE TABLENAME;

TRUNCATE:

TRUNCATE TABLE TABLENAME;

RENAME:

RENAME old name TO new name;

TABLE CREATION AND ADDING CONSTRAINTS:


1.Write a query to create countries table and verify it. Table description:

Country_id at table value

char(2)

primary key constraint not null

Country_name varchar2(40) Region_id number table at table

foreign key constraint to regions level

CREATE TABLE countries ( Country_id CHAR(2), Country_name VARCHAR2(40) NOT NULL, Regions_id NUMBER, CONSTRAINT count_id_pk PRIMARY KEY (country_id), CONSTRAINT reg_id_fk FOREIGN KEY (region_id) REFERENCES regions(region_id));
Verify by: DESC countries;

2.Write a query to crate locations table and verify it.


Table description:

Loc_id level Street_add Postal_code City State_prov

number(4)primary key constraint at column varchar2(40) varchar2(12) not null foreign key to constraint to level varchar2(25)

varchar2(30)

Country_id char(2) countries table at column CREATE TABLE locations (

Loc_id NUMBER(4) CONSTRAINT loc_id_pk PRIMARY KEY, Street_add VARCHAR2(40),

Postal_code VARCHAR2(12), City VARCHAR2(25) NOT NULL, State_prov VARCHAR2(25), Country_id CHAR(2), CONSTRAINT country_id_fk FOREIGN KEY (country_id) REFERENCES countries (country_id));
Verify by: DESC locations;

3.Write a query to create jobs table and verify it. Table description:

Job_id column level Job_title

varchar2(10)

primary key constraint at

varchar2(35) number(6)

not null

Min_salarynumber(6) Max_salary CREATE TABLE jobs ( Job_id VARCHAR2(10) CONSTRAINT job_id_pk PRIMARY KEY, Job_title VARCHAR2(25) NOT NULL,Min_salary NUMBER(6),Max_salary NUMBER(6));
Verify by: DESC jobs;

TABLE CREATION AND ADDING CONSTRAINTS:


1.Write a query to create departments table and verify it. Table description:

dept_id

number(4)primary key constraint at column level varchar2(30) number(6) not null

dept_name manager_id

location_id number(4)foreign key constraint to region table at column level CREATE TABLE departments ( Dept_id NUMBER(4) CONSTRAINT dept_id_pk PRIMARY KEY, Dept_name VARCHAR2(30) NOT NULL, Manager_id NUMBER(6), Location_id NUMBER(4) CONSTRAINT location_id_fk FOREIGN KEY (location_id) REFERENCES regions (location_id));
Verify by: DESC departments;

2.Write a query to create job_history table and verify it. Table description:

Emp_id Dept_id

number(6)primary key constraint at column level varchar2(30) number(6) not null

Manager_id

Location_id number(4)foreign key constraint to regions table at column level CREATE TABLE job_history ( Emp_id NUMBER(6) CONSTRIANT emp_id_pk PRIMARY KEY, Start_date DATE NOT NULL, End_date DATE NOT NULL, Job_id VARCHAR2(10) NOT NULL, Dept_id NUMBER(4) CONSTRAINT dept_id_fk FOREIGN KEY (dept_id) REFERENCES departments (dept_id));
Verify by: DESC job_history;

TABLE CREATION AND ADDING CONSTRAINTS:


1.Write a query to create employees table and verify it. Table description:

Emp_id

number(6)primary key constraint at column level varchar2(20) not null unique key constraint at varchar2(25)

First_name Email table level

Last_namevarchar2(20)

Phone_no varchar2(10) level Hire_date date

unique key constraint at column

not null foreign key constraint to

Job_id varchar2(10) jobs table at column level Salary number(8,2) Comm_pct number(2,2)

Manager_id

number(6)

Dept_id number(4)foreign key constraint to departments table at column level CREATE TABLE employees ( Emp_id NUMBER(6) CONSTRAINT emp_id_pk PRIMARY KEY, First_name VARCHAR2(20), Last_name VARCHAR2(25) NOT NULL, Email VARCHAR2(25), Phone_no_uk UNIQUE, Hire_date DATE NOT NULL, Job_id VARCHAR(10) CONSTRAINT job_id_fk FOREIGN KEY (job_id) REFERENCES job55 (job_id), Salary NUMBER(8,2), Comm_pct NUMBER(2,2), Manager_id NUMBER(6), (dept_id) REFERENCES departments (dept_id)

CONSTRAINT email_uk UNIQUE (email));


Verify by: DESC employees;

TABLE CREATION AND ADDING A CONSTRAINTS:


1.Write a query to create job_grades table and verify it. Table description:

Grade_level Lowest_sal Highest_sal

varchar(30) number(6) number(6)

CREATE TABLE job_grades ( Grade_level VARCHAR(3), Lowest_sal NUMBER(6), Highest_sal NUMBER(6));


Verify by: DESC job_grades;

2.Write a query to create students table and verify it. Table description:

Roll_no Name

number(4) varchar2(20) number(10) number(3) number(3) number(3) not null

Contact_no Mark1 Mark2 Mark3

CREATE TABLE students ( Roll_no NUMBER(4),

Name VARCHAR2(20) NOT NULL, Contact_no NUMBER(10), Mark1 NUMBER(3), Mark2 NUMBER(3), Mark3 NUMBER(3)):

Verify by: DESC students;

TABLE ALTERATION: ADD and MODIFY A COLUMN


1.Write a query to alter students table to add mark4 and mark5 columns and verify it. Alter table description by:

Mark4 Mark5

number(3) number(3)

ALTER TABLE students ADD ( Mark4 NUMBER(3), Mark5 NUMBER(3));


Verify by: DESC students; 2.Write a query to alter students table to add the total & average columns and verify it. Alter table description by:

Total Average

number(4) number(5,2)

ALTER TABLE students ADD ( Total NUMBER(4), Average NUMBER(5,2));


Verify by: DESC students; 2.Write a query to alter students table to modify the following column to add constraint on it and verify it. Alter table description by:

Roll_no

number(4)primary key constraint

ALTER TABLE students MODIFY ( Roll_no NUMBER(4) CONSTRAINT roll_no_pk PRIMARY KEY);
Verify by: DESC students;

3.Write a query to alter students table to modify the columns to add constraints on it and verify it. Alter table description by:

Contact_no

number(10)

unique key constraint

ALTER TABLE students MODIFY ( Contact_no NUMBER(10) CONSTRAINT contact_no_uk UNIQUE);


Verify by: DESC students;

TABLE ALTERATION: DROPPING A COLUMN


1.Write a query to alter students table to drop the mark5 column and verify it.

ALTER TABLE students DROP COLUMN mark5;

Verify by: DESC students;

2.Write a query to alter students table to drop the mark5 column and verify it.

ALTER TABLE students DROP COLUMN mark5;

Verify by: DESC students;

TABLE ALTERATION: SET UNUSED COLUMN and DROP UNUSED COLUMNS OPTION
1.Write a query to alter students table to set contact_no column as unused and verify it.

ALTER TABLE students SET UNUSED COLUMN column_no;

Verify by: DESC students;

2.Write a query to alter students table to set contact_no column as unused and verify it.

ALTER TABLE students SET UNUSED mark4; Verify by: DESC students;

3.Write a query to alter students table to drop the unused columns and verify it.

ALTER TABLE students DROP UNUSED COLUMN;

Verify by: DESC students;

VIEWING CONSTRAINT:
1.Write a query to view all constraint definitions and names from the USER_CONSTRAINTS table.

SELECT * FROM USER_CONSTRAINTS;

2.Write a query to describe the field from the USER_CONSTRAINT table.

SELECT * FROM USER_CONSTRAINTS;

3.Write a query to view the constraints names and its types of the employees table from the USER_CONSTRAINTS table.

SELECT constraint_name, constraint_type FROM USER_CONSTRIANTS WHERE table_name = employees;

4.Write a query to view the constraints names and its types from the locations table.

SELECT constraint_name, constraint_type FROM USER_CONSTRIANTS WHERE table_name = locations;

DISABLING A CONSTRAINT:
1.Write a query to disable the UNIQUE KEY (contact_no_uk) constraint on the students table without dropping it or re-creating it and verify it.

ALTER TABLE students DISABLE CONSTRAINT contact_no_uk;

Verify by: DESC students;

2.Write a query to disable the PRIMARY KEY constraint on the employees table. Also disable associated FOREIGN KEY constraint on the departments table without dropping or re-creating it and verify it.

ALTER TABLE employees DISABLE CONSTRAINT emp_id_pk CASCADE; Verify by: DESC employees;

3.Write a query to disable the PRIMARY KEY (roll_no_pk) constraint on the students table without dropping it or re-creating and verify it.

ALTER TABLE students DISABLE CONSTRAINT roll_no_pk;

Verify by: DESC students;

ENABLING A CONSTRAINT:
1.Write a query to enable or activate the UNIQUE KEY constraint (contact_no_uk) on students table and verify it.

ALTER TABLE students ENABLE CONSTRAINT contact_no_pk;

Verify by: DESC students;

2.Write a query to enable or activate the PRIMARY KEY constraint on the employees table. Also enable or activate the associated FOREIGN KEY constraint on the departments table and verify it.

ALTER TABLE employees ENABLE CONSTRAINT emp_id_pk;

Verify by: DESC employees;

3.Write a query to enable or activate the PRIMARY KEY constraint (roll_no_pk) on the student table and verify it.

ALTER TABLE students ENABLE CONSTRAINT roll_no_pk;

Verify by: DESC students;

4.Write a query to enable or activate the PRIMARY KEY constraint on the regions table. Also enable or activate associated FOREIGN KEY constraint on the countries table and verify it.

ALTER TABLE regions ENABLE CONSTRAINT region_id_pk; Verify by: DESC regions;

DROPPING A CONSTRAINT:

1.Write a query to remove the UNIQUE KEY (contact_no_uk) constraint from the students table and verify it.

ALTER TABLE students DROP CONSTRAINT contact_no_uk;

Verify by: DESC students;

2.Write a query to remove the PRIMARY KEY constraint on the department table and drop the associated FOREIGN KEY constraint on the employees.dept_id column and verify it.

ALTER TABLE students DROP PRIMARY KEY CASCADE;

Verify by: DESC students;

3.Write a query to remove the PRIMARY KEY (roll_no_pk) constraint from the students table and verify it.

ALTER TABLE students DROP CONSTRAINT roll_no_pk;

Verify by: DESC students;

4.Write a query to disable the PRIMARY KEY constraint on the region table. Also disable associated FOREIGN KEY constraint on the countries table without dropping or re-creating it and verify it.

ALTER TABLE region DROP PRIMARY KEY CASCADE;

Verify by: DESC region;

CHANGING THE NAME OF A TABLE:

1.Write a query to rename the students table to stud and verify it.

RENAME students TO stud;

Verify by: DESC stud;

2.Write a query to rename the stud table to students and verify it.

RENAME stud TO students;

Verify by: DESC students;

TRUNCATEING AND DELETING TABLE:


1.Write a query to truncate the students table and verify it.

TRUNCATE TABLE students;

Verify by: DESC students;

2.Write a query to truncate the students table and verify it.

DROP TABLE students;

Verify by: DESC students;

SQL> create table emp(eno number(10),ename varchar2(10),dno number(10),sal number(10),jobid varchar2(10),mgrid varchar2(10),foreign key(dno) references depart(dno));

Table created

SQL> desc emp;

Name

Null?

Type

----------------------------------------- -------- ---------------------------ENO ENAME DNO SAL JOBID MGRID NUMBER(10) VARCHAR2(10) NUMBER(10) NUMBER(10) VARCHAR2(10) VARCHAR2(10)

SQL> desc emp;

Name

Null?

Type

----------------------------------------- -------- ---------------------------ENO ENAME NOT NULL NUMBER(10) VARCHAR2(10)

DNO SAL JOBID MGRID ADDR

NUMBER(10) NUMBER(10) VARCHAR2(10) VARCHAR2(10) VARCHAR2(10)

SQL> alter table emp add(phno number(5)); Table altered. SQL> alter table emp modify(jobid char(20));

Table altered. SQL> desc emp; Name Null? Type

----------------------------------------- -------- ---------------------------ENO ENAME DNO SAL JOBID MGRID ADDR PHNO NOT NULL NUMBER(10) VARCHAR2(10) NUMBER(10) NUMBER(10) CHAR(20) VARCHAR2(10) VARCHAR2(10) VARCHAR2(10)

SQL> drop table emp; Table dropped. SQL> desc emp;

ERROR

ORA-04043: object emp does not exist

RESULT:

NESTED QUERIES (SUB QUERIES) AIM :


To write a DQL commands to restrict and retrieves information from the same table using nested queries, executes it and verify the same.

SUBQUERY
Sub-Queries are nothing but nested SELECT statement. A subquery makes it possible for a user to base the search criteria of one SELECT statement on the results of another SELECT statement.

PURPOSE:
To provide values for condition in where, having and start with clauses of select statement. To define set of rows to be inserted into target table of insert or create table statement. To define the set of rows to be include in a view or create the snapshot statement.

SUBQUERY SYNTAX:

SELECT FROM WHERE

SELECT_LIST TABLE EXPR OPERATOR

(SELECT SELECT_LIST FROM TABLE);

The sub query(inner query)executes once before the main query

The result of the sub query is used by main query

TYPES OF SUB QUERIES

SINGLE ROW SUB QUERY:

MAIN QUERY

SUB QUERY

SINGLE ROW SUB QUERY RETURNS A SINGLE VALUE

MULTIPLE ROW SUB QUERY:

MAIN QUERY

SUB QUERY

MULTIPLE ROW SUB QUERY RETURNS MULTIPLE VALUES

QUERIES : SELECTING ROWS USING SUBQUERY :

1. Write a query to display the last name of all employees who

earn More than Kumars salary and verify it.

SELECT last_name FROM employees WHERE salary > (SELECT salary FROM employees WHERE last_name=kumar

2.
and

Write a query to display the last_name and hire_date of all employees who are in the same department as Kumar

verify it.

SELECT last_name, hire_date FROM employees WHERE departments = (SELECT dept_name FROM employees WHERE last_name=Kumar);

3. Write a query to display the last name and job id of all


employees whose job id is same as that of employee 141.

SELECT last_name, job_id FROM employees WHERE job_id =(SELECT job_id FROM employees WHERE emp_id=141);

4.Write a query to display the last name and job id of all employees whose job id is same as that of employee 141 and whose salary is greater than that of employee 143. SELECT last_name , job_id FROM employees WHERE emp_id = (SELECT emp_id FROM employees WHERE emp_id=141) and > (SELECT salary FROM employees WHERE emp_id=143);

SELECTING ROWS USING GROUP FUNCTIONS IN :SUBQUERIES

5. Write a query to display the last name,job id and salary of all employees whose salary is equal to minimum salary. SELECT last_name, job_id, salary FROM employees WHERE Salary = (SELECT MIN (salary) FROM employees);

6. Write a query to display the last name,job id and salary of

all employees who earn more than average salary. Sort the result in ascending order of salary.

SELECT last_name, job_id salary FROM employees WHERE Salary > (SELECT AVG (salary) FROM employees ORDER BY (salary));

SELECTING ROWS USING HAVING CLAUSE IN SUBQUERY :

7. Write a query to display all the department id which have a

minimum salary greater than that of department id 50.

SELECT dept_id , MIN(salary) FROM employees GROUP BY dept_id HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE dept_id=50);
8. Write a query to display all the job id and which have a

lowest average salary and verify it.

SELECT job_id , AVG (salary) FROM employees GROUP BY Job_id HAVING AVG (salary) = (SELECT MIN (salary) FROM employees GROUP BY( job_id);

SELECTING ROWS USING MULTIPLE ROW SUBQUERY IN

[<ANY(less than the maximum) ,>ANY(more than the minimum) =ANY(equivalent to IN), <ALL(less than the minimum) >ALL(more than the maximum),=ALL(equivalent to IN)]

9. Write a query to display the last name,salary,department id of all employees who earn the same salary as the minimum salary for each department and verify it.

SELECT last_name,salary,dept_id FROM employees WHERE salary IN(SELECT MIN(salary) FROM employees GROUP BY(Dept_id);

10. Write query to display the last name,salary,department id

of all employees who earn the same salary as the average salary for each department and verify it. SELECT last_name,salary,dept_id FROM employees WHERE Salary IN(SELECT AVG(salary) FROM employees GROUP BY Dept_id);

11. Write a query to display the employee id,last name,job id, salary of all employees who are not IT programmers and whose salary is less than that of any IT programmers maximum salary and verify it. Note :use <ANY operator. SELECT emp_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;

12. Write a query to display the employee id,last name,job

id,salary of all employees who are not SALES REPRESENTATIVE and whose salary is more than that of any sales representatives minimum salary and verify it. Note:use >ANY operator. SELECT emp_id,last_name.job_id,salary FROM employees WHERE salary>ANY(SELECT salary FROM employees WHERE job_id=SA_REP) AND job_id < > SA_REP;

12.Write a query display the employee id,last name,job id,salary of all employees who are not IT programmers and whose salary is less than that of the IT programmers minimum salary and verify it Note : use <ALL operator.

SELECT emp_id, last_name, job_id, salary FROM employees WHERE salary <ALL (SELECT salary FROM employees WHERE job_id=IT_PROG) AND job_id < > IT_PROG;

13.Write a query to display the employee id,last name,job id,salary of all employees who are not SALES REPRESENTATIVE and whose salary is more than that of the sales representatives maximum salary and verify it Note : use >ALL operator.

SELECT emp_ id , last_name, job_id, salary FROM employees WHERE salary >ALL (SELECT salary FROM employees WHERE Job_id=SA_REP AND job_id < > SA_REP;

14.Write a query to display the employees last name who have subordinates and verify it .Note : use IN operator.

SELECT last_name FROM employees WHERE emp_id IN (SELECT manager_id FROM employees);

15.Write a query to display the employees last name who do not have

subordinates and verify it Note : use NOT IN operator.

SELECT last_name FROM employees WHERE emp_id NOT IN (SELECT manager_id FROM employees);

RESULT :

JOIN QUERIES
AIM:
To write a DDL commands to join, restrict and retrieves information from one or more tables execute it and verify the same.

INTRODUCTION
The purpose of a join concept is to combine data spread across tables. A join is actually performed by the where clause which combines specified rows of tables.Syntax; select columns from table1, table2 where logical expression;

Types of Joins
1. Simple Join 2. Self Join 3. Outer Join

Simple Join
It is the most common type of join. It retrieves the rows from 2 tables having a common column and is further classified into

(a)Equi-join
A join, which is based on equalities, is called equi-join.

(b)Non Equi-join
It specifies the relationship between columns belonging to different tables by making use of relational operators other than=.

Self join
Joining of a table to itself is known as self-join. It joins one row in a table to another. It can compare each row of the table to itself and also with other rows of the same table.

Outer Join
It extends the result of a simple join. An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the table. The It specifies the relationship between columns belonging to different tables by making use of relational operators other than=.symbol(+) reprsents outer join.

JOINS

SYNTAX: SELECT table1.column,table2.column FROM table1,table2 WHERE table1.column = table2.column;

JOIN OPERATIONS
SQL>create table locn (lid number(5),city varchar(10),area varchar(5),primary key(lid)); Table created;

SQL>desc locn;
Name Null? Type ----------------------------------------- -------- --------------------------LID NOT NULL NUMBER(5) CITY VARCHAR2(10) AREA VARCHAR2(5) SQL>create table dep (dno number(5),dname varchar(10),lid number(5),primary ey(dno),foreign key(lid) references locn(lid)); Table created; SQL>desc dep; Name Null? Type ----------------------------------------- -------- -------------------DNO NOT NULL NUMBER(5) DNAME VARCHAR2(10) LID NUMBER(5) SQL>create table emp (eid number(5),ename varchar(10),dno number(5),esal number(10),jobid number(5),mgrid varchar(5),primary key(eid),foreign key(dno) references dep(dno)); Table created;

SQL>desc emp;

Name EID ENAME DNO ESAL MGRID JOBID

Null? NOT NULL

Type NUMBER(5) VARCHAR2(10) NUMBER(5) NUMBER(10) NUMBER(3) VARCHAR2(5)

----------------------------------------- -------- ----------------------------

SQL>create table grade(gno number(5),ls number(8),hs number(8)); Table created; SQL>desc grade; Name Null? Type ----------------------------------------- -------- -----------------GNO NOT NULL NUMBER(5) LS NUMBER(8) HS NUMBER(8) SQL>insert into locn values(&lid,'&city','&area'); enter lid:1 enter city:chennai enter area:aaa old 1: insert into locn values(&lid,'&city','&area') new 1: insert into locn values(1,'chennai','aaa') 1 row created SQL>insert into dep values(&dno,'&dname',&lid); enter dno:1 enter dname:admin enter lid:2 old 1: insert into dep values(&dno,'&dname',&lid) new 1: insert into dep values(1,'admin',2) 1 row created SQL>insert into emp values(&eid,'&ename',&dno,&esal, &jobid,&mgr id); enter eid:3 enter ename:zzz enter dno:3 enter esal :3500 enter jobid:2 enter mgr id:2 old 1: insert into emp values(&eid,'&ename',&dno,&esal,&jobid,&mgrid) new 1: insert into emp values(1,'zzz',3500,2,2)

1 row created

SQL>insert into grade values(&gno,&ls,&hs); enter gno:1 enter ls:1000 enter hs:2000 old 1: insert into grade values(&gno,&ls,&hs) new 1: insert into grade values(1,1000,2000) 1 row created SQL> select * from dep; DNO DNAME ---------- ---------- ------------1 admin 2 finance 3 Hr 4 market 5 sales SQL> select * from locn; LID CITY AREA ---------- ---------- ----------------------1 chennai aaa 2 bombay bbb 3 calcutta ccc SQL> select * from grade; GNO LS HS ---------- ---------- ---------1 1000 2000 2 2001 3000 3 3001 4000 4 4001 500 SQL> select * from emp; EID ENAME DNO ESAL JOBID MGRID ------- ---------- ---------- ---------- ----- ---------5 bbc 4700 2 1 xxx 1 4000 1 2 yyy 2 2000 2 1 3 zzz 3 3500 2 2 4 abc 2 4500 LID 2 3 4 3 1

EQUIJOINS
ENAME DNAME ---------- ---------xxx admin yyy finance zzz hr abc finance

Selecting Rows With Equijoins Using Table Aliases:


1.write a query to display the employee id, last name, department id, department name and location id for all employees and verify It. SELECT employees.emp_id, employees.last_name, employees.dept_id, d.dept_id, d.loc_id FROM employees,depatments d WHERE employees.dept_id = d.dept_id;

2.Write a query to display the higgins department id and department name and
verify it. SELECT e.dept_id,dept_name FROM employees e,departments d WHERE last_name=Higgins AND e.dept_id = d.dept_id; 3.Write a query to display the unique listing of all jobs that are in department 80. Include the location id of the department in the output and verify it. SELECT j.job_id,d.loc_id FROM job_histroy j,departments d WHERE dept_id=80 AND j.dept_id = d.dept_id;

NON_EQUIJOINS
SQL> select e.ename,e.esal,g.gno from emp e,grade g where e.esal between g.ls and g.hs; ENAME ESAL GNO ---------- ---------- ---------bbc 4700 4 xxx 4000 3 yyy 2000 1 zzz 3500 3 abc 4500 4

Selecting Rows with Non_Equijoins using Table Aliases:


Other conditions such as >=,<= and BETWEEN..AND 4.Write a query to display the last name,salary,grade level of all employees and verify it. SELECT e.last_name,e.salary,jg.grade_level FROM employees e, job_grades jg WHERE e.salary BETWEEN jg.lowest_sal AND jg.higest_sal; 5.Writea query to display the last_name,phone number,salary and job title of all employees whose salary is greater than Rs.5000/- and verify it. SELECT e.last_name,e.phone_no,e.salary,j.job_id FROM employees e, jobs j WHERE salary>5000; 6.Write a query to display the department name,location id,last name and salaries of all employees who works in location 1800 and verify it. SELECT e.dept_name,e.last_name,l.loc_id,e.salary FROM employees e, location l WHERE l.loc_id IN (1800);

7.Write a query to display the name ,department name and city of all employees who earn a commision and verify it. SELECT e.last_name,e.dept_name,l.city FROM employees e,location l WHERE e.comm_pct IS NOT NULL;

OUTER JOINS

LEFT OUTER JOIN: SYNTAX: SELECT table1.column,table2.column FROM table1,table2 WHERE table1.column(+) = table2.column; SQL> select e.ename,d.dname from emp e,dep d where e.dno(+)=d.dno;

ENAME

DNAME

---------- ---------------xxx admin yyy finance abc finance zzz hr market sales

RIGHT OUTER JOIN:

SYNTAX: SELECT table1.column,table2.column FROM table1,table2 WHERE table1.column = table2.column(+);


ENAME DNAME ---------- --------------bbc xxx admin yyy finance zzz hr abc finance

Selecting Rows using Left Outer Joins:


8. Write a query to display the last name,department id and department name of a employees . Make sure that employees without department are included as well and verify it. SELECT e.last_name,e.dept_id,d.dept_name FROM employees e, department d WHERE e.dept_id (+) = d.dept_id;

9.Write a query to display the last_name,department id ,salary and department name of all employees. Make sure that departments without employees are included as well and verified. SELECT e.last_name,e.salary,e.dept_id FROM employees e,departments d WHERE d.dept_id = d.dept_id (+);

SELF JOINS SELFJOIN----TO DISPLAY ENAME & THEIR MANAGER NAMES


SQL> select e.ename,m.ename from emp e,emp m where e.mgrid=m.eid; ENAME ENAME ---------- ---------bbc yyy yyy xxx zzz yyy

SELFJOIN----TO DISPLAY MANAGER'S SALARY FOR EVERY EMPLOYEE

SQL> select e.ename,m.esal from emp e,emp m where e.mgrid=m.eid;


ENAME ESAL ---------- ---------------bbc 2000 yyy 4000 zzz 2000

Selecting Rows using Self Joins:


10.Write a query to find and display the last name of each employees manager and verify it.

Employees Manager Kumar works for Rajesh


SELECT w.last_name || work for || m.last_name AS Employees Manager FROM employees w,employees m WHERE w.manager_id = m.emp_id;

CROSS JOIN

Selecting Rows using Cross Join: [ like cartesian product


of 2 tables]

11.Write a query to displaythe last name and department name of all employees and verify it. SELECT last_name, dept_name FROM employees CROSS JOIN departments;

NATURAL JOIN (or) INNER JOIN Selecting Rows using Natural or Inner join: [like equijoin]
12.Write a query to display the department id , department name , location id and city and verify it. SELECT dept_id,dept_name,location_id,city FROM departments NATURAL JOIN locations;

13.Write a query to display the department id , department name , location id and city. Limits the rows outputs to those with department id are equal to 20 or 50 and verify it. SELECT dept_id , dept_name , loc_id , city FROM departments NATURAL JOIN locations WHERE dept_id =20 OR dept_id=50;

JOIN with USING Clause Selecting Rows using Join with USING Clause: [like Non_equi_join]
14.Write aquery to display employee id, last name and location id of all employees and verify it. SELECT e.emp_id,e.last_name,l.loc_id FROM employees e JOIN Departments USING (dept_id); 15.Write a query to display location id and department name . Limits the row outputs to those with location id 4000 and verify it. SELECT e.last_name,d.dept_name,l.loct_id FROM employees e JOIN departments d USING (dept_id) WHERE loc_id = 1400;

JOIN with ON Clause

Selecting Rows using Join with ON Clauses:[like self_join]


16.Write a query to display the employee id, last name, department id, department name and loction id of all employees and verify it. SELECT e.emp_id,e.last_name,e.dept_id,d.dept_id,d.loc_id FROM employees e JOIN departments d ON (e.dept_id = d.dept_id);

17.Write a query to display the employee id,last name,department id and department name and loction id of all employees whose manager id is 149 and verify it. SELECT e.emp_id,e.last_name,d.dept_id,d.dept_id,d.dept_name, FROM employees WHERE e.manager_id=149;

OUTER JOIN with ON Clause LEFT OUTER JOIN with ON Clause:

Selecting Rows using Left Outer Join with ON Clause:


18.Write a query to display thw last name , department id and department name

of all employees. Make sure that employees without department are included as well and verify it. SELECT e.last_name,e.dept_id,d.dept_name FROM employees e LEFT OUTER JOIN department d ON (e.dept_id = d.dept_id);

RIGHT OUTER JOIN with ON Clause Selecting Rows using Right Outer Join with ON Clause:
19.Write a query to display the last name , department id and department name of all employees.Make sure that departments without employees are includee as well and verify it. SELECT e.last_name,e.dept_id,d.dept_name FROM employees e RIGHT OUTER JOIN departments d ON (d.dept_id=e.dept_id);

FULL OUTER JOIN with ON Clause


SQL>select e.ename,d,dname from emp e,dep d where e.dno(+)=(+)d.dno; ENAME DNAME bbc xxx admin yyy finance zzz hr abc finance market sales

Selecting Rows using Full Outer Join with ON Clause:


20.Write a query to display the last name,department id and department name of all employees. Make sure the following condition and verify it. Employees without departments are includee as well. Departments without employees are included as well. SELECT e.last_name,d.dept_id,d.dept_name FROM employees e FULL OUTER JOIN departments d ON (d.dept_id = e.dept_id);

UNION OPERATOR Selecting Rows using Union Operator : [Eliminates duplicate records]
21.Write a query to display the current and previous job details of all employees without duplication and verify it . SELECT emp_id,job_id FROM employees UNION SELECT emp_id,job_id FROM job_histroy;

22.Write a query to display the current and previous job details of all employees in each department without duplication and verify it. SELECT emp_id,job_id FROM employees UNION SELECT emp_id job_id,dept_id FROM job_history GROUP BY dept_id ORDER BY emp_id;

INTERSECT OPERATOR

Selecting Rows using Intersect Operator:[Return all rows common to multiple queries]
23.Write a query to disdplay the employees id and job id of employees who currently have Job title that they held before beginning their tenure with the company. SELECT emp_id,job_id FROM employees INTERSECT SELECT emp_id,job_id FROM job_history;

MINUS OPERATOR Select Rows using Minus Operator:[first SELECT second SELECT]
24.Write a query to display the employee id and job id of those employees who have not changed their jobs even once and verify it. SELECT emp_id,job_id FROM employees MINUS SELECT emp_id,job_id FROM jobs;

RESULT:

Creating Views:

1. SQL> CREATE VIEW vw_emp80(id_number, name, salary) AS SELECT

emp_id, last_name, salary FROM employees WHERE dept_id=80; Verified By: SQL> DESC vw_emp80; Name ----------------ID_NUMBER NAME SALARY Null? --------------NOT NULL NOT NULL Type -------------------NUMBER(6) VARCHAR2(25) NUMBER(8,2)

2. SQL> SELECT * FROM vw_emp80; ID_NUMBER ---------- -----149 174 176 NAME ----------kumar abel raman SALARY ------------10500 11000 8600

3. SQL> CREATE VIEW vw_sal50(id_number, Name,"Annual_Salary") AS

SElect emp_id, last_name, salary*12 FROM employees WHERE dept_id=50; View created. Verified By: SQL> DESC vw_sal50; Name Null? Type ----------------------------------------- -------- ---------------------------ID_NUMBER NOT NULL NUMBER(6) NAME NOT NULL VARCHAR2(25) Annual_Salary NUMBER

4. SQL> SELECT * FROM vw_sal50; ID_NUMBER NAME Annual_Salary ---------- ------------------------- -------------

124 petersen 141 kumar 142 kumari 143 radha 144 prabha

69600 42000 37200 31200 30000

Creating Views with Group Functions: 5. SQL> CREATE OR REPLACE VIEW vw_dept_sal(Dept_Name, Min_Sal, Max_Sal) AS SELECT d.dept_name, MIN(e.salary), MAX(e.salary) FROM employees e, departments d WHERE e.dept_id=d.dept_id GROUP BY dept_name; Verified By: DESC vw_dept_sal; NAME NULL? Dept_name MIN_Sal MAX_Sal AVG_Sal TYPE VARCHAR2(30) NUMBER NUMBER NUMBER

6. SQL> SELECT dept_name, MIN_Sal FROM vw_dept_sal; DEPT_NAME ----------------Accounting Administration . . 7 rows selected. 7. MIN_SAL ------------10 000 44 000

CREATE or REPLACE VIEW vw_job_sal(JOB_NAME, MIN_SAL, MAX_SAL) AS SELECT j.job_title, MIN(e.salary), MAX(e.salary) FROM employees e, jobs j GROUP BY dept_id; Verified By: DESC vw_job_sal; NAME NULL JOB_NAME MIN_SAL MAX_SAL TYPE VARCHAR2(35) NUMBER NUMBER

8. SQL> SELECT job_name, MAX_SAL FROM vw_job_sal; JOB_NAME ---------------President Administration assistant . MAX_SAL -------------40 000 6 000

. 12 rows selected Creating Views with Check Function:


9. SQL> CREATE OR REPLACE VIEW vw_emp20 AS SELECT * FROM

employees WHERE dept_id=20 WITH CHECK OPTION CONSTRAINT vw_emp20_ck; View created. Verified By: SQL> desc vw_emp20; Name ---------------------EMP_ID FIRST_NAME LAST_NAME EMAIL PHONE_NO HIRE_DATE JOB_ID SALARY COMM_PCT MANAGER_ID DEPT_ID Null? ---------------NOT NULL Type ---------------------------NUMBER(6) VARCHAR2(20) VARCHAR2(25) VARCHAR2(30) VARCHAR2(20) DATE VARCHAR2(10) NUMBER(8,2) NUMBER(2,2) NUMBER(6) NUMBER(4)

10. SQL> select emp_id,last_name,dept_id from vw_emp20; EMP_ID --------------201 Kumar 202 Kumar LAST_NAME -------------------20 20 DEPT_ID ---------------

11. SQL> update vw_emp20 set salary=15000 where emp_id=201; 1 row updated. Verified By: SQL> select salary from vw_emp20 where emp_id=201; SALARY ---------15000

12. SQL> update vw_emp20 set dept_id=10 where emp_id=201; view WITH CHECK OPTION where-clause violation. Reason: No rows are updated because if the dept_id where to change to 10, a view would no longer will able to see that employee. The view can see only department in dept20 and does not allow dept_id for those employees to be changed. Creating Views with Read Only Option:
13.

SQL> create or replace view vw_emp10(employee_id,employee_name,job_id) as select emp_id,last_name,job_id from employees where dept_id =10; View created. Verified By: SQL> desc vw_emp10; Name ---------------------------EMPLOYEE_ID EMPLOYEE_NAME JOB_ID Null? --------------NOT NULL Type --------------------------NUMBER(6) VARCHAR2(25) VARCHAR2(10)

14. SQL> select employee_id,employee_name,job_id from vw_emp10; EMPLOYEE_ID ---------------------200 Antony EMPLOYEE_NAME --------------------------AD_ASST JOB_ID ----------

15. SQL> delete from vw_emp10 where employee_id=200; integrity constraint (IICSEA_327.EMP_ID_JOBHIS_FK) violated - child record found Reason: Any attempt to insert a row or modify a row using the View with read only constraints results in Oracle server Error. Dropping the Views: 16. SQL> drop view vw_emp80; View dropped.

Selecting Rows with Inline Views and Top-N Analysis:


17.

SQL> select rownum as rank,e.last_name,e.salary from(select last_name,salary from employees order by salary desc)e where rownum<=3; LAST_NAME ------------------King Kumar Raj SALARY ---------34320 24310 18700

RANK --------1 2 3
18.

SQL> select rownum as senior,e.last_name,e.hire_date from(select last_name,hire_date from employees order by salary asc)e where rownum<=5; SENIOR -----------1 2 3 4 5 LAST_NAME -------------------Prabha Radha Kumari Kumar Lorentz HIRE_DATE -------------------09-JUL-08 15-MAR-08 29-JAN-07 17-OCT-95 07-FEB-09

19.

SQL> select rownum as rank,e.last_name,e.salary from(select last_name,salary from employees order by salary asc)e where rownum<=5; RANK ---------1 2 3 4 5 LAST_NAME ------------------Prabha Radha Kumari Kumar Lorentz SALARY ------------2750 2860 3410 3850 4620

20.

SQL> select rownum as senior,e.last_name,e.hire_date from(select last_name,hire_date from employees order by salary desc)e where rownum<=3; SENIOR -----------1 2 3 LAST_NAME ------------------King Kumar Raj HIRE_DATE ------------------17-JUN-97 21-SEP-99 13-JAN-93

RESULT:

Bind Variables:
1. Verified By (Before):

SQL> SELECT emp_id, salary FROM employees WHERE emp_id=178; EMP_ID ---------178 SALARY ---------7000

PL/SQL Block: SET SERVEROUTPUT ON VARIABLE g_salary NUMBER BEGIN SELECT salary INTO :g_salary FROM employees WHERE emp_id=178; DBMS_OUTPUT.PUT_LINE('The Salary is assigned to the bind variable..!!!'); END; / The Salary is assigned to the bind variable..!!! PL/SQL procedure successfully completed. Verified By (After): SQL> PRINT :g_salary; G_SALARY ---------7000 2. Verified By (Before): SQL> SELECT emp_id, last_name FROM employees WHERE emp_id=101; EMP_ID LAST_NAME ---------- ------------------------101 Kumar PL/SQL Block: SQL> VARIABLE g_lname VARCHAR2(25) BEGIN SELECT last_name INTO :g_lname FROM employees WHERE emp_id=101; DBMS_OUTPUT.PUT_LINE(' The last name is assigned to the Bind Variable..!!!'); END;

/ The last name is assigned to the Bind Variable..!!! PL/SQL procedure successfully completed. Verified By (After): SQL> PRINT :g_lname; G_LNAME --------------Kumar 3. PL/SQL Block: SQL> DEFINE p_annual_sal=60000 SQL> VARIABLE g_monthly_sal NUMBER SQL> DECLARE 2 v_monthly_sal NUMBER(9,2):=&p_annual_sal; 3 4 BEGIN 5 v_monthly_sal := v_monthly_sal/12; 6 :g_monthly_sal := v_monthly_sal; 7 DBMS_OUTPUT.PUT_LINE('The monthly salary is ' || TO_CHAR(v_monthly_sal)); 8 END; 9 / old 2: v_monthly_sal NUMBER(9,2):=&p_annual_sal; new 2: v_monthly_sal NUMBER(9,2):=60000; The monthly salary is 5000 PL/SQL procedure successfully completed. Verified By (After): SQL> PRINT g_monthly_sal; G_MONTHLY_SAL ------------5000

4. Verified By (Before):

SQL> SELECT emp_id, salary, hire_date FROM employees WHERE emp_id=100; EMP_ID SALARY HIRE_DATE ---------- ---------- --------100 24000 17-JUN-97 PL/SQL Block: SQL> DECLARE 2 v_hire_date employees.hire_date %TYPE; 3 v_salary employees.salary %TYPE; 4 v_emp_id NUMBER NOT NULL := 100; 5 BEGIN 6 SELECT hire_date, salary INTO v_hire_date, v_salary FROM employees WHERE emp_id=v_emp_id; 7 DBMS_OUTPUT.PUT_LINE('The hire date is ' || v_hire_date); 8 DBMS_OUTPUT.PUT_LINE('The Salary is '|| v_salary); 9 END; 10 / The hire date is 17-JUN-97 The Salary is 24000 PL/SQL procedure successfully completed.
5. Verified By (Before):

SQL> SELECT SUM(salary) AS sum FROM employees WHERE dept_id=60; SUM ---------19200 PL/SQL Block: DECLARE v_emp_id employees.emp_id %TYPE; v_sum_salary employees.salary %TYPE; v_dept NUMBER NOT NULL := 60; BEGIN SELECT emp_id, SUM(salary) INTO v_emp_id, v_sum_salary FROM employees WHERE emp_id=v_dept; DBMS_OUTPUT.PUT_LINE('The Sum of Salaries is ' || v_sum_salary);

END; Procedure successfully completed


6. Verified By (Before):

SQL> SELECT salary FROM employees WHERE job_id='ST_CLERK'; SALARY ---------3500 3100 2600 2500 PL/SQL Block: SQL> DECLARE 2 v_salary_inc employees.salary%TYPE := 500; 3 BEGIN 4 UPDATE employees SET salary=salary+v_salary_inc WHERE job_id='ST_CLERK'; 5 DBMS_OUTPUT.PUT_LINE('The Salary is Updated..!!!'); 6 END; 7 / The Salary is Updated..!!! PL/SQL procedure successfully completed. Verified (After): SQL> SELECT salary FROM employees WHERE job_id='ST_CLERK'; SALARY ---------4000 3600 3100 3000 7. Verified By (Before): SELECT emp_id, last_name, dept_id FROM employees WHERE dept_id=10; Emp_id ---------200 Last_name ------------Whalen Dept_id ----------10

PL/SQL Block: BEGIN Delete from employees where dept_id=10; END; / Verified (After): SELECT emp_id, last_name, dept_id from employees where dept_id=10; No rows selected. 8. Verified By (Before): SQL> SELECT last_name, job_id, dept_id FROM employees WHERE last_name='Petersen'; LAST_NAME -----------------Petersen JOB_ID DEPT_ID ------------------ST_MAN 50

PL/SQL Block: DECLARE v_name employees.last_name%TYPE; v_job employees.job_id%TYPE := 'MK_MAN'; v_deptid employees.dept_id%TYPE :=20; BEGIN SELECT last_name INTO v_name FROM employees WHERE last_name='Petersen'; IF v_name='Petersen' THEN UPDATE employees SET job_id=v_job WHERE last_name=v_name; UPDATE employees SET dept_id=v_deptid WHERE last_name=v_name; DBMS_OUTPUT.PUT_LINE('Updated the Record ..!!!'); END IF; END; / PL/SQL procedure successfully completed. Verified (After): SQL> SELECT last_name, job_id, dept_id FROM employees WHERE last_name='Petersen'; LAST_NAME -------------------Petersen JOB_ID ----------MK_MAN DEPT_ID ---------20

9. Verified By (Before): Select salary,dept_id from employees;

SALARY DEPT_ID ----------------------18700 10 18700 10 PL/SQL Block: DECLARE V_dept_id employees.dept_id % TYPE; V_salary employees.salary %TYPE; BEGIN SELECT dept_id,v_dept_id FROM employees IN dept_id=10, THEN Update employees v_salary=5000; ELSE IF v_dept_id =80 UPDATE employees v_salary =7500; ELSE IF UPDPATE employees SET v_salary=2000; END IF; END IF; END IF; END; / PL/SQL procedure successfully completed Verified (After): SELECT salary , dept_id FROM employees WHERE dept_id=10; SALARY -----------5000 5000
10.

DEPT_ID ----------10 10

Verified By (Before): SELECT salary FROM employees WHERE job_id=ST_CLERK;

SALARY ----------4500 3100 4600 3500 PL/SQL Block: DECLARE V_salary_inc employees.salary %TYPE := 500; BEGIN FOR I in 1..2 LOOP

UPDATE employees SET salary=salary+v_salary_inc WHERE job_id =ST_CLERK; END LOOP; END; / PL/SQL procedure successfully completed Verified (After): SALARY ----------5000 3600 5100 4000 11. PL/SQL Block: DECLARE num number := 100; BEGIN WHILE num<= 250 LOOP num:= num + 25; END LOOP; DBMS_OUTPUT.PUT_LINE( 'The Value of variable num is :' ||num ); END; / The value of variable num is :275 PL/SQL procedure successfully completed.

12. PL/SQL Block: DECLARE Var number:=50; BEGIN WHILE var<=250 LOOP Var:=var+50; END LOOP; DBMS_OUTPUT.PUT_LINE (The value of variable var is : || var); END; / The value of variable var is :300 PL/SQL procedure successfully completed.

13. PL/SQL Block: DECLARE

num number := 100; BEGIN LOOP num:= num + 25; EXIT WHEN num=250; END LOOP; DBMS_OUTPUT.PUT_LINE( TO_CHAR(num)); END; / 250 PL/SQL procedure successfully completed. 14.PL/SQL Block: DECLARE Var number :=50 BEGIN LOOP var:=var+50; EXIT WHEN var=300; END LOOP DBMS_OUTPUT.PUT_LINE(TO_CHAR(var)); END; / 300 PL/SQL procedure successfully completed. 15. Verified By (Before): SELECT last_name, job_id , dept_id FROM employees WHERE last_name=Petersen; LAST_NAME ---------------Petersen JOB_ID --------MK_MAN DEPT_ID ----------20

PL/SQL Block: DECLARE V_name employees.last_name%type; V_job employees.job_id %TYPE := MK_MAN;

V_deptid employees.dept_id %TYPE :=20; BEGIN SELECT last_name INTO v_name FROM employees WHERE last_name = Petersen;

IF v_name =petersen THEN GOTO updation; END IF; <<Updation>> UPDATE employees SET job_id = v_job_id WHERE last_name =v_name; UPDATE employees SET dept_id = v_dept_id WHERE last_name = v_name; DBMS_OUTPUT.PUT_LINE(Updated the record!!!); END; / Updated the record!!! PL/SQL procedure successfully completed. Verified By (After): SELECT last_name, job_id, dept_id FROM employees WHERE last_name=petersen; LAST_NAME ----------------Petersen JOB_ID ---------MK_MAN DEPT_ID ---------20

16. Verified By: SELECT emp_id, last_name FROM employees WHERE emp_id=300; No rows selected. PL/SQL Block: DECLARE v_emp_id employees.emp_id%TYPE; BEGIN SELECT emp_id INTO v_emp_id FROM employees WHERE emp_id=300; Exception WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE( 'Record for employee ID 300 is not available..!!!'); END; / Record for employee Id 300 is not available!!! PL/SQL procedure successfully completed. 17. Verified By : SELECT emp_id, last_name FROM employees WHERE emp_id=400;

no rows selected. PL/SQL Block: DECLARE

v_emp_id employees.emp_id%TYPE; BEGIN SELECT emp_id INTO v_emp_id FROM employees WHERE emp_id=400; Exception WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE( 'Record for employee ID 400 is not available..!!!'); END; / Record for employee ID 400 is not available..!!! PL/SQL procedure successfully completed. 18. Verified By: SELECT last_name, job_id, salary FROM employees WHERE job_id='IT_PROG';

LAST_NAME ---------------Pandian Kumar Lorentz

JOB_ID ---------IT_PROG IT_PROG IT_PROG

SALARY ------------10890 7260 5082

PL/SQL Block: DECLARE Ex_lowsal EXCEPTION; V_salary employees.salary % TYPE; BEGIN SELECT MIN(salary) INTO v_salary FROM employees WHERE job_id=IT_PROG; IF v_salary < 5000 THEN RAIS ex_lowsal; END IF; EXCEPTION WHEN ex_lowsal THEN DBMS_OUTPUT.PUT_LINE(Very low salary for IT programmers!!!); END; / Very low salary for IT programmers!!! PL/SQL procedure successfully completed.

19. Verified By: SELECT emp_id, manager_id last_name FROM employees WHERE emp_id=100; EMP_ID MANAGER_ID LAST_NAME

--------100

--------------

------------------King

PL/SQL Block: DECLARE Ex_manager EXCEPTION; BEGIN SELECT manager_id INTO v_managerid FROM employees WHERE dept_id=100; IF v_managerid = NULL THEN EXCEPTION ex_manager END IF; DBMS_OUTPUT.PUT_LINE (Employee Id 100 has NO manager!!!!); END; / Employee Id 100 has NO manager!!!! PL/SQL procedure successfully completed. 20. Verified By: SELECT last_name from employees WHERE last_name='Rajeshwari'; No rows selected PL/SQL Block: DECLARE Ex_noemp EXCEPTION V_lname employees.last_name %TYPE; BEGIN DELETE FROM employees WHERE last_name=Rajeshwari; IF SQL % NOT FOUND THEN RAISE ex_noemp; ELSE DBMS_OUTPUT.PUT_LINE(Employee Rajeshwari Record is deleted!!!); END IF; EXCEPTION WHEN ex_noemp THEN RAISE_APPLICATION_ERROR(-20001,Rajeshwari is not a valid employee); END; / ORA.-20001: Rajeshwari is not a valid employee

PL/SQL procedure successfully completed.

RESULT:

Creating Procedures:
1. Verified By(Before):

SQL> SELECT salary FROM employees; SALARY ---------24000 17000 17000 : 20 rows selected. PL/SQL Block: SQL> CREATE OR REPLACE PROCEDURE proc_raise_salary_all IS BEGIN UPDATE employees SET salary=salary*1.10; END; / Procedure created. SQL> EXECUTE proc_raise_salary_all; PL/SQL procedure successfully completed. Verified By (After): SQL> SELECT salary FROM employees; SALARY ---------29040 20570 20570 : 20 rows selected.
2. Verified By(Before):

SQL> SELECT mark1 FROM students;

MARK1 ---------78 89 78 : 7 rows selected. PL/SQL Block: SQL> CREATE OR REPLACE PROCEDURE proc_raise_mark_all IS BEGIN UPDATE students SET mark1=mark1+5; END; / Procedure created. SQL> EXECUTE proc_raise_mark_all; PL/SQL procedure successfully completed. SQL> SELECT mark1 FROM students; MARK1 ---------83 94 83 : 7 rows selected. Creating procedures with parameters: IN, OUT, INOUT parameters
3. Verified By (Before):

SQL> SELECT salary FROM employees WHERE emp_id=101; SALARY ---------18700 PL/SQL Block:

SQL> CREATE OR REPLACE PROCEDURE proc_raise_salary( p_emp_id IN employees.emp_id%TYPE) IS BEGIN UPDATE employees SET salary= salary * 1.30 WHERE emp_id=p_emp_id; END; / Procedure created. SQL> EXECUTE proc_raise_salary(101); PL/SQL procedure successfully completed. SQL> SELECT salary FROM employees WHERE emp_id=100; SALARY --------24310

04. Verified by (Before): SQL> SELECT * FROM students WHERE roll_no=7; ROLL_NO NAME MARK1 MARK2 ---------- ------------------------------ ---------- ---------- ---------7 Yogeswari 94 56 97 MARK3

PL/SQL Block: SQL> CREATE OR REPLACE PROCEDURE proc_del_stu( p_roll_no IN students.roll_no%TYPE) IS BEGIN DELETE FROM students WHERE roll_no=p_roll_no; END; / Procedure created. SQL> EXECUTE proc_del_stu(7); PL/SQL procedure successfully completed.

Verified by(After):

SQL> SELECT * FROM students WHERE roll_no=7; no rows selected.

05. PL/SQL Block: SQL> CREATE OR REPLACE PROCEDURE proc_sal_comm ( p_emp_id IN employees.emp_id%TYPE, p_name OUT employees.last_name%TYPE, p_salary OUT employees.salary%TYPE, p_comm OUT employees.comm_pct%TYPE) IS BEGIN SELECT last_name, salary, comm_pct INTO p_name, p_salary, p_comm FROM employees WHERE emp_id=p_emp_id; END; / Procedure created. Viewing OUT parameter values: 06. SQL> VARIABLE g_name VARCHAR2(25) SQL> VARIABLE g_sal NUMBER SQL> VARIABLE g_comm NUMBER SQL> EXECUTE proc_sal_comm(107, :g_name, :g_sal, :g_comm); PL/SQL procedure successfully completed. SQL> PRINT :g_name G_NAME --------------------Lorentz SQL> SELECT last_name, salary, comm_pct FROM employees WHERE emp_id=107; LAST_NAME SALARY COMM_PCT ------------------------- ---------- ---------Lorentz 4620 SQL> CREATE OR REPLACE PROCEDURE proc_mail_job ( p_emp_id IN employees.emp_id%TYPE,

07.

p_name OUT employees.last_name%TYPE, p_mail OUT employees.email%TYPE, p_job OUT employees.job_id%TYPE) IS BEGIN SELECT last_name,email,job_id INTO p_name,p_mail,p_job FROM employees WHERE emp_id=p_emp_id; END; / Procedure created Viewing OUT parameters values: 08. SQL> VARIABLE g_name VARCHAR2(25) SQL> VARIABLE g_email VARCHAR2(25) SQL> VARIABLE g_jobid NUMBER SQL> EXEC proc_mail_job(142,:g_name,:g_email,:g_jobid); Procedure successfully completed SQL> PRINT :g_name :g_email :g_jobid; G_NAME ---------------Kumari G_EMAIL ---------------chitkum@gmail.com G_JOBID ---------------ST_CLERK SQL> SELECT last_name,email,job_id FROM employees WHERE emp_id=142; LAST_NAME EMAIL JOB_ID ----------------------------------------------------------------------------------------Kumari chitkum@gmail.com ST_CLERK

09.

SQL> CREATE OR REPLACE PROCEDURE proc_format_phone (p_phone IN OUT VARCHAR2) IS BEGIN

p_phone:=( || SUBSTR(p_phone,1,3) || ) || SUBSTR(p_phone,4,4) || - || SUBSTR(p_phone,8,4); END; / Procedure created Viewing IN OUT parameter values: 10. SQL> VARIABLE g_phone_no VARCHAR2(15) BEGIN :g_phone_no := (04426530708); END; / PL/SQL procedure successfully completed SQL> PRINT :g_phone_no; G_PHONE_NO -------------------------04426530708 SQL> EXEC proc_format_phone(:g_phone_no); PL/SQL procedure successfully completed SQL> PRINT :g_phone_no; G_PHONE_NO -------------------------(044)2653-0708 Creating functions: 11. SQL> CREATE OR REPLACE FUNCTION func_get_sal (f_empid IN employees.emp_id%TYPE) RETURN NUMBER IS v_salary employees.salary%TYPE :=0; BEGIN SELECT salary INTO v_salary FROM employees WHERE emp_id=f_empid; RETURN v_salary; END; / Function created

12.

SQL> SELECT func_get_sal(107) FROM DUAL;

FUNC_GET_SAL(107) ----------------------------------4620 13. SQL> CREATE OR REPLACE FUNCTION tax(p_value IN NUMBER) RETURN NUMBER; IS BEGIN RETURN (p_value * 0.08); END; / Function created 14. SQL> SLECET emp_id,last_name,salary,tax(salary) FROM employees WHERE dept_id=90; EMP_ID LAST_NAME SALARY TAX(SALARY) -------------------------------------------------------------------------------------------100 King 26400 2112 101 Kumar 24313 1944.8 102 Raj 18700 1496

RESULT:

Triggers:
1. SQL>CREATE OR REPLACE TRIGGER trg_sec_ins BEFORE INSERT ON employees BEGIN IF(TO_CHAR(SYSDATE,DY) IN (SAT,SUN)) OR (TO_CHAR(SYSDATE,HH24:MI) NOT BETWEEN 08:00 AND 18:00) THEN RAISE_APPLICATION_ERROR(-20501,You may insert into employees table only during business hours); END IF; END; /

Trigger created.

2. SQL>INSERT INTO employees VALUES (178,Arun,Kumar,arunkumar@gmail.com,9996655031,to_date(Jun 17,1997,MON DD YYYY) ad_pres,2400,NULL,NULL,90);

Error at line 1:

ORA-20501: You may inset into employees table only during business hours ORA-06512: atiicsea_12.TRG_SEC_INS,line 4

ORA-04088: error during execution of trigger iicsea_12.TRG_SEC_INS

3. SQL>CREATE OR REPLACE TRIGGER trg_sec_ins BEFORE INSERT ON employees BEGIN IF(TO_CHAR(SYSDATE,DY) IN (SAT,SUN)) OR (TO_CHAR(SYSDATE,HH24:MI) NOT BETWEEN 08:00 AND 18:00) THEN IF INSERTING THEN RAISE_APPLICATION_ERROR(-20501,You may insert into employees table only during business hours!!!); ELSIF UPDATING(salary) THEN RAISE _APPLICATION_ERROR(-20502,You may update records into employees table only during business hours!!!); ELSIF DELETING THEN RAISE_APPLICATION_ERROR(-20503,You may delete records into employees table only during business hours!!!); ELSE RAISE_APPLICATION_ERROR(-20504, You may update records into employees table only during business hours!!!);

END IF; END IF; END; / Trigger created.

4. SQL>UPDATE employees set salary=salary+1000 WHERE emp_id=101; Error at line 1: ORA-20502: You may insert into employees table only during business hours!!! ORA-60512:at iicsea_12 TRG_SEC_EMP, LINE 7

ORA-04088: Error during execution of trigger iicsea_12 TRG_SEC_EMP

5. SQL>DELETE FROM employees WHERE emp_id=200; Error at line 1: ORA-20503: You may insert into employees table only during business hours!!! ORA-06512: AT IICSEA_12 trg_sec_emp, line 9 ORA-04088: ERROR during execution of trigger iicsea_12 TRG_SEC_EMP

6. SQL>CREATE OR REPLACE TRIGGER trg_audit_empval AFTER INSERT OR UPDATE OR DELETE ON employees FOR EACH ROW BEGIN INSERT INTO trg_audit_empval (user_name, timestamp, id, old_lname, new_lname, old_title, new_title, old_sal, new_sal) VALUES (USER, SYSDATE, :OLD.emp_id, :OLD.last_name, :NEW.last_name, :OLD.job_id, :NEW.job_id, :OLD.salary, :NEW.salary); END; / Trigger created.

7. SQL>ALTER TABLE employees DISABLE trg_sec_emp; Table altered.

8. SQL>UPDATE employees SET salary=salary+1000 WHERE emp_id=101; 1 row updated.

9. SQL>ALTER TABLE order_master DISABLE ALL TRIGGERS;

Table altered. 10. INSERT INTO employees VALUES (177, Arun,Kumar,arun@gmail.com, 9977886655, 14-Dec2011,ST_CLERK, 4000,5,100,90); 1 row inserted.

11. ALTER TABLE employees ENABLE trg_sec_emp; Table altered.

12. ALTER TABLE employees DISABLE ALL TRIGGERS; Table created.

13. DROP TRIGGER trg_audit_empval; Trigger Dropped.

RESULT:

FORMS WITH SINGLE BLOCK

AIM:

Introduction to Oracle Form Builder:

Oracle Forms Builder provides two main wizards to create data blocks: 1. The Data Block wizard guides through the steps of choosing a base table and columns. 2. The Layout wizard guides through arranging the base table and columns on the form.
Steps to Create a Single Block:

I.

Creating a New Block:

1.

To create a new block, pull down the Tools menu and select the

Data Block wizard menu item. The dialog box will appear. Click on the Next button.

2.

Choose Table/View and click on the Next button.

3.

Choose a base table and columns that will belong to the data block.

To associate a database table with the block, click on the Browse... button to the right of the Table or View field.

4.

Make sure the Current User and Tables buttons are selected.

5.

Highlight the name of the database table EMPLOYEES and click on

the OK button.

6.

The wizard should reappear with the name of the table and a list of

available columns displayed.

7.

To include a column in the data block, highlight the column name

and click on the right arrow. The name of the column should move over to the right hand side. 8. Click on the Next button, a dialog box will appear allowing you to name the data block as EMPLOYEES.

9.

Click the Next button and the final dialog box for the Data Block

wizard will appear. Make sure the Create the block, then call the Layout wizard option is selected and click on the Finish button.

10.

The data block will be created. The objects created include the

EMPLOYEE data block containing items for each of the columns that were

selected.

11.

Once the new data block and items are created, the first dialog box

in the Layout wizard will appear. Click on the Next button and a dialog box will appear.

12.

The layout for a data block may be placed on any existing canvas.

In this case, there are no existing canvases so the only option available is to create a new canvas. Click on the Next button.

13.

In the next dialog box, the columns from a given base table on a

data block can be added to the layout. Since we are laying out the
EMPLOYEE data block, it is highlighted automatically. Move all of the Available Columns over to the Displayed Items side by clicking on the double right arrow and click on the Next button.

14.

In the next dialog box, the field labels, field sizes and field heights

can be altered and click on the Next button.

15.

In the next dialog box, choose a Form layout and click on the Next

button.

16.

In the next dialog box, type a title for the frame (around the data

block) and check the option to include a scroll bar.

17.

Click on the Next button and the final dialog box for the Layout

wizard will appear.

18.

Click on the Finish button to create the layout. A new Canvas will be

created with the new block.

19.

Click Tools menu Object Navigator EMPLOYEES will display

that data block's properties.

20. table.
II.

Specify a WHERE clause to filter the selection of rows from the base

Saving, Compiling and Running Forms:

1. To save a form, select File menu Save menu item. Click on the Save button to save the file name employee.fmb

2. To compile a form, select Program menu Compile Module menu item.

3. To run a form,
StartProgramsOracle Developer SuiteForms DeveloperStart OC4J Instance III. Query By Example:

1. Select Query menu Enter Query, it places the form in Enter Query mode. In this mode, the form is cleared and the user can navigate in the various fields.

2. Enter the value 50 in the department id Text Box, then select Query menu Execute; it will display the employees records who is working in the department 50.

3. If no criteria are supplied, then all records in the table will be displayed.

OUTPUT:

RESULT:

FORMS WITH MASTER DETAILS:


AIM:

Steps to Create a Master - Details Block:

I.

Creating a Master Block: [Table - departments]

1.

In the Object Navigator, Choose Forms and select File menu

New Forms.

2.

Create a new block DEPARTMENTS that contains all of the

columns in the DEPARTMENTS table as same as single block creation.

3.

Save a form, select File menu Save. Click on the Save button to

save the file name Dept_Emp.fmb.

4.

Use the QBE features to retrieve only those departments with

department id 80. Then, do another QBE query to retrieve only those

departments with the letter A or a in their name.

II.

Creating a Details Block: [Table - employees]

1. In the Object Navigator, click on the Data Blocks branch of the


Dept_Emp form (do not click on the department data block).

2. Select Tools menu choose Data Block wizard. 3. Select the EMPLOYEES table and include the
FIRST_NAME,

LAST_NAME, HIRE_DATE, JOB_ID, SALARY, DEPT_ID columns.

4. The next step in the wizard will be to create a relationship between the existing data block DEPARTMENTS and the new block being created.

5. In next dialog box, De-select the Auto-join data blocks option. Click on the Create Relationship button to list the available data blocks.

6. In the next dialog box Relation Type, choose Based on a join condition and click the OK button.

7. When the list of blocks appears, choose the DEPARTMENTS data block. Arrange the Detail Item as DEPT_ID and Master Item as DEPT_ID such as that the join condition becomes:

EMPLOYEES.DEPT_ID = DEPARTMENTS.DEPT_ID

8. Name the data block EMPLOYEES.

9. Make sure the Create the block, then call the Layout wizard option is selected and click on the Finish button.

10.Be sure to choose the existing canvas CANVAS4 and include all of the items except the DEPT_ID as displayed.

11.The DEPT_ID column will still be a part of the EMPLOYEE data block; however, it will not be displayed.

12.In the next dialog box, choose the Tabular layout. Give the Frame Title as Department-wise Employee Details.

13.Select 5 Records displayed with 0 distances between records.

14. Save the form and then compile and run it.

Creating a new LOV(List of Values) Object:

1.

In the Edit menu, Choose Create menu item.

2.

The dialog box will appear, choose Use the LOV Wizard and then

click Ok.

3.

The LOV Wizard will appear, by default, New Record Group

based on a query is selected. Make sure this selection is highlighted

and then click the Next button.

4.

In the next screen, enter the LOV query as mentioned below and

press Connect button to connect to the EMS database.

SELECT dept_id FROM departments

5.

Then click the Build SQL Query button to build the query. After

the successful execution of the query, press Next button.

6.

The next step is to specify which columns in the record group will

be returned to for use by the LOV. Here it only returns dept_id so select that column and then click Next button.

III.

Test the LOV(List of Values) Object:

1. Save, Compile and Run the form. When entering new data, navigate to the dept_id (Department id) field. Notice the form, a message appears: List of Values indicating a list of values is available for this field.

OUTPUT: Department Details:

Department-wise Employee Details:

RESULT:

REPORTS WITH SINGLE BLOCK

AIM:

Steps to Create a Single Table Report:

I.

Specify the Data Model and Layout of the Report:

1. From the Object Navigator, pull down the Tools menu and choose
Report wizard...

2. The first screen for the reports wizard will appear. The first option is to decide the type of report to be created. Oracle Reports can be created to display on a web page (inside of a web browser), or by using the more traditional Oracle Reports runtime. The latter is called the
"Paper Layout". For this example, both types of layouts will be created.

Choose "Create both Web and Paper Layout" option is selected and click the Next button.

3. The wizard prompts for the style of the report and for the Report
Title. Type "Employees Report" as the title, chooses the Tabular Layout

and click on the Next button.

4. The next step is to specify the Type of query the report will be based on. Choose the "SQL Query" and click the next button.

5. The next step is to specify the query that will form the basis of the report. In this case, type the following query in the SQL Query
Statement text box (or) use the Query Builder to select the specified

columns from the employees table and click Next button.

SELECT emp_id, last_name, hire_date, job_id, salary FROM employees

Note: If you did not Connect to the database, you will be prompted for the Username, Password and Database.

6. In the next wizard dialog box, specify which columns from the SQL
Query will be displayed in the report output. To specify all columns,

click on the double right arrow (>>) to bring all of the Available Fields to the Displayed Fields side. Click the Next button.

7. In the next step, aggregate functions can be applied to the fields on the report to calculate the total salary of all employees as well as count the number of employees.

Highlight last_name and Click on Count button. Then click the Next button. Highlight Salary and Click on Sum button.

8. The next dialog box allows you to change the field labels and display widths for various fields in the report. Change the following label values and click the Next button.

Fields and Totals CountEMP_IDPerReport SumSALARYPerReport

Lables No. of Employees : Total Salary :

Width 10 10

9. As a final step, a design template can be applied to the report. Design templates include specifications for fonts, colors and layout of the report. Here, choose the "Blue" predefined template and then click on the Finish button.

10. After a short delay, the Reports Live Previewer will appear showing the report.

II.

Saving, Running and Generating the Report:

1. To save a report, Choose File menu Save option. The source code for Oracle Reports is saved in files with an .rdf file name extension.
Compiled and generated reports are saved with a .rep extension. Here,

save this report as employee.rdf.

2. Note that report files can also be saved as static HTML or XML files as well as Java Server Page (.JSP) files.

3. Once the report is saved, it can be run by choosing Program menu Run Web Layout or Run Paper Layout menu item.

The Paper Layout option will display the current report directly within a window inside of Reports Builder as was seen at the end of the report wizard.

The Web Layout will take the current report with a snapshot of the data as it is now in the database and save it to an HTML file.

III.

About Activity Screen:

1.

As the report is running, an Activity screen will appear

giving an indication of the processing that is currently underway.

2.

The Activity will go through 3 stages:

Client Activity while the queries are prepared. Server Activity when the queries are executed.

Finally Client Activity as the report is formatted.

4. When this is finished, the report will appear on screen.

OUTPUT:

Employees Details in Paper Layout:

Employees Details in Web Layout:

RESULT:

REPORTS WITH MASTER DETAIL BLOCK


AIM:

Steps to Create a Master-Detail Report:

I.

Specify the Master-Detail Data Model and Layout of the Report:

1.

From the Object Navigator, pull down the Tools menu and choose

Report wizard...

2.

The first screen for the reports wizard will appear. The first option

is to decide the type of report to be created. Oracle Reports can be created to display on a web page (inside of a web browser), or by using the more traditional Oracle Reports runtime. The latter is called the
"Paper Layout". For this example, both types of layouts will be created.

Choose Create both Web and Paper Layout" option is selected and click the Next button.

3.

The wizard prompts for the style of the report and for the Report

Title. Type "Department-wise Employees Reports" as the title, choose

the Group Above Layout and click on the Next button.

4.

The next step is to specify the Type of query the report will be

based on. Choose the "SQL Query" and click the next button.

5.

The next step is to specify the query that will form the basis of the

report. In this case, type the following query in the SQL Query
Statement text box and click Next button.

SELECT d.dept_name, e.emp_id, e.last_name, e.job_id, e.salary FROM departments d, employees e WHERE d.dept_id = e.dept_id

Note: If you did not Connect to the database, you will be prompted for the Username, Password and Database.

11. In the next wizard dialog box, specify which columns from the SQL
Query will be displayed in the report output.

Designate the dept_name field as a Group field (Level 1). Click on the dept_name field and then on the right arrow (>) button. To display all columns in the report, click on the double right arrow (>>) to bring all of the Available Fields to the Displayed Fields side. Click the Next button.

12. In the next step, aggregate functions can be applied to the fields on the report to calculate the average of salary for each department as well as for all employees.

Highlight Salary and Click on Average button.

13. The next dialog box allows you to change the field labels and display widths for various fields in the report. Change the following label values and click the Next button.

Fields and Totals Dept_name

Lables Department Name

Width 20

Emp_id Last_name Job_id salary AvgSALARYPerReport

Employee ID Last Name Job ID Salary Average :

6 10 10 8 10

14. As a final step, a design template can be applied to the report. Design templates include specifications for fonts, colors and layout of the report. Here, choose the "Blue" predefined template and then click on the Finish button.

IV.

Saving, Running and Generating the Report:

1. To save a report, Choose File menu Save option. The source code for
Oracle Reports is saved in files with an .rdf file name extension. Compiled and generated reports are saved with a .rep extension. Here, save this

report as dept_emp.rdf.

2. Note that report files can also be saved as static HTML or XML files as well as Java Server Page (.JSP) files.

OUTPUT:

Department-wise Employees Report in Paper Layout:

Department-wise Employees Report in Paper Layout:

RESULT:

ORACLE DATA CONTROL


AIM:

Steps to Create a Employee Details Form:

4. Create a Standard EXE project. 5. Choose the Project menu Components to add reference to the
Oracle Data Control.

6. The Oracle Data Control appears in the projects toolbox. Add an instance of the Oracle Data Control to the projects form and set the
name property as odc_empsal.

7. Set the caption property of Form1 as Employees Salary Details... 8. Add the 3 Label control in the form and set the name property as
lbl_title, lbl_lname and lbl_salary. Also set the caption property as Employees Salary Details, Employee Name and Salary. Also

change the Font property if needed. 9. Add the 2 textbox control in the form and name it as txt_lname and
txt_salary. Also clear the text property of both textbox.

10.In the odc_empsal control, set the following properties: i. ii. iii.
Connect username / password Database EMS Record Source SELECT last_name, salary FROM employees;

11.Set the txt_lnames and txt_salarys Data Source property as odc_empsal.

12.Set the txt_lnames Data Field property as last_name. 13.Set the txt_salarys Data Field property as salary. 14.Double click the cmd_exit and add the following code in bold: Private Sub cmd_exit_Click() Unload Me End Sub

15. Run the application. The record will be display in the both text box. 16.Each record can be accessed by using odc_empsal control.

OUTPUT:

Employees Salary Details in VB Form:

RESULT:

EMPSAL DETAILS USING ADO


AIM:

Steps to Create a Employee Details Form: 4. Create a Standard EXE project. 5. Choose ProjectReferencesMicrosoft ActiveX Data Objects 6.0 Library. 6. Add 10 Label controls in the form and set the name and caption property as, Control Name Label1 Label2 Label3 Name Property lbl_title lbl_empid lbl_fname Caption Property Employee Details Employee ID Employees First Name Employees Last Name E-Mail ID Phone Number Date of Joining Job ID Salary Department ID

Label4 Label5 Label6 Label7 Label8 Label9 Label10

lbl_lname lbl_email lbl_phone lbl_doj lbl_jobid lbl_salary lbl_deptid

7. Add 9 Textbox controls in the form and set the name and caption property as, Control Name Textbox1 Textbox2 Textbox3 Textbox4 Textbox5 Textbox6 Textbox7 Textbox8 Textbox9 Name Property txt _empid txt _fname txt _lname txt _email txt _phone txt _doj txt _jobid txt _salary txt _deptid

8. Add 10 command button controls in the form and set the name and caption property as,

Control Name Command1 Command2 Command3 Command4 Command5 Command6 Command7 Command8 Command9

Name Property cmd_first cmd _next cmd _prev cmd _last cmd _add cmd _save cmd _modify cmd _delete cmd _cancel

Caption Property First Next Prev Last Add Save Modify Delete Cancel

Command10

cmd _exit

Exit

9. Set the caption property of Form1 as Employees Salary Details... 10.Double click the form1 and add the following code in bold: Private Sub Form_Load() Set con = New ADODB.Connection Set rst = CreateObject("ADODB.RecordSet") With rst .CursorLocation = adUseServer .LockType = adLockOptimistic .CursorType = adOpenDynamic End With

'Connection String With con .Provider = "OraOLEDB.Oracle" .Properties("Data Source") = "EMS" .Properties("User Id") = "iicsea_03" .Properties("Password") = "cselab3"

.Open End With

'Selecting rows from employees table..

rst.Open "SELECT emp_id, first_name, last_name, email, phone_no, hire_date, job_id, salary, dept_id FROM employees WHERE dept_id IS NOT NULL", con

Set txt_empid.DataSource = rst Set txt_fname.DataSource = rst Set txt_lname.DataSource = rst Set txt_email.DataSource = rst Set txt_phone.DataSource = rst Set txt_doj.DataSource = rst Set txt_jobid.DataSource = rst Set txt_salary.DataSource = rst Set txt_deptid.DataSource = rst

txt_empid.DataField = "emp_id" txt_fname.DataField = "first_name" txt_lname.DataField = "last_name" txt_email.DataField = "email"

txt_phone.DataField = "phone_no" txt_doj.DataField = "Hire_date" txt_jobid.DataField = "job_id" txt_salary.DataField = "salary"

txt_deptid.DataField = "dept_id"

End Sub Public Sub MoveFields() txt_empid.Text = rst("emp_id") txt_fname.Text = rst("first_name") txt_lname.Text = rst("last_name") txt_email.Text = rst("email") txt_phone.Text = rst("phone_no") txt_doj.Text = rst("Hire_date") txt_jobid.Text = rst("Job_id") txt_salary.Text = rst("salary") txt_deptid.Text = rst("dept_id")

End Sub

11.Double click the cmd_first and add the following code in bold: Private Sub cmd_first_Click() rst.MoveFirst

MoveFields cmd_prev.Enabled = False cmd_next.Enabled = True MsgBox "First Record"

End Sub

12.Double click the cmd_next and add the following code in bold: Private Sub cmd_next_Click() rst.MoveNext If rst.EOF = True Then rst.MoveLast cmd_next.Enabled = False cmd_last.Enabled = False MsgBox "Last Record" End If MoveFields cmd_prev.Enabled = True End Sub

13.Double click the cmd_prev and add the following code in bold: Private Sub cmd_prev_Click() rst.MovePrevious If rst.BOF = True Then

rst.MoveFirst

cmd_prev.Enabled = False

cmd_first.Enabled = False MsgBox "First Record" End If MoveFields

cmd_next.Enabled = True cmd_last.Enabled = True cmd_first.Enabled = True End Sub 14.Double click the cmd_last and add the following code in bold: Private Sub cmd_last_Click() rst.MoveLast MoveFields cmd_next.Enabled = False cmd_prev.Enabled = True MsgBox "Last Record" End Sub

15.Double click the cmd_Add and add the following code in bold: Private Sub cmd_Add_Click()

cmd_first.Enabled = False cmd_prev.Enabled = False

cmd_next.Enabled = False cmd_last.Enabled = False

txt_empid.Text = "" txt_fname.Text = "" txt_lname.Text = "" txt_email.Text = "" txt_phone.Text = "" txt_doj.Text = "" txt_jobid.Text = "" txt_salary.Text = "" txt_deptid.Text = ""

rst.AddNew End Sub

16.Double click the cmd_save and add the following code in bold: Private Sub cmd_save_Click() If rst.EditMode = adEditAdd Then rst("emp_id") = txt_empid.Text rst("first_name") = txt_fname.Text

rst("last_name") = txt_lname.Text rst("email") = txt_email.Text

rst("phone_no") = txt_phone.Text rst("hire_date") = txt_doj.Text rst("Job_id") = txt_jobid.Text rst("salary") = txt_salary.Text rst("dept_id") = txt_deptid.Text End If rst.Update

cmd_first.Enabled = True cmd_next.Enabled = True cmd_prev.Enabled = True cmd_last.Enabled = True End Sub

17.Double click the cmd_modify and add the following code in bold: Private Sub cmd_modify_Click() If rst.EditMode = adEditNone Then rst("first_name") = txt_fname.Text rst("last_name") = txt_lname.Text rst("email") = txt_email.Text rst("phone_no") = txt_phone.Text

rst("hire_date") = txt_doj.Text rst("Job_id") = txt_jobid.Text

rst("salary") = txt_salary.Text rst("dept_id") = txt_deptid.Text End If rst.Update

cmd_first.Enabled = True cmd_next.Enabled = True cmd_prev.Enabled = True cmd_last.Enabled = True End Sub

18.Double click the cmd_modify and add the following code in bold: Private Sub cmd_del_Click() rst.Delete rst.MoveNext If rst.EOF = True Then rst.MoveLast End If MoveFields

End Sub

19.Double click the cmd_cancel and add the following code in bold: Private Sub cmd_cancel_Click() rst.CancelUpdate MoveFields End Sub

20.Double click the cmd_exit and add the following code in bold: Private Sub cmd_exit_Click() Unload Me End Sub 21. Run the application. The record will be display in the both text box. 22.Each record can be accessed by using odc_empsal control. OUTPUT: Employees Details in VB Form:

RESULT: