dbms record completed

170
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;

Upload: anitha-varshini

Post on 21-Feb-2015

221 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Dbms Record Completed

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;

Page 2: Dbms Record Completed

DQL SELECTION

Introduction:

The DQL Selection is performed using the following Between…and In Not in Like Relational Operators Logical Operators

Page 3: Dbms Record Completed

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;

Page 4: Dbms Record Completed

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,salary”salary”,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;

Page 5: Dbms Record Completed

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’;

Page 6: Dbms Record Completed

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 with’k’

SELECT last_nameFROM employees WHERE last_name LIKE ‘K%’;

Page 7: Dbms Record Completed

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

Page 8: Dbms Record Completed

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’);

Page 9: Dbms Record Completed

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%’;

Page 10: Dbms Record Completed

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 DetailsThe 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 of all employees whose last name is ‘higgins’.

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’;

Page 11: Dbms Record Completed

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.92’46 and 50.

SELECT ROUND (45.923) ,ROUND (45.923’0),ROUND(45.923,-1) FROM DUAL ;

11. Write a query to truncate the value 45.923 into 45.92’45 AND 0.

SELECT TRUNCATE(45.923,2), TRUNCATE(45.923,0), TRUNCATE

Page 12: Dbms Record Completed

(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;

Page 13: Dbms Record Completed

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;

Page 14: Dbms Record Completed

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’) AS”MONTH”, 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’);

Page 15: Dbms Record Completed

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;

Page 16: Dbms Record Completed

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 employee’s job id is ‘IT_PROG’, then the salary increase is 10%.b. If the employee’s job id is ST_CLERK’, then the salary increase is 15%.c. If the employee’s 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 * salaryWHEN ‘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 employee’s job id is ‘IT_PROG’, then the salary increase is 10%.b. If the employee’s job id is ST_CLERK’, then the salary increase is 15%.c. If the employee’s 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: 0→0.00, 1→0.09, 2→0.20, 3→ 0.30, 4→0.40,5→0.42, 6→0.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,

Page 17: Dbms Record Completed

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 AGE

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

1 sayee 2890 19

2 rama 5000 20

3 meera 6000 20

4 sayee 4536 20

5 bala 7780 20

SELECT SINGLE COLUMN:SQL> select ename from employee;

ENAME

-----------------------------------------------sayeeramameerasayeebala

SELECT MULTICOLUMN :

SQL> select eno,ename,sal from employee;

Page 18: Dbms Record Completed

ENO ENAME SAL

1 sayee 2890

2 rama 5000

3 meera 6000

4 sayee 4536

5 bala 7780

SELECT ALL:SQL> select * from employee;

ENO ENAME SAL AGE

1 sayee 2890 19

2 rama 5000 20

3 meera 6000 20

4 sayee 4536 20

5 bala 7780 20

SELECTION WITH ARITHMETIC OPERATION:SQL> select eno,ename,sal+1000 from employee;

ENO ENAME SAL+1000

1 sayee 3890

2 rama 6000

3 meera 7000

4 sayee 5536

5 bala 8780

SELECTION WITH ALIAS:

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

ENO ENAME WITHBONUS

1 sayee 3890

2 rama 6000

Page 19: Dbms Record Completed

3 meera 7000

4 sayee 5536

5 bala 8780

SQL> select eno,ename,sal+1000 “withbonus” from employee;

ENO ENAME withbonus

1 sayee 3890

2 rama 6000

3 meera 7000

4 sayee 5536

5 bala 8780

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

ENAME ENO WITHBONUS

sayee 1 3890

rama 2 6000

meera 3 7000

sayee 4 5536

bala 5 8780

RENAME:SQL> select sal “salary” from employee;

salary2890

Page 20: Dbms Record Completed

5000600045367780

SELECTION WITH CONCATENATION OPERATOR:SQL> select eno || ename from employee;

ENO||ENAME

1sayee2rama3meera4sayee5bala

SELECTION WITH LITERAL CHARACTER STRINGS:SQL> select ename || ‘ ‘ || ‘getting’ || ‘ ‘ || sal from employee;

ENAME|| ‘ ‘ || ‘GETTING’ || ‘ ‘ ||SAL

sayeegetting2890ramagetting5000meeragetting6000sayeegetting4536balagetting7780

SELECT DISTINCT:SQL> select distinct ename from employee;

ENAME

meerabalasayee

SQL> select distinct eno from employee;

ENO

12453

Page 21: Dbms Record Completed
Page 22: Dbms Record Completed

RESULT:

Page 23: Dbms Record Completed

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;

Page 24: Dbms Record Completed

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 ‘countries’table, 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.

Page 25: Dbms Record Completed

Verify by: SQL> SELECT * FROM countries;

3.Write a query to insert a new row containing values for each column into the ‘locations’table, 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;

Page 26: Dbms Record Completed

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;

Page 27: Dbms Record Completed

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', ‘[email protected] ', '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', ‘[email protected] ', '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;

Page 28: Dbms Record Completed

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 ‘total’ column as sum of mark1,mark2,mark3,mark4 for all

the students,set the savepoint s3 and verify it.

UPDATE students SET total=mark1+mark2+mark3+mark4;3 rows updated.

SAVEPOINT s3;

Savepoint created.

Page 29: Dbms Record Completed

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 the’students’table 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.

Page 30: Dbms Record Completed

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));

Page 31: Dbms Record Completed

Table created

SQL> desc cust;

Name Null? Type

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

CNAME VARCHAR2(15)

CID NOT NULL NUMBER(5)

CADDR CHAR(10)

CACCNO NUMBER(5)

CACCTYPE VARCHAR2(10)

CBALANCE 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

Page 32: Dbms Record Completed

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.

Page 33: Dbms Record Completed

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 1 Chennai 1001 savings 15000

Shriram 2 Pondy 1002 savings 25000

Chamundi 3 Salem 1003 fd 36200

Madhan 4 Salem 1004 checkings 5000

Subha 5 Trichy 1005 checkings 10000

Jayashree 6 Pondy 1006 fd 15000

Sridharan 7 Kanchi 1007 fd 22000

7 rows selected.

Page 34: Dbms Record Completed

UPDATE:

SQL> update cust set caccno=1111 where cname='Chamundi';

1 row updated

SQL> select * from cust;

CNAME CID CADDR CACCNO CACCTYPE CBALANCE

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

Anusha 1 Chennai 1001 savings 15000

Shriram 2 Pondy 1002 savings 25000

Chamundi 3 Salem 1111 fd 36200

Madhan 4 Salem 1004 checkings 5000

Subha 5 Trichy 1005 checkings 10000

Jayashree 6 Pondy 1006 fd 15000

Sridharan 7 Kanchi 1007 fd 22000

7 rows selected.

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

3 row deleted

SQL> select * from cust;

CNAME CID CADDR CACCNO CACCTYPE CBALANCE

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

Anusha 1 Chennai 1001 savings 15000

Shriram 2 Pondy 1002 savings 25000

Page 35: Dbms Record Completed

Madhan 4 Salem 1004 checkings 5000

Subha 5 Trichy 1005 checkings 10000

4 rows selected.

RESULT:

Page 36: Dbms Record Completed

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};

Page 37: Dbms Record Completed

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 char(2) primary key constraint at table valueCountry_name varchar2(40) not nullRegion_id number foreign key constraint to ‘regions’ table at table

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;

Page 38: Dbms Record Completed

2.Write a query to crate ‘locations’ table and verify it.Table description:

Loc_id number(4) primary key constraint at column levelStreet_add varchar2(40)Postal_code varchar2(12)City varchar2(30) not nullState_prov varchar2(25)Country_id char(2) foreign key to constraint to ‘countries’ table at column level

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 varchar2(10) primary key constraint at column levelJob_title varchar2(35) not nullMin_salary number(6)Max_salary number(6)

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 leveldept_name varchar2(30) not nullmanager_id number(6)

Page 39: Dbms Record Completed

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 number(6) primary key constraint at column levelDept_id varchar2(30) not nullManager_id number(6)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 levelFirst_name varchar2(20)Last_name varchar2(20) not nullEmail varchar2(25) unique key constraint at table levelPhone_no varchar2(10) unique key constraint at column levelHire_date date not nullJob_id varchar2(10) foreign key constraint to ‘jobs’ table at column levelSalary number(8,2)Comm_pct number(2,2)

Page 40: Dbms Record Completed

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 varchar(30)Lowest_sal number(6)Highest_sal 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 number(4)Name varchar2(20) not nullContact_no number(10)Mark1 number(3)Mark2 number(3)Mark3 number(3)

CREATE TABLE students (Roll_no NUMBER(4),

Page 41: Dbms Record Completed

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 number(3)Mark5 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 number(4)Average 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

Page 42: Dbms Record Completed

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;

Page 43: Dbms Record Completed

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 studentsDISABLE 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 employeesDISABLE CONSTRAINT emp_id_pk CASCADE;

Verify by: DESC employees;

Page 44: Dbms Record Completed

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:

Page 45: Dbms Record Completed

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;

Page 46: Dbms Record Completed

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

Page 47: Dbms Record Completed

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

ENO NUMBER(10)

ENAME VARCHAR2(10)

DNO NUMBER(10)

SAL NUMBER(10)

JOBID VARCHAR2(10)

MGRID VARCHAR2(10)

SQL> desc emp;

Name Null? Type

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

ENO NOT NULL NUMBER(10)

ENAME VARCHAR2(10)

DNO NUMBER(10)

SAL NUMBER(10)

JOBID VARCHAR2(10)

MGRID VARCHAR2(10)

ADDR VARCHAR2(10)

SQL> alter table emp add(phno number(5));

Table altered.

SQL> alter table emp modify(jobid char(20));

Page 48: Dbms Record Completed

Table altered.

SQL> desc emp;

Name Null? Type

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

ENO NOT NULL NUMBER(10)

ENAME VARCHAR2(10)

DNO NUMBER(10)

SAL NUMBER(10)

JOBID CHAR(20)

MGRID VARCHAR2(10)

ADDR VARCHAR2(10)

PHNO VARCHAR2(10)

SQL> drop table emp;

Table dropped.

SQL> desc emp;

ERROR

ORA-04043: object emp does not exist

RESULT:

Page 49: Dbms Record Completed

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 sub-query 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.

Page 50: Dbms Record Completed

SUBQUERY SYNTAX:

SELECT SELECT_LIST

FROM TABLE

WHERE EXPR OPERATOR

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

(SELECT SELECT_LIST

FROM TABLE);

Page 51: Dbms Record Completed

SINGLE ROW SUB QUERY:

MAIN QUERY

SINGLE ROW SUB QUERY RETURNS A SINGLE VALUE

MULTIPLE ROW SUB QUERY:

MAIN QUERY

SUB QUERY

SUB QUERY

Page 52: Dbms Record Completed

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 Kumar’s salary and verify it.

SELECT last_name FROM employees WHERE salary > (SELECT

salary FROM employees WHERE last_name=kumar

2. Write a query to display the last_name and hire_date of all

employees who are in the same department as ‘Kumar’ and

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.

Page 53: Dbms Record Completed

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.

Page 54: Dbms Record Completed

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);

Page 55: Dbms Record Completed

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

Page 56: Dbms Record Completed

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 representative’s 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

Page 57: Dbms Record Completed

who are not SALES REPRESENTATIVE and whose salary is more than that of the sales

representative’s 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);

Page 58: Dbms Record Completed
Page 59: Dbms Record Completed

RESULT :

Page 60: Dbms Record Completed

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.

INTRODUCTIONThe 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 Joins1. Simple Join2. Self Join3. Outer Join

Simple JoinIt 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-joinA join, which is based on equalities, is called equi-join.

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

Self joinJoining 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 JoinIt 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.

Page 61: Dbms Record Completed

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;

Page 62: Dbms Record Completed

Name Null? Type ----------------------------------------- -------- ---------------------------- EID NOT NULL NUMBER(5) ENAME VARCHAR2(10) DNO NUMBER(5) ESAL NUMBER(10)MGRID NUMBER(3)JOBID 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:1enter city:chennaienter area:aaaold 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:1enter dname:adminenter lid:2old 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:3enter ename:zzzenter dno:3enter esal :3500enter jobid:2enter mgr id:2old 1: insert into emp values(&eid,'&ename',&dno,&esal,&jobid,&mgrid)new 1: insert into emp values(1,'zzz',3500,2,2)

Page 63: Dbms Record Completed

1 row created

SQL>insert into grade values(&gno,&ls,&hs);enter gno:1enter ls:1000enter hs:2000old 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 LID---------- ---------- ------------- 1 admin 2 2 finance 3

3 Hr 4 4 market 3 5 sales 1

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

Page 64: Dbms Record Completed

EQUIJOINS

ENAME DNAME---------- ----------xxx adminyyy financezzz hrabc 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 higgin’s 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 4xxx 4000 3yyy 2000 1zzz 3500 3abc 4500 4

Page 65: Dbms Record Completed

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

Page 66: Dbms Record Completed

---------- ----------------xxx adminyyy financeabc financezzz hr market sales

RIGHT OUTER JOIN:

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

ENAME DNAME---------- ---------------bbcxxx adminyyy financezzz hrabc 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 (+);

Page 67: Dbms Record Completed

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 yyyyyy xxxzzz yyy

SELFJOIN----TO DISPLAY MANAGER'S SALARY FOR EVERY EMPLOYEESQL> select e.ename,m.esal from emp e,emp m where e.mgrid=m.eid;

ENAME ESAL---------- ----------------bbc 2000yyy 4000zzz 2000Selecting Rows using Self Joins:

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

Employee’s Manager Kumar works for Rajesh

SELECT w.last_name || ‘work for’ || m.last_name AS “Employee’s Manager” FROM employees w,employees m WHERE w.manager_id = m.emp_id;

Page 68: Dbms Record Completed

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’;

Page 69: Dbms Record Completed

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

Page 70: Dbms Record Completed

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 DNAMEbbc xxx adminyyy financezzz hrabc 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);

Page 71: Dbms Record Completed

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 employee’s 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;

Page 72: Dbms Record Completed

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:

Page 73: Dbms Record Completed

Creating Views:

01. 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 Null? Type ----------------- --------------- -------------------- ID_NUMBER NOT NULL NUMBER(6) NAME NOT NULL VARCHAR2(25) SALARY NUMBER(8,2)

02. SQL> SELECT * FROM vw_emp80;

ID_NUMBER NAME SALARY---------- ------ ----------- -------------149 kumar 10500174 abel 11000176 raman 8600

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

04. SQL> SELECT * FROM vw_sal50;

ID_NUMBER NAME Annual_Salary---------- ------------------------- ------------- 124 petersen 69600

Page 74: Dbms Record Completed

141 kumar 42000 142 kumari 37200 143 radha 31200 144 prabha 30000

Creating Views with Group Functions:05. 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? TYPEDept_name VARCHAR2(30)MIN_Sal NUMBERMAX_Sal NUMBERAVG_Sal NUMBER

06. SQL> SELECT dept_name, MIN_Sal FROM vw_dept_sal;

DEPT_NAME MIN_SAL----------------- -------------Accounting 10 000Administration 44 000..7 rows selected.

07. 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 TYPEJOB_NAME VARCHAR2(35)MIN_SAL NUMBER

MAX_SAL NUMBER

08. SQL> SELECT job_name, MAX_SAL FROM vw_job_sal;

JOB_NAME MAX_SAL ---------------- -------------- President 40 000 Administration assistant 6 000 . .

Page 75: Dbms Record Completed

12 rows selected

Creating Views with Check Function:

09. 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 Null? Type ---------------------- ---------------- ----------------------------EMP_ID NOT NULL NUMBER(6)

FIRST_NAME VARCHAR2(20) LAST_NAME VARCHAR2(25)

EMAIL VARCHAR2(30) PHONE_NO VARCHAR2(20)

HIRE_DATE DATE JOB_ID VARCHAR2(10)

SALARY NUMBER(8,2)COMM_PCT NUMBER(2,2)

MANAGER_ID NUMBER(6)DEPT_ID NUMBER(4)

10. SQL> select emp_id,last_name,dept_id from vw_emp20;

EMP_ID LAST_NAME DEPT_ID--------------- -------------------- ---------------

201 Kumar 20 202 Kumar 20

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

Page 76: Dbms Record Completed

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 Null? Type---------------------------- --------------- ---------------------------EMPLOYEE_ID NOT NULL NUMBER(6)EMPLOYEE_NAME VARCHAR2(25)JOB_ID VARCHAR2(10)

14. SQL> select employee_id,employee_name,job_id from vw_emp10;

EMPLOYEE_ID EMPLOYEE_NAME JOB_ID---------------------- --------------------------- ----------200 Antony AD_ASST

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.

Page 77: Dbms Record Completed

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;

RANK LAST_NAME SALARY--------- ------------------- ----------

1 King 34320 2 Kumar 24310 3 Raj 18700

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 LAST_NAME HIRE_DATE------------ -------------------- --------------------1 Prabha 09-JUL-08

2 Radha 15-MAR-08 3 Kumari 29-JAN-07 4 Kumar 17-OCT-95 5 Lorentz 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 LAST_NAME SALARY---------- ------------------- -------------

1 Prabha 2750 2 Radha 2860 3 Kumari 3410 4 Kumar 3850 5 Lorentz 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 LAST_NAME HIRE_DATE------------ ------------------- -------------------

1 King 17-JUN-97 2 Kumar 21-SEP-99 3 Raj 13-JAN-93

Page 78: Dbms Record Completed

RESULT:

Page 79: Dbms Record Completed

Bind Variables:

01. Verified By (Before):SQL> SELECT emp_id, salary FROM employees WHERE emp_id=178;

EMP_ID SALARY---------- ----------178 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

02. 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;

Page 80: Dbms Record Completed

/The last name is assigned to the Bind Variable..!!!

PL/SQL procedure successfully completed.

Verified By (After):

SQL> PRINT :g_lname;

G_LNAME---------------Kumar

03. PL/SQL Block:

SQL> DEFINE p_annual_sal=60000SQL> VARIABLE g_monthly_sal NUMBERSQL> 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

Page 81: Dbms Record Completed

04. 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-97The Salary is 24000

PL/SQL procedure successfully completed.

05. Verified By (Before):

SQL> SELECT SUM(salary) AS sum FROM employees WHERE dept_id=60;

SUM----------19200

PL/SQL Block:

DECLAREv_emp_id employees.emp_id %TYPE;v_sum_salary employees.salary %TYPE;v_dept NUMBER NOT NULL := 60;

BEGINSELECT 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);

Page 82: Dbms Record Completed

END;

Procedure successfully completed

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

07. Verified By (Before):SELECT emp_id, last_name, dept_id FROM employees WHERE dept_id=10;

Emp_id Last_name Dept_id---------- ------------- ----------- 200 Whalen 10

Page 83: Dbms Record Completed

PL/SQL Block:BEGINDelete 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.

08. Verified By (Before):

SQL> SELECT last_name, job_id, dept_id FROM employees WHERE last_name='Petersen';

LAST_NAME JOB_ID DEPT_ID------------------ ---------- ----------Petersen 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 JOB_ID DEPT_ID-------------------- ----------- ----------Petersen MK_MAN 20

Page 84: Dbms Record Completed

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

SALARY DEPT_ID------------- -----------18700 1018700 10PL/SQL Block:DECLAREV_dept_id employees.dept_id % TYPE;V_salary employees.salary %TYPE;BEGINSELECT dept_id,v_dept_id FROM employees IN dept_id=10, THEN Update employees v_salary=5000;ELSE IF v_dept_id =80UPDATE employees v_salary =7500;ELSE IF UPDPATE employees SET v_salary=2000;END IF;END IF;END IF;END;/

PL/SQL procedure successfully completedVerified (After):SELECT salary , dept_id FROM employees WHERE dept_id=10;

SALARY DEPT_ID------------ -----------5000 105000 10

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

SALARY-----------4500310046003500PL/SQL Block:DECLAREV_salary_inc employees.salary %TYPE := 500;BEGINFOR I in 1..2LOOP

Page 85: Dbms Record Completed

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

360051004000

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 :275PL/SQL procedure successfully completed.

12. PL/SQL Block: DECLARE

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

Page 86: Dbms Record 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 BEGINLOOP var:=var+50;EXIT WHEN var=300;END LOOP DBMS_OUTPUT.PUT_LINE(TO_CHAR(var));END;/

300PL/SQL procedure successfully completed.

15. Verified By (Before):SELECT last_name, job_id , dept_id FROM employees WHERE last_name=’Petersen’;

LAST_NAME JOB_ID DEPT_ID---------------- --------- -----------Petersen MK_MAN 20

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

Page 87: Dbms Record Completed

V_deptid employees.dept_id %TYPE :=20;BEGINSELECT last_name INTO v_name FROM employees WHERE last_name = ‘Petersen’;

IF v_name =’petersen’ THENGOTO 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 JOB_ID DEPT_ID----------------- ---------- ---------- Petersen MK_MAN 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;

Page 88: Dbms Record Completed

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 JOB_ID SALARY---------------- ---------- -------------Pandian IT_PROG 10890Kumar IT_PROG 7260Lorentz IT_PROG 5082

PL/SQL Block:DECLARE Ex_lowsal EXCEPTION;V_salary employees.salary % TYPE;BEGINSELECT MIN(salary) INTO v_salary FROM employees WHERE job_id=’IT_PROG’;IF v_salary < 5000 THEN RAIS ex_lowsal;END IF;EXCEPTIONWHEN ex_lowsal THENDBMS_OUTPUT.PUT_LINE(‘Very low salary for IT programmers!!!’);END;/

Very low salary for IT programmers!!!PL/SQL procedure successfully completed.

Page 89: Dbms Record 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:DECLAREEx_manager EXCEPTION;BEGIN SELECT manager_id INTO v_managerid FROM employees WHERE dept_id=100;IF v_managerid = NULL THENEXCEPTION ex_managerEND 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 selectedPL/SQL Block:DECLAREEx_noemp EXCEPTIONV_lname employees.last_name %TYPE;BEGINDELETE FROM employees WHERE last_name=’Rajeshwari’;IF SQL % NOT FOUND THEN RAISE ex_noemp;ELSEDBMS_OUTPUT.PUT_LINE(‘Employee Rajeshwari Record is deleted!!!’);END IF;EXCEPTIONWHEN ex_noemp THENRAISE_APPLICATION_ERROR(-20001,’Rajeshwari is not a valid employee’);END;/ORA.-20001: Rajeshwari is not a valid employeePL/SQL procedure successfully completed.

Page 90: Dbms Record Completed
Page 91: Dbms Record Completed

RESULT:

Creating Procedures:

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

Page 92: Dbms Record Completed

:20 rows selected.

02. 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_allISBEGINUPDATE 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

03. Verified By (Before):

Page 93: Dbms Record Completed

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 MARK3 ---------- ------------------------------ ---------- ---------- ---------- 7 Yogeswari 94 56 97

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; /

Page 94: Dbms Record Completed

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 NUMBERSQL> VARIABLE g_comm NUMBERSQL> EXECUTE proc_sal_comm(107, :g_name, :g_sal, :g_comm);

PL/SQL procedure successfully completed.

SQL> PRINT :g_name

G_NAME---------------------Lorentz

Page 95: Dbms Record Completed

SQL> SELECT last_name, salary, comm_pct FROM employees WHERE emp_id=107;

LAST_NAME SALARY COMM_PCT------------------------- ---------- ----------Lorentz 4620

07. SQL> CREATE OR REPLACE PROCEDURE proc_mail_job ( p_emp_id IN employees.emp_id%TYPE, 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 NUMBERSQL> 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

[email protected]

G_JOBID----------------ST_CLERK

SQL> SELECT last_name,email,job_id FROM employees WHERE emp_id=142;

LAST_NAME EMAIL JOB_ID-----------------------------------------------------------------------------------------

Page 96: Dbms Record Completed

Kumari [email protected] ST_CLERK

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

BEGINp_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 NUMBERISv_salary employees.salary%TYPE :=0;

Page 97: Dbms Record Completed

BEGINSELECT 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 2112101 Kumar 24313 1944.8102 Raj 18700 1496

Page 98: Dbms Record Completed

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’,’[email protected]’,’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

Page 99: Dbms Record Completed

ORA-06512: at”iicsea_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.

Page 100: Dbms Record Completed

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.

Page 101: Dbms Record Completed

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’,’[email protected]’, ’9977886655’, ’14-Dec-2011’,’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.

Page 102: Dbms Record Completed

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.

Page 103: Dbms Record Completed

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.

Page 104: Dbms Record Completed

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. Specify a WHERE clause to filter the selection of rows from the base table.

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

Page 105: Dbms Record Completed

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 employee’s records who is working in the department 50.

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

Page 106: Dbms Record Completed

OUTPUT:

RESULT:

Page 107: Dbms Record Completed

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

Page 108: Dbms Record Completed

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.

Page 109: Dbms Record Completed

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

Page 110: Dbms Record Completed

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.

Page 111: Dbms Record Completed

OUTPUT:

Department Details:

Page 112: Dbms Record Completed

Department-wise Employee Details:

RESULT:

Page 113: Dbms Record Completed

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.

Page 114: Dbms Record Completed

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 Lables Width

CountEMP_IDPerReport No. of Employees : 10

SumSALARYPerReport Total Salary : 10

Page 115: Dbms Record Completed

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.

Page 116: Dbms Record Completed

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.

Page 117: Dbms Record Completed

OUTPUT:

Employees Details in Paper Layout:

Page 118: Dbms Record Completed

Employees Details in Web Layout:

Page 119: Dbms Record Completed

RESULT:

Page 120: Dbms Record Completed

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.

Page 121: Dbms Record Completed

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 Lables Width

Dept_name Department Name 20

Emp_id Employee ID 6

Last_name Last Name 10

Job_id Job ID 10

Page 122: Dbms Record Completed

salary Salary 8

AvgSALARYPerReport Average : 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.

Page 123: Dbms Record Completed

OUTPUT:

Department-wise Employees Report in Paper Layout:

Page 124: Dbms Record Completed

Department-wise Employees Report in Paper Layout:

RESULT:

Page 125: Dbms Record Completed

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 project’s toolbox. Add an instance of

the Oracle Data Control to the project’s form and set the name property as

odc_empsal.

7. Set the caption property of Form1 as Employee’s 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 Employee’s

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. Connect – username / password

ii. Database – EMS

iii. Record Source – SELECT last_name, salary FROM employees;

11. Set the txt_lname’s and txt_salary’s Data Source property as odc_empsal.

Page 126: Dbms Record Completed

12. Set the txt_lname’s Data Field property as last_name.

13. Set the txt_salary’s 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.

Page 127: Dbms Record Completed

OUTPUT:

Employee’s Salary Details in VB Form:

Page 128: Dbms Record Completed

RESULT:

Page 129: Dbms Record Completed

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 Name Property Caption Property

Label1 lbl_title Employee Details

Label2 lbl_empid Employee ID

Label3 lbl_fname Employee’s First Name

Label4 lbl_lname Employee’s Last Name

Label5 lbl_email E-Mail ID

Label6 lbl_phone Phone Number

Label7 lbl_doj Date of Joining

Label8 lbl_jobid Job ID

Label9 lbl_salary Salary

Label10 lbl_deptid Department ID

Page 130: Dbms Record Completed

7. Add 9 Textbox controls in the form and set the name and caption property

as,

Control Name Name Property

Textbox1 txt _empid

Textbox2 txt _fname

Textbox3 txt _lname

Textbox4 txt _email

Textbox5 txt _phone

Textbox6 txt _doj

Textbox7 txt _jobid

Textbox8 txt _salary

Textbox9 txt _deptid

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

property as,

Control Name Name Property Caption Property

Command1 cmd_first First

Command2 cmd _next Next

Command3 cmd _prev Prev

Command4 cmd _last Last

Command5 cmd _add Add

Command6 cmd _save Save

Page 131: Dbms Record Completed

Command7 cmd _modify Modify

Command8 cmd _delete Delete

Command9 cmd _cancel Cancel

Command10 cmd _exit Exit

9. Set the caption property of Form1 as Employee’s 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"

Page 132: Dbms Record Completed

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

Page 133: Dbms Record Completed

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

Page 134: Dbms Record Completed

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

Page 135: Dbms Record Completed

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()

Page 136: Dbms Record Completed

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

Page 137: Dbms Record Completed

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

Page 138: Dbms Record Completed

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

Page 139: Dbms Record Completed

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:

Employee’s Details in VB Form:

Page 140: Dbms Record Completed

RESULT: