Top Banner
SOFTWARE LABORATORY RECORD Name : VENKATA PHANIKRISHNA B Assistant Professor DNR CET Lab : DATABASE MANAGEMENT SYSTEMS
92

bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Mar 31, 2018

Download

Documents

vuthien
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SOFTWARELABORATORY RECORD

Name : VENKATA PHANIKRISHNA B

Assistant ProfessorDNR CET

Lab : DATABASE MANAGEMENT SYSTEMS

Page 2: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

INDEXS.NO DATE TITLE OF EXPERIMENT Page No.

1 1. EXPERIMENTS ON SQL1. 1.Simple SQL commands1.2.Creation of tables1.3.Set Operations1.4.Functions and Procedures1.5.Triggers

112203045

Page 3: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

1

1. EXPERIMENTS ON SQL

Expno: 1.1 DATE: 3-7-2012

SIMPLE SQL COMMANDS

Aim:To practice simple sql commands for retrieving data contained in tables

Theory:Questions including data stored in a data base are called queries. Queries are the

primary mechanism for retrieving information from a database and consist of questions presented to the database in a predefined format. Many database management systems use the Structured Query Language (SQL) standard query format. A database query can be either a select query or an action query. A select query is simply a data retrieval query. An action query can ask for additional operations on the data, such as insertion, updating, or deletion. Structured Query Language is a special-purpose programming language designed for managing data in relational database management systems (RDBMS).

SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language), was designed to manipulate and retrieve data stored in IBM's original quasi-relational database management system, System R, which a group at IBM San Jose Research Laboratory had developed during the 1970s. To bring conformity among vendors, the American National Standards Institute (ANSI) published its first SQL standard in 1986 and a second widely adopted standard in1989. ANSI released updates in 1992, known as SQL92 and SQL2, and again in 1999, termed as both SQL99 and SQL3.

In SQL92, SQL statements are grouped into three broad categories. They areData Manipulation Language (DML), Data Definition Language (DDL), Data Control Language (DCL)

Clauses, which are constituent components of statements and queries.

The FROM clause which indicates the table(s) from which data is to be retrieved.The FROM clause can include optional JOIN sub clauses to specify the rules for joining tables.

The WHERE clause includes a comparison predicate, which restricts the rows returned by the query. The WHERE clause eliminates all rows from the result set for which the comparison predicate does not evaluate to True.

The GROUP BY clause is used to project rows having common values into a smaller set of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The WHERE clause is applied before the GROUP BY clause.

Page 4: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions can be used in the HAVING clause predicate.

The ORDER BY clause identifies which columns are used to sort the resulting data, and in which direction they should be sorted (options are ascending or descending). Without an ORDER BY clause, the order of rows returned by an SQL query is undefined.

Depending on the operations performed by database, SQL is categorized into following sub- languages

1) DDL:- Data Definition Language2) DML:-Data Manipulation Language3) DRL:-Data Retrieval Language4) DCL:-Data Controlling Language5) TCL:-Transaction Control Language

DDL:- Data Definition LanguageOperations are

Create:-we can create a table or data definition Alter:- already created data definition we want to add new entity we use this means to

modify data definition we use alter Drop:- To drop the data definition (Means to delete the table or data definition) Truncate:- Release memory allocated for the table that is one table is created then

some memory allocated for that table. When we use truncate that memory is cleared Rename:-used to change name of the tables

DML:-Data Manipulation LanguageThis is used to implement operations on data Set of instructions to manipulate data are

Insert:-for inserting the data in already created table Update: -for updating the content in table Delete:- for deleting the content in the table

DRL:-Data Retrieval Language Select:- To retrieve data from data base

DCL:-Data Controlling Language Grant:- if one user data cannot be accessed by another user until 1st user give

permissions to 2nd user. Then only 2nd user can access 1st user data. Means for giving permissions to user we use the grant command. i.e. The GRANT command gives privileges to users

Revoke:- REVOKE command takes away privileges from user.TCL:-Transaction Control Language

Commit:- To save transaction. This is same as save option in notepad if we use this„commit‟ command we save the data permanently in secondary memory otherwise itis in RAM

Page 5: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Rollback:-To cancel transaction. This is same as undo operation in notepad.

Page 6: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Savepoint:- To cancel part of the transaction to cancel whole transaction we use rollback. For to cancel part of transaction we use save point

PROCEDURE:For getting SQL prompt

Click start Click all programs Click Oracle Click Application development Click SQL plus

At Logon window enter the following data. User name : system Password : manager Host string : oracle9

After getting SQL prompt type the following command to create a new user

Creating new user in Database:SQL> create user mtech34 identified by phani quota 100m on users;User created.

For providing permissions to newly created user SQL> grant connect,create session,resource to mtech34; Grant succeeded.

For changing existing account to another accountSQL> connect mtech34Enter password: Connected.For find outing the present accountSQL> show user; USER is "MTECH34"

For copying the one account tables to the present account SQL> create table mtech34.sailors as select * from mt34.sailors; Table created.SQL> create table mtech34.Boats as select * from mt34.boats; Table created.SQL> create table mtech34.reserves as select * from mt34.reserves; Table created.

Page 7: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999

QUERIES :

SQL> SELECT * FROM EMP;EMPNO-----------

ENAME-----------

JOB----------

MGR HIREDATE------- ---------------

SAL COMM DEPTNO-------- --------- ----------

7369 SMITH CLERK 7902 17-DEC-80 800 207499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 307521 WARD SALESMAN 7698 22-FEB-81 1250 500 307566 JONES MANAGER 7839 02-APR-81 2975 207654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 307698 BLAKE MANAGER 7839 01-MAY-81 2850 307782 CLARK MANAGER 7839 09-JUN-81 2450 107788 SCOTT ANALYST 7566 09-DEC-82 3000 207839 KING PRESIDENT 17-NOV-81 5000 107844 TURNER SALESMAN 7698 08-SEP-81 1500 307876 ADAMS CLERK 7788 12-JAN-83 1100 207900 JAMES CLERK 7698 03-DEC-81 950 307902 FORD ANALYST 7566 03-DEC-81 3000 207934 MILLER CLERK 7 782 23-JAN-82 1300 10

SQL> SELECT * FROM DEPT;DEPTNO DNAME LOC---------- -------------- ------------10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

SQL> SELECT * FROM SALGRADE;GRADE LOSAL HISAL

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

Page 8: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Display all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME---------- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER14 rows selected.

Display all the department names. SQL> SELECT DNAME FROM DEPT; DNAME-------------- ACCOUNTING RESEARCH SALES OPERATIONS

Display all the employees names along with their designations SQL> SELECT ENAME,JOB AS DESIGNATION FROM EMP; ENAME DESIGNATION---------- --------- SMITH CLERK ALLEN SALESMAN WARD SALESMAN JONES MANAGER MARTIN SALESMAN BLAKE MANAGER CLARK MANAGER SCOTT ANALYST KING PRESIDENT TURNER SALESMAN ADAMS CLERK JAMES CLERKFORD ANALYST MILLER CLERK

Page 9: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Display the details of employees whose salaries are greater than 2000.

SQL> SELECT EMPNO,ENAME FROM EMP WHERE SAL>2000;EMPNO ENAME

---------- ----------7566 JONES7698 BLAKE7782 CLARK7788 SCOTT7839 KING7902 FORD

6 rows selected.

Display the details of employee whose empno is 7788SQL> select * from emp where empno=7788;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO---------- ----------- ------ ------------ --------------- ----- ----------- -------------7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

Display the designation of employee whose empno is 7788SQL> select job as designation from emp where empno=7788;

DESIGNATION---------------- ANALYSTDisplay the name, designation and salary of employees whose salaries are greater than2000.SQL> select ename, job as designation from emp where sal>2000;ENAME DESIGNATION---------- ---------JONES MANAGER BLAKE MANAGER CLARK MANAGER SCOTT ANALYST KING PRESIDENT FORD ANALYST

Display the name, designation and salary of employees whose salariesare between 2500 and 3000.SQL> select ename, job as designation from emp where sal between 2500 and 3000;ENAME DESIGNATION---------- ---------JONES MANAGER BLAKE MANAGER SCOTT ANALYST FORD ANALYST

Page 10: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

7369 SMITH CLERK 7902 17-DEC-80 8007788 SCOTT ANALYST 7566 09-DEC-82 3000

Display the name, designation and salary of employees whose salaries are less than 2500 and that of employees whose salaries are greater than 3000.SQL> select ename, job as designation,sal from emp where sal<2500 or sal>3000;ENAME DESIGNATION SAL---------- --------- ----------SMITH CLERK 800ALLEN SALESMAN 1600WARD SALESMAN 1250MARTIN SALESMAN 1250CLARK MANAGER 2450KING PRESIDENT 5000TURNER SALESMAN 1500ADAMS CLERK 1100JAMES CLERK 950MILLER CLERK 130010 rows selected.

Display the details of employee whose name is scott.SQL> select * from emp where ename='SCOTT';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO----------

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

Display the details of employees whose designation is manager.SQL> select * from emp where job='MANAGER';EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO7566 JONES MANAGER 7839 02-APR-81 2975 207698 BLAKE MANAGER 7839 01-MAY-81 2850 307782 CLARK MANAGER 7839 09-JUN-81 2450 10

Display the names and designation of employees whose designation is manager and whose salary is greater than 2500.SQL> SELECT ename,job from emp where job='MANAGER' and sal>2500;

ENAME JOB---------- ---------JONES MANAGER BLAKE MANAGER

Display the details of employees whose names start with letter s.SQL> select * from emp where ename like 'S%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- ---------- ----- ----------------- --------------- ---------- -----------

2020

Display the details of employees whose names end with letter t.SQL> select * from emp where ename like '%T';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- ---------- ----- ----------------- --------------- ---------- -----------7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

Display the salaries of employees without repetitions

Page 11: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SQL> select distinct sal from emp;

Page 12: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SAL-------2450500013001250285029751100300080016001500950

12 rows selected.

Display names and designation of employees after concatenating.SQL> SELECT ENAME||':-'||JOB FROM EMP;ENAME||':-'||JOB--------------------- SMITH:-CLERK ALLEN:-SALESMAN WARD:-SALESMAN JONES:-MANAGER MARTIN:-SALESMAN BLAKE:-MANAGER CLARK:-MANAGER SCOTT:-ANALYST KING:-PRESIDENT TURNER:-SALESMAN ADAMS:-CLERK JAMES:-CLERKFORD:-ANALYST MILLER:-CLERK14 rows selected.

Display names of employees without any commissionSQL> SELECT * FROM EMP WHERE COMM IS NULL;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- ---------- ----- ----------------- --------------- ---------- -----------7369 SMITH CLERK 7902 17-DEC-80 800 207566 JONES MANAGER 7839 02-APR-81 2975 207698 BLAKE MANAGER 7839 01-MAY-81 2850 307782 CLARK MANAGER 7839 09-JUN-81 2450 107788 SCOTT ANALYST 7566 09-DEC-82 3000 207839 KING PRESIDENT 17-NOV-81 5000 107844 TURNER SALESMAN 7698 08-SEP-81 1500 307876 ADAMS CLERK 7788 12-JAN-83 1100 207900 JAMES CLERK 7698 03-DEC-81 950 307902 FORD ANALYST 7566 03-DEC-81 3000 207934 MILLER CLERK 7782 23-JAN-82 1300 10

11 rows selected.

Display names of employees with some commission along with commission.SQL> SELECT * FROM EMP WHERE COMM IS NOT NULL;

Page 13: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- ---------- ----- ----------------- --------------- ---------- -----------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 307521 WARD SALESMAN 7698 22-FEB-81 1250 500 307654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

Display empno of employees and salaries in order of salaries such that employee with max salary is on top.SQL> SELECT ENAME,SAL FROM EMP ORDER BY SAL DESC;

ENAME SAL---------- ----------KING 5000FORD 3000SCOTT 3000JONES 2975BLAKE 2850CLARK 2450ALLEN 1600TURNER 1500MILLER 1300WARD 1250MARTIN 1250ADAMS 1100JAMES 950SMITH 800

14 rows selected.

Display names of employees and salaries in order of salaries such that employee with max salary is at the bottomSQL> SELECT ENAME,SAL FROM EMP ORDER BY SAL;ENAME SAL---------- ----------SMITH 800JAMES 950ADAMS 1100WARD 1250MARTIN 1250MILLER 1300TURNER 1500ALLEN 1600CLARK 2450BLAKE 2850JONES 2975SCOTT 3000FORD 3000KING 5000

14 rows selected.

Page 14: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Display names of employees and joining dates in the order of joining dates. SQL> SELECT ENAME,HIREDATE FROM EMP ORDER BY HIREDATE; ENAME HIREDATE---------- ---------SMITH 17-DEC-80ALLEN 20-FEB-81WARD 22-FEB-81JONES 02-APR-81BLAKE 01-MAY-81CLARK 09-JUN-81TURNER 08-SEP-81MARTIN 28-SEP-81KING 17-NOV-81JAMES 03-DEC-81FORD 03-DEC-81MILLER 23-JAN-82SCOTT 09-DEC-82ADAMS 12-JAN-83

14 rows selected.

Display the details of salesman and manager whose salary is 1500 or more.SQL> SELECT * FROM EMP WHERE SAL>=1500 AND JOB='SALESMAN' ORJOB='MANAGER';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- ---------- ----- ----------------- --------------- ---------- -----------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 307566 JONES MANAGER 7839 02-APR-81 2975 207698 BLAKE MANAGER 7839 01-MAY-81 2850 307782 CLARK MANAGER 7839 09-JUN-81 2450 107844 TURNER SALESMAN 7698 08-SEP-81 1500 30

Calculate and display salary of scott for one year.SQL> select 12*sal as pa from emp where ename='SCOTT';

PA----------

36000

Display empno, deptno, dname of all employeesSQL> select e.ename,e.deptno,d.loc,d.dname from dept d,emp e where e.deptno=d.deptno;ENAME DEPTNO LOC DNAME---------- ---------- ------------- -------------- SMITH 20 DALLAS RESEARCH ALLEN 30 CHICAGO SALES WARD 30 CHICAGO SALES JONES 20 DALLAS RESEARCH MARTIN 30 CHICAGO SALES BLAKE 30 CHICAGO SALESCLARK 10 NEW YORK ACCOUNTING SCOTT 20 DALLAS RESEARCHKING 10 NEW YORK ACCOUNTING TURNER 30 CHICAGO SALES ADAMS 20 DALLAS RESEARCHJAMES 30 CHICAGO SALES FORD 20 DALLAS RESEARCHMILLER 10 NEW YORK ACCOUNTING14 rows selected.

Page 15: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Display location of the department in which ‘scott’ is workingSQL> select d.loc from dept d,emp e where e.deptno=d.deptno and e.ename='SCOTT';LOC------------- DALLAS

RESULT: The simple sql commands executed successfully and output verified

Page 16: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Expno: 1.2 DATE: 3-7-2012CREATING TABLES

Aim:To create, modify and update tables and to practice some aggregate functions

Theory:Tables are the basic structure where data is stored in the database. Tables are defined

using the create command. The simplified form of create command iscreate table r( A1 D1, A2 D2,…, An Dn,[ integrit y_constraint1 ],…,[ integrity_constraintn])| as select_statement;

insert :Tables are const ructed using the insert command. The simplified form of insert command isinsert into r[(A1, A2, ..,An)] values(v1, v2, . .,vn)| select statement ;

update: The attributes values are updated using the update command. The simplified form of update Command isupdate table_name | view_nameset A = v1where conditions;

drop table: Table can be dropped using drop table. The syntax of the command isdrop table [owner. ] table_name;

Delete: Table contents can be deleted using delete command. The syntax of delete command isdelete from [owner.] table_name [where clause];

alter table: Table structure can be altered using alter table command. The syntax of alter table command isalter table [owner_name. ] table_nameadd A D| modify A D| drop column A ;

Aggregate functions:Aggregate functions are functions that take a collection of values as input and return a single value. SQL offers five built-in aggregate functions.· MIN (A ) :returns minimum of column values· MAX (A ) :returns maximum of column values· AVG ( [ distinct ] A ) :returns average of unique column values· SUM ( [ distinct ] A ) :returns total of unique column values· COUNT( [ distinct ]A):returns number of unique column values

Page 17: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

OPERATIONSCreating the Emp TableSQL> CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10),JOB VARCHAR2(9),MGR NUMBER(4),HIREDATE DATE,SAL NUMBER(7, 2),COMM NUMBER(7, 2), DEPTNO NUMBER(2));

SQL> DESC EMP;Name Null? Type----------------------------------------- -------- -------------- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATESAL NU MBER(7,2) COMM NU MBER(7,2) DEPTNO NUMBER(2)

For insertionINSERT INTO EMP VALUES(7934, 'MILLER','CLERK',7782, TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10);

Integrity constraints: Are used to implement business rules To validate the data To maintain data integrity To implement business rules

Integrity constraints ensure the data inserted in a table has integrity. Inserted data will be always correctGenerally constraints mean „a rule‟;According to RDBMS the different integrity constraints are

Entity integrity: is implemented by UNIQUE, PRIMARY key Domain integrity: is implemented by NOT NULL, CHECK Referential integrity: is implemented by FORIGN key

UNIQUE:- this constraint doesn‟t allow duplicates, but allow null values.Syntax: empno number unique

NOT NULL:- this constraint doesn‟t allow null values but allow duplicatesSyntax: ename varchar2(20) not null;

PRIMARY KEY:- It doesn‟t allows duplicate values and null valuesSyntax: eno number(4) primary key

Page 18: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Check: if validations is based on some condition then we use check constraintSyntax: sal number(7,2) check(sal>300)

FOREIGN key:- used to establish relation between two tablesRules: value of foreign key should watch with primary key values or foreign key can

be null. But doesn‟t allow new values other than primary key values and null valuesAfter declaring foreign key a relationship is established between the two tables and that relationship is called parent-child relation or master-slave relation.Referring table is child-->empReferred table is parent-->dept

ExSQL> create table sailors(sid integer primary key,sname varchar2(13),rating integer,age number);Table created.SQL> create table boats(bid integer primary key,bname varchar2(13),color varchar2(10)); Table created.SQL> create table reserves(sid integer references sailors(sid),bid integer references boats(bid),day date);Table created.

SQL> create table student(regno varchar2(12), name varchar2(12),address varchar2(29), profile varchar2(23),branch varchar2(6),phno number,password varchar2(34)) ;Table created. SQL> desc student;Name Null? Type---------------- ------- --------------------- REGNO VARCHAR2(12) NAME VARCHAR2(12) ADDRESS VARCHAR2(29) PROFILE VARCHAR2(23) BRANCH VARCHAR2(6) PHNO NUMBER PASSWORD VARCHAR2(34)

Update: is used to modify the data. Means to update the particular field value of a row we use updateSQL> update emp set sal=sal+100 where sal<1000;2 rows updated.Delete: is used to modify the data. Means to delete the particular row we use delete commandSQL> delete from emp where empno=7902;1 row deleted.

Page 19: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

ALTER COMMNAD: Is Used To Modify The Data definition Of A Table

To rename a column:Alter table <tname> rename column <old-name> to <new –name> SQL> Alter table student rename column name to sname;Table altered.

SQL> desc student;Name Null? Type---------------- ------- --------------------- REGNO VARCHAR2(12) SNAME VARCHAR2(12) ADDRESS VARCHAR2(29) PROFILE VARCHAR2(23) BRANCH VARCHAR2(6) PHNO NUMBER PASSWORD VARCHAR2(34) To modify a columnIe increment or decreament field size, to change datatype, to change null values to not null

values, to chane not null values to valuesSQL> alter table student modify regno varchar2(10); Table altered

Adding a column:SQL> alter table student add(yofad date); Table altered.SQL> desc student;Name Null? Type---------------- ------- --------------------- REGNO VARCHAR2(12) SNAME VARCHAR2(12) ADDRESS VARCHAR2(29) PROFILE VARCHAR2(23) BRANCH VARCHAR2(6) PHNO NUMBER PASSWORD VARCHAR2(34) YOFAD DATE Dropping columns:SQL> alter table student drop column profile;Table altered.To change the data type:SQL> alter table student modify(yofad varchar2(12)); Table altered.Changing to null to not nullSQL> alter table student modify(sname not null); Table altered.

Page 20: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

22 Dustin 7 4529 Brutus 1 3331 Lubber 8 55.532 Andy 8 25.558 Rusty 10 3564 Horatio 7 3571 Zorba 10 1674 Horatio 9 3585 Art 3 25.595 Bob 3 63.5

SQL> create table sailors(sid integer primary key,sname varchar2(13),rating integer,age number);Table created.

SQL> create table boats(bid integer primary key,bname varchar2(13),color varchar2(10)); Table created.

SQL> create table reserves(sid integer references sailors(sid),bid integer referencesboats(bid),day date);Table created.

SQL> desc sailors;Name Null? Type----------------------------------------- -------- ------------------- SID NOT NULL NUMBER(38) SNAME VARCHAR2(13) RATING NUMBER(38)AGE NUMBER

SQL> desc boats;Name Null? Type----------------------------------------- -------- ------------------- BID NOT NULL NUMBER(38) BNAME VARCHAR2(13) COLOR VARCHAR2(10)

SQL> desc reserves;Name Null? Type----------------------------------------- -------- ------------------- SID NUMBER(38)BID NUMBER(38)DAY DATE

S AIL O RS SID SNAME RATING AGE

Page 21: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

BOAT

BID BNAME COLOR--- ------------- ------101 Interlake blue102 Interlake red103 Clipper green104 Marine red

RE S ER V ES SID BID DAY

----- ---------- ---------22 101 10-OCT-9822 102 10-OCT-9822 103 10-AUG-9822 104 10-JUL-9831 102 11-OCT-9831 103 11-JUN-9831 104 11-DEC-9864 101 09-MAY-9864 102 09-AUG-98

Find all sailors with a rating above 7.SQL> select * from sailors where rating>7;

SID SNAME RATING AGE---------- ------------- ---------- ----------

31 Lubber 8 55.532 Andy 8 25.558 Rusty 10 3571 Zorba 10 1674 Horatio 9 35

LIKE o p er a t o r : Find the ages of sailors whose name begins and ends with B and has at lease three characters,SQL> select s.age from sailors s where s.sname like 'B_%b';

AGE-----63.5

Page 22: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

S et-Co mp arison Op era tors:

{<,<=,=,<>,>=,>}Find sailors whose rating is better than some sailor called HoratioSQL> select s.sname from sailors s where s.rating> any (select s2.rating from sailors s2 where s2.sname='Horatio');SNAME----------- Lubber Andy Rusty Zorba Horatio

Find the sailors with the highest ratingSQL> select s.sid,s.sname from sailors s where s.rating>= all(select s2.rating from sailors s2);

SID SNAME----- -------------58 Rusty71 Zorba

Find the names of sailors who have reserved all boatsSQL> select s.sname from sailors s where not exists ((select bid from boats) except (select r.bid from reserves r where r.sid=s.sid));

Agg re ga t e fun c tion s : It take a collection of values as input and return a single valueMin(a):-returns minimum of column values Max(a):-returns maximum of column values Avg(a):- retunes average of column values Sum(a):- returns sum of columns values Count(a): -returns number of values in a column.

Find the average age of all sailors SQL> select avg(s.age) from sailors s; AVG(S.AGE)----------

36.9

Find the average age of sailors with a rating of 10SQL> select avg(s.age) from sailors s where s.rating=10;

AVG(S.AGE)----------

25.5

Page 23: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Find the name and age of the oldest sailorSQL> select s.sname, s.age from sailors s where s.age=(select max(s2.age) from sailors s2);ORSQL> select s.sname, s.age from sailors s where (select max(s2.age) from sailors s2)=s.age;SNAME AGE------------- ---------- Bob 63.5

Count the number of sailorsSQL> select count(*) from sailors;

COUNT(*)----------

10Count the number of different sailors names; SQL> select count(distinct s.sname) from sailors s; COUNT(DISTINCTS.SNAME)----------------------

9Find the names of sailors who are older than the oldest sailor with a rating of 10SQL> select s.sname from sailors s where s.age>(select max(s2.age) from sailors s2 where s2.rating=10);SNAME------------- Dustin Lubber Bob

RESULT:

The sql commands for creation of table is executed successfully and output verified

Page 24: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Expno: 1.3 DATE: 10-7-2012SET OPERATIONS

Aim :-To Practice set operations, nested queries and joins in SQL

Theory:-A nested query is query that has another query embedded within it, the embedded query is called sub query.Nested Queries in this inner sub queries are completely dependent on the outer queries Correlated Nested queries in this inner sub query has been completely independent of the outer queryThere are some points to be remembered while using nested queries. They are

Use single-row operators with single-row sub queries and use multiple-row operators with multiple-row sub queries.

In Single row sub query, operators used are <, >, <= , >=, <> In multiple row sub query, operators used are all, some and in. whose meanings are

every value returned by the sub query, at least one value returned by the sub query , any value in the list respectively.

SQL supports the set operations union, intersection and minus with the key words union, intersect, and except (minus in oracle). It also supports exists and not exists. Exists operator returns true if the set is not empty and not exists returns true if the set is empty. The UNION operator returns records from the result of both queries after eliminating the duplicate records which are common in both. There is another option of union, the UNION ALL operator, which returns records from the result of both queries, including duplicate records which are common in both. The INTERSECT operator returns the records which are common in the result of both queries. The EXCEPT operator returns the records which are in the result of the first query but not in the result of the second one

We can use the join capability y in SQL to bring together data that is stored in different tables by creating a link between them. When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. A join with a join condition is known as conditional join. When a join condition is invalid or omitted completely, the result is a Cartesian product, in which all combinations of rows are displayed. All rows in the first table are joined to all rows in the second table.

Equiv.-Join is a special case of condition join where the condition contains only equalities.A natural join is an Equiv.-Join on all common fields of the related tables. If there are any values in one table that do not have corresponding values in the other, in an Equi-join that row will not be selected. Such rows can be forcefully selected by using outer join. The left outer join takes all the rows in the left table (first table in the join) and pads the rows which don‟t have a matching row with null values for all other attributes in the right table. The right outer join takes all the rows in the right table( first table in the join) and pads the rows which doesn‟t have a matching row with null values for all other attributes in the left table. The full outer join includes all the rows from both tables and pads the rows which doesn‟t have a matching row with null values for all other attributes in the other table.

Page 25: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

In SQL there are four join types namely inner join, left outer join, right outer join and full outer join. And there are three join conditions natural, on <condition>, using (field1, field2,.. ).Here on <condition> is for conditional join and using (field1, field2,..) is like natural join but the join fields are fields specified in the using class.

Conditional joins: The following statement applies Cartesian product on dept and emp tables and displays the records which satisfy the condition i.e. the details of department no 10 employees‟ details who doesn‟t belong to the department.Select * from dept,emp where dept.deptno<>emp.deptno and dept.deptno=10;

Equi-join: The following statement applies Cartesian product on dept and emp tables and displays the records which satisfy the condition i.e. the details of departments which have some employees along with employees‟ details who belong to the department. The condition here is equality condition. So, it is also known as Equi-join.select * from dept,emp where dept.deptno=emp.deptno;

inner join: An alternative way of using the above query isselect * from dept inner join emp on dept.deptno=emp.deptno;

left outer join: The following statements display all the dept records which have the matching emp records along with the matching emp records and in addition displays dept records which does not have any employees.select * from dept left outer join emp on dept.deptno=emp.deptno; ORselect * from dept, emp where dept.deptno =emp.deptno(+);

right outer join: The following statements display all the dept records which have the matching emp records along with the matching emp records and in addition displays emp records which does not have any department.select * from dept right outer join emp on dept.deptno=emp.deptno; ORselect * from dept, emp where dept.deptno(+) =emp.deptno

full outer join: The following statements display all the dept records which have the matching emp records along with the matching emp records and in addition displays emp records which does not have any department and dept records which does not have any employees.select * from dept full outer join emp on dept.deptno=emp.deptno; ORselect * from dept, emp where dept.deptno(+) =emp.deptno(+);

natural inner join: The following statement inner joins the two tables by equating all the common fields i.e. in this case it is deptno. So the result is same as the above inner join but in the display the common column deptno is displayed onl y once.select * from dept natural inner join emp;Natural left outer join: The following statement left outer joins the two tables by equating all the common fields i.e. in this case it is deptno. So the result is same as the above left outer join but in the display the common column deptno is displayed only once.select * from dept natural left outer join emp;

Page 26: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Natural right outer join: The following statement left outer joins the two tables by equating all the common fields i.e. in this case it is deptno. So the result is same as the above right outer join but in the display the common column deptno is displayed only once.select * from dept natural right outer join emp;

Natural full outer join: The following statement full outer joins the two tables by equating all the common fields i.e. in this case it is deptno. So the result is same as the previous full outer join but in the display the common column deptno is displayed onl y onceselect * from dept natural full outer join emp;

Examples: Conditional joins:The following statement applies Cartesian product on dept and emp tables and displays therecords which satisfy the condition i.e. the details of department no 10 employees‟ details who doesn‟t belong to the departmentSQL> select * from dept,emp where dept.deptno<>emp.deptno and 2 dept.deptno=10;

DEPTNO DNAME LOC EMPNO ENAME JOB---------- -------------- ------------- ---------- ---------- ---------

MGR HIREDATE SAL COMM DEPTNO---------- --------- ---------- ---------- ----------

10 ACCOUNTING NEW YORK 7369 SMITH CLERK7902 17-DEC-80 800 20

10 ACCOUNTING NEW YORK 7499 ALLEN SALESMAN7698 20-FEB-81 1600 300 30

10 ACCOUNTING NEW YORK 7521 WARD SALESMAN7698 22-FEB-81 1250 500 30

**11 rows selected.

Equi-join:The following statement applies Cartesian product on dept and emp tables and displays therecords which satisfy the condition i.e. the details of departments which have some employees along with employees‟ details who belong to the department. The condition here is equality condition. So, it is also known as Equi-join.

SQL> select * from dept,emp where dept.deptno=emp.deptno;DEPTNO DNAME LOC EMPNO ENAME JOB

---------- -------------- ------------- ---------- ---------- --------- MGR HIREDATE SAL COMM DEPTNO

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

20 RESEARCH DALLAS 7369 SMITH CLERK7902 17-DEC-80 800 2030 SALES CHICAGO 7499 ALLEN SALESMAN

7698 20-FEB-81 1600 300 3030 SALES CHICAGO 7521 WARD SALESMAN

7698 22-FEB-81 1250 500 30

*

Page 27: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

*14 rows selected.

Page 28: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

OPERATIONS:Note: these operations are implemented on sailors, reserves and boats table created in expno:1.2

Find the names and ages of all sailors.SQL> select distinct s.sname,s.age from sailors s;

SNAME AGE------------- ------ Andy 25.5Zorba 16Art 25.5Bob 63.5Lubber 55.5Horatio 35Dustin 45Brutus 33Rusty 359 rows selected.

Find all sailors with a rating above 7.SQL> select * from sailors where rating>7;

SID SNAME RATING AGE---------- ------------- ---------- ----------

31 Lubber 8 55.532 Andy 8 25.558 Rusty 10 3571 Zorba 10 1674 Horatio 9 35

Find the names of sailors who have reserved a bid 103.SQL> select s.sname from sailors s, reserves r where s.sid=r.sid and r.bid=103;OrBy using nested queries( In this inner sub queries are completely dependent on the outer queries)SQL> select s.sname from sailors s where s.sid in (select r.sid from reserves r where r.bid=103);OrBy using Correlated Nested queries(In this inner sub query has been completely independent of the outer query )SQL> select s.sname from sailors s where exists ( select * from reserves r where r.bid=103 and r.sid=s.sid);SNAME------------- Dustin Lubber Horatio

Page 29: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Find the sids and names of sailors who have reserved a red boatSQL> select s.sid,s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and b.color='red';

SID SNAME------ -------------22 Dustin22 Dustin31 Lubber31 Lubber64 Horatio

By using Nested QueriesSQL> select s.sid,s.sname from sailors s where s.sid in (select r.sid from reserves r wherer.bid in(select b.bid from boats b where b.color='red'));

SID SNAME---------- -------------

22 Dustin31 Lubber64 Horatio

Find the colors of boats reserved by lubberSQL> select b.color from sailors s,reserves r,boats b where s.sname='Lubber' and s.sid=r.sid and r.bid=b.bid;COLOR---------- redgreen red

Find the names of sailors who have reserved at least one boat; SQL> select s.sname from sailors s, reserves r where s.sid=r.sid; SNAME------------- Dustin Dustin Dustin Dustin Lubber Lubber Lubber Horatio Horatio9 rows selected.

Page 30: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Compute increments for the ratings of persons who have sailed two different boats on the same day.

SQL> select s.sname,s.rating+1 as rating from sailors s,reserves r1,reserves r2 where s.sid=r1.sid and s.sid=r2.sid and r1.day=r2.day and r1.bid<>r2.bid;SNAME RATING------------- ---------- Dustin 8Dustin 8

Find the ages of sailors whose name begins and ends with B and has at least three characters,SQL> select s.age from sailors s where s.sname like 'B_%b';

AGE-----63.5

Find the names of sailors who have reserved a red or a green boat.SQL> select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and(b.color='red' or b.color='green');

SNAME------------- Dustin Dustin Dustin Lubber Lubber LubberHoratio 7 rows selected.(OR)SQL> select s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and b.color='green' union select s1.sname from sailors s1,reserves r1,boats b1 where s1.sid=r1.sid and r1.bid=b1.bid and b1.color='red';SNAME------------- Dustin Horatio LubberFind the names of sailors who have reserved both a red and a green boat.SQL> select s.sname from sailors s, reserves r1,reserves r2, boats b1,boats b2 where s.sid=r1.sid and r1.bid=b1.bid and s.sid=r2.sid and r2.bid=b2.bid and b1.color='red' and b2.color='green';SNAME------------- Dustin Dustin Lubber Lubber

Page 31: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

(or)SQL> select s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and b.color='green' intersect select s1.sname from sailors s1,reserves r1,boats b1 where s1.sid=r1.sid and r1.bid=b1.bid and b1.color='red';SNAME------------- Dustin Lubber

OR(By using Nested queries)SQL> select s.sname from sailors s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and b.color='red' and s.sid in(select s2.sid from sailors s2,boats b2,reserves r2 where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green');SNAME------------- Dustin Dustin Lubber Lubber

Find the sids of all sailors who have reserved red boats but not green boats;select s.sid from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and b.color='red' minus select s2.sid from sailors s2, reserves r2, boats b2 where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green';SID-------64Find all sids of sailors who have a rating of 10 or have reserved boat 104SQL> select s.sid from sailors s, reserves r, boats b where s.rating=10 union select s1.sid from sailors s1,reserves r1, boats b1 where s1.sid=r1.sid and r1.bid=b1.bid and b1.bid=104;

SID---------

22315871

Find the names of sailors who have not reserved at least one boat.SQL> select s.sname from sailors s where s.sid not in(select r.sid from reserves r where r.bid in(select b.bid from boats b));SNAME------------- Brutus Andy Rusty ZorbaArtBob

Page 32: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Find the names of sailors who have not reserved a red boat.SQL> select s.sname from sailors s where s.sid not in ( select s1.sid from sailors s1,reserves r1,boats b1 where s1.sid=r1.sid and r1.bid=b1.bid and b1.color='red');(Or)SQL> select s.sname from sailors s where s.sid not in(select r.sid from reserves r where r.bid in(select b.bid from boats b where b.color='red'));SNAME------------- Brutus Andy Rusty Zorba HoratioArtBob 7 rows selected.

Find sailors whose rating is better than some sailor called HoratioSQL> select s.sname from sailors s where s.rating> any (select s2.rating from sailors s2 where s2.sname='Horatio');SNAME------------- Lubber Andy Rusty Zorba Horatio

Find the sailors with the highest ratingSQL> select s.sid,s.sname from sailors s where s.rating>= all(select s2.rating from sailors s2);

SID SNAME----- -------------58 Rusty71 Zorba

Find the names of sailors who have reserved all boatsSQL> select s.sname from sailors s where not exists ((select bid from boats) except (select r.bid from reserves r where r.sid=s.sid));Find the average age of all sailors SQL> select avg(s.age) from sailors s; AVG(S.AGE)----------

36.9Find the average age of sailors with a rating of 10SQL> select avg(s.age) from sailors s where s.rating=10;AVG(S.AGE)----------

25.5Find the name and age of the oldest sailorSQL> select s.sname, s.age from sailors s where s.age=(select max(s2.age) from sailors s2);

Page 33: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

8 25.57 353 25.5

(OR)SQL> select s.sname, s.age from sailors s where (select max(s2.age) from sailors s2)=s.age;SNAME AGE------------- ---------- Bob 63.5

Count the number of sailorsSQL> select count(*) from sailors;

COUNT(*)----------

10

Count the number of different sailors names; SQL> select count(distinct s.sname) from sailors s; COUNT(DISTINCTS.SNAME)----------------------

9Find the names of sailors who are older than the oldest sailor with a rating of 10SQL> select s.sname from sailors s where s.age>(select max(s2.age) from sailors s2 where s2.rating=10);SNAME------------- Dustin Lubber Bob

Find the age of the youngest sailors for each rating level(This can be possible by using grouping clauses)SQL> select s.rating,min(s.age) from sailors s group by s.rating;

RATING MIN(S.AGE)---------- ----------

1 338 25.57 353 25.510 169 35

Find the age of the youngest sailor who is eligible to vote( means at least 18 years old)for each rating level with at least two such sailors.SQL> select s.rating,min(S.age) as minage from sailors s where s.age>=18 group by s.rating having count(*)>1;

RATING MINAGE---------- ----------

Page 34: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

For each red boat, find the number of reservations for this boatSQL> select b.bid,count(*) as sailorscount from boats b,reserves r where r.bid=b.bid and b.color='red' group by b.bid;

BID SAILORSCOUNT---------- ------------

102 3104 2

Find the average age of sailors for each rating level that has at least two sailors

SQL> select s.rating,avg(s.age) as avgage from sailors s group by s.rating having count(*)>1;

RATING AVGAGE---------- --------

8 40.57 403 44.510 25.5

RESULT:The simple sql commands by using set operators is executed successfully and output

verified

Page 35: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Expno:1.4 Date: 24-7-2012

FUNCTIONS AND PROCEDURES

Aim:-To create and execute functions and procedures

Theory:-PL-> procedural languageIt is an extension to SQL generally there are two types of languages are in the database

Non-Procedural ProceduralEx:- SQL EX:- PL/SQLHere we specify the operation, there is nohow it possible, means how it done

Here we specify the operations and itprocedure means how it doing that operation are also available

In SQL only one (command) statement sendto server.Means one by one

In PL/SQL, SQL commands(Statements) cangrouped into one block and that block can be submitted to oracle server

In pl/sql number of request and response between user and oracle server are reduced and performance is improved.PL/SQL is a programming language, so pl/sql supports conditional statementsPL/SQL supports loopsPl/SQL supports modular programming (i.e. functions and procedure) PL/SQL supports exception handlingPL/SQL supports transaction management

Procedures:Procedures are similar to Functions, in that they can be executed to perform work.

The primary difference is that procedures cannot be used in a SQL statement. Another difference is that it can return multiple values. Procedures are traditionally the workhorse of the coding world and functions are traditionally the smaller, more specific pieces of code. PL/SQL maintains many of the distinctions between functions and procedures found in many general-purpose programming languages, but in addition, functions can be called from SQL, while procedures cannot.

FunctionsA function is named pl/sql block that accept some input, performs a task and must returns avalue. Functions are created for to do calculations and to fetch a value from database Function must return a value by using “return” word, it returns only one value Procedure used to update the balance of the customer andFunction used to get the balance of the customer

PL/SQL blocks Anonymous block Named block

Page 36: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Anonymous block:A block without name is called anonymous block. Anonymous means name lessStructure of anonymous block

Declare <variables> BEGIN STATEMENTS; END

Named block:Syntax of the named blocks (procedures and functions):

CREATE [OR REPLACE] PROCEDURE [owner_name.]procedure_name[(parameter1 [IN | OUT | IN OUT] datat ype][,...n)]]{IS | AS} PL/SQL block ;

CREATE [OR REPLACE] FUNCTION [owner_name.]function_name[(parameter1 [IN | OUT | IN OUT] datat ype][,...n)]] RETURN datat ype{IS | AS} PL/SQL block;

Data manipulation and query statements of SQL are included within procedural units of code. PL/SQL Block Structure is as follows.

<header>IS | ASDeclaration sectionBEGINExecutable sectionEXCEPTION (optional) Exception sectionEND;

Section DescriptionHeader Required for named blocks. Specifies the way the program is called by other PL/SQL blocks. Anonymous blocks do not have a header. They start with the DECLARE keyword if there is a declaration section, or with the BEGIN keyword i f there are no declarations.

Declaration It is optional. Declares variables, cursors, TYPEs, and local programs that are used in the block' s execution and exception sections.Execution Optional in package and TYPE specifications; contains statements that are executed when the block is run.Exception Optional; describes error-handling behavior for exceptions raised in the executable section.

Page 37: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

An example of an anonymous block:The following code declares today as date data type and the default value is system datewhich can be obtained from the environment variable SYSDATE. Display the date after concatenating it with the string.

DECLAREtoday DATE DEFAULT SYSDATE;BEGINDBMS_OUTPUT.PUT_LINE ('Today is ' || today);END;SQL> set serveroutput onSQL> @ s y sda t e

6 /Today is 27-OCT-12PL/SQL procedure successfully completed.

Example:Procedure that computes and displays tax to be paid i f income is passed as parameterCREATE OR REPLACE PROCEDURE tax1(p_value IN NUMBER)IS BEGINDBMS_OUTPUT.PUT_LINE (p_value * 0.08); END;

Function that returns tax to be paid i f income is passed as parameter CREATE OR REPLACE FUNCTION tax2(p_value IN NUMBER) RETURN NUMBERIS BEGINRETURN (p_value * 0.08); END;

PL/SQL Data Types1) Scalar : Single values with no internal components. (ALL built in types are called

scalar types)2) Composite: Data items that have internal components that can be accessed

individually. (It allows group alike array in c,java)3) Reference:-Pointers to other data items. Explained in Using Cursor Variables (REF

CURSORs).4) Large Object (LOB):-Pointers to large objects that are stored separately from other

data items, such as text, graphic images, video clips, and sound waveforms.

Predefined PL/SQL Scalar Data Types and SubtypesScalar data types store single values with no internal components.

number(p,s) :Where p is the precision and s is the scale.example, number(7,2) is a number that has 5 digits before the decimal and 2 digits after the decimal.

dec(p,s):Where p is the precision and s is the scale. example, dec(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal.

Page 38: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

decimal(p,s): Where p is the precision and s is the scale. decimal(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal.

Date/Time Datatypes: timestamp (fractional seconds precision) Includes year, month, day, hour, minute, and seconds. example: timestamp(6)

timestamp (fractional seconds precision) with time zone: ncludes year, month, day, hour, minute, and seconds; with a time zone displacement value. For example: timestamp(5) with time zone

timestamp (fractional seconds precision) with local time zone: Includes year, month, day, hour, minute, and seconds; with a time zone expressed as the session time zone. For example: timestamp(4) with local time zone

interval year (year precision) to month: Time period stored in years and months.For example: interval year(4) to month interval day (day precision) to second (fractional seconds precision): Time period stored in days, hours, minutes, and seconds.For example: interval day(2) to second(6)

Systax: variable name dataype;Ex:x number(4) S varchar2(20)

D data;T timestamp;

X number(2)X is a scalar type then x allow one value with two digits;

Composite type datatypes;Composite type allows group of elements there are two composite typesPl/sql table or pl/sql array: allows group of elements of same data typesPl/sql record : allows group of elements of dissimilar types

Reference type: There are two type:%type:- used to refer the data type of the date type of particular column in a tableEx: e emp.empno%type;Whatever data type we declare in table emp for empno that datatype is assign in e.%rowtype: used to refer the data type of a record in a tableSy: e emp%row type.

Operators::= assignment operator: used to assign value to a variableEx X:=10;|| concatenation operator:- used to concatenate two strings;

How to display or print message in pl/sqlDbms_oputpu.put_lint(message);

To enable the dbms_output execute the following commandSQL> SET SERVEROUTPUT ON;To write a plsql program at sql prompt gives this commandEd prog1

Page 39: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

After giving this command one file is created with the prog1.sql nameWrite program save and exit from editor(notepad) after exit from note pad compile and run the program@ p r og1

CURSORS:Cursors are used to process multiple records ie., row by row processingWhen select statements is submitted to oracle server oracle server get the data from data base and loads the data into temporary memory called context area or active set

Using cursor we can give the name to the context area and get one by one recard from context and process the recordCursor is a name pointing to the context areaCoursers are two typesExplicit cursorImplicit cursor

Explicit cursor: cursor declared by user are called explicit cursorsTo use explicit cursor follow below steps

Declare cursor Open cursor Fetch record from cursors Close cursor

Syntax: cursor<name> is select statement

PROCEDURE:

Go to SQL prompt Execute the following commands.

o set autocommit on;o set serveroutput on;

Type edit file1.sql (Then the default editor i.e. notepad is invoked.) Type the procedure or function definition. Save it and exit notepad. Compile the procedure or function by t yping the following command.

o @ f i l e 1 If there are any errors type the following command to show the errors.

o Show errors; Type the following command to edit the file and introduce the corrections.

o edit file1.sql Save the file and exit the editor.

Compile the procedure by t yping the following command again.o @ f i l e 1

If there are any errors type the following command to show the errors.o show errors;

Continue the process of reediting and recompilation until the procedure or function issuccessfull y created.

Page 40: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

After successful creation of procedure t ype the following command to execute the procedure.

o exec procedurename(parameter);o example1 exec pemp1;o example2 exec tax1(1000);

If it is a function t ype the following command to execute the function.o select tax2(1000) from dual;

Execute Following sequence of statements for getting the valueo returned by the function into bind variable and print it.o variable v1 number;

exec :v1:=tax2(1000);o print v1;

We can view the function names and procedure names using the command.o select object_name, object_t ype from user_objectso where object_t ype in („PROCEDURE‟,‟FUNCTION‟)o order by object_name;

We can view the function or procedure body using the command.o select text from user_source where name =‟TAX1‟ ;

Exit SQL after saving the work.o commit;o exit;

OPERATIONS:Example for the function creations and execution of that functionSQL> ed tax2create or replace function tax2(p in number)return number isbegin return(p*2); end;

SQL> @ t ax2 //for compilation7 /

Function created.SQL> variable v1 number; SQL> exec :v1:=tax2(100);PL/SQL procedure successfully completed. SQL> print v1;

V1------200

Page 41: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Anonymous procedure exampleSQL> ed eeedeclarex number(2); y number(2); z number(3); beginx:=&x; y:=&y; z:=x+y;dbms_output.put_line('answer is');dbms_output.put_line(z);end;SQL> @ ee e 12 /Enter value for x: 7 old 6: x:=&x;new 6: x:=7;Enter value for y: 8 old 7: y:=&y;new 7: y:=8;answer is 15PL/SQL procedure successfully completed.

Note: in anonymous block both compiling and exaction we use @ file n a me But in named block, for compilation @file n a me For execution exec procedure name

Anonymous block for creating procedure for finding biggest numberSQL> ed bigpDeclarex number(2); y number(2); big number(2);small number(2);begin x:=&x; y:=&y;big:=greatest(x,y); small:=least(x,y); dbms_output.put_line('big =' ||big); end;SQL> @ b i g p (for compiling and execution)13 /

Enter value for x: 7 old 7: x:=&x;new 7: x:=7;Enter value for y: 9 old 8: y:=&y;new 8: y:=9;big =9PL/SQL procedure successfully completed.

Page 42: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

FA C TORIAL O F T H E GIV E N N U M BER:

By using name blockSQL>SQL> ed factcreate or replace procedure factisi number;fact number:=1; m number:=&m; beginfor i in 1..m loop fact:=fact*i; end loop;dbms_output.put_line('the factorial of '|| m ||'is' || fact);end;

SQL> @ f a c t (for compilation)13 /

Enter value for m: 5old 5: m number:=&m; new 5: m number:=5; Procedure created.

SQL> exec fact (for execution)PL/SQL procedure successfully completed.SQL> set serveroutput onSQL> exec factthe factorial of 5is120PL/SQL procedure successfully completed.

Page 43: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

FIB O N A C C I S ERIES

SQL> ed ex2 (file name is ex2)

create or replace procedure fib(m in number)isf number:=0; t number:=1;s number:=1; d number:=1; c number;begin dbms_output.put_line(f); dbms_output.put_line(t); dbms_output.put_line(s); for i in 2..m-1loop t:=s; s:=d; c:=t+s; d:=c;dbms_output.put_line(c);end loop;end;

SQL> @ e x2 (compilation is done by using file name ie ex2)18 /Procedure created.

SQL> exec fib(5); (execution is done by using procedure name, not by file name ie not ex2 , procedure name is fact)011235PL/SQL procedure successfully completed.

Page 44: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

PRI N TING T HE PRI M E N UM BER OF A GIV E N R A N GE

SQL> ed ex3

create or replace procedure prime(m in number)isc number;beginfor i in 2..m loopc:=0;for j in 2..trunc(i/2)loopif (mod(i,j)=0) then c:=c+1;end if; end loop; if(c=0) thendbms_output.put_line(i);end if; end loop; end;SQL> @ e x3 19 /

Procedure created.

SQL> exec prime(10);2357

PL/SQL procedure successfully completed.

Page 45: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Prin ting th e p rime n u mb er of a given range by u sin g f un ction

SQL> ed fun1

create or replace function funp(m in number)return number isc number;beginfor i in 2..m loopc:=0;for j in 2..trunc(i/2)loopif (mod(i,j)=0) then c:=c+1;end if; end loop; if(c=0) thendbms_output.put_line(i);end if; end loop; return(m); end;

SQL> @ fun 1 21 /

Function created.SQL> variable v number; SQL> exec :v:=funp(10);2357

PL/SQL procedure successfully completed. SQL> print v;

V----------

10SQL>

Page 46: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Plsql program for finding any number model ie even or odd or primeSQL> ed findallcreate or replace procedure try1isc number:=0;p number:=&p; begin if(mod(p,2)=1) then for j in 2..trunc(p/2) loopif(mod(p,j)=0) then c:=c+1;end if; end loop; if(c=0) thendbms_output.put_line(p || 'is prime ');elsedbms_output.put_line(p || 'is odd ');end if;elsif(p=2) thendbms_output.put_line(p || 'both even on prime number');elsif(mod(p,2)=0) then dbms_output.put_line('is even'); elsedbms_output.put_line('is invalid table ');end if;end;

SQL> @ f i n d all 26 /Enter value for p: 9old 4: p number:=&p; new 4: p number:=9; Procedure created.

SQL> exec findall9is oddPL/SQL procedure successfully completed.

SQL> @ f i n d all 26 /Enter value for p: 5old 4: p number:=&p; new 4: p number:=5; Procedure created.

SQL> exec findall5is primePL/SQL procedure successfully completed.

SQL> @ f i n d all 26 /Enter value for p: 4old 4: p number:=&p; new 4: p number:=4; Procedure created.

SQL> exec findall4 is evenPL/SQL procedure successfully completed.

Page 47: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Procedure that displays name of an employee if his empno is given. It uses the %type.

SQL> ed ename

CREATE OR REPLACE PROCEDURE enameISno emp.empno%type:=&no; empname emp.ename%type; BEGINSELECT ename INTO empname FROM empWHERE empno = no;DBMS_OUTPUT.PUT_LINE ('name of employe whose empno '|| no || 'is ' ||empname); END;/

SQL> @ e n a m e Enter value for no: 7698old 3: no emp.empno%type:=&no; new 3: no emp.empno%type:=7698; Procedure created.

SQL> exec enamename of employe whose empno 7698is :BLAKEPL/SQL procedure successfully completed.

PROGRAM BY USING %ROW TYPE%ROW TYPE: IS REDUCES THE NO OF VARIABLE

SQL> ED CUROWCREATE OR REPLACE PROCEDURE CUROWIS E EMP%ROWTYPE; VENO EMP.EMPNO%TYPE; BEGINVENO :=&eno;select * into e from emp where empno=veno;dbms_output.put_line('name:-'||e.ename);end;

SQL> @C U ROW 10 /Enter value for eno: 7698 old 5: VENO :=&eno; new 5: VENO :=7698; Procedure created.SQL> exec CUROWname:-BLAKEPL/SQL procedure successfully completed.

Page 48: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

CURSOR EXAMPLE Cursor c1 is select * from emp;

The select statement associated with c1 named cursor after this Open cusor

SYNTAX: OPEN <CURSOR-NAME>Ex: open c1

Fetch record from cusrosr: is used to fetch recard from context areaSyntax: fetch<cursor-name> into <variable>Ex: fetch c1 into x,y,z---

Closing cursor: after completing the fetching we are close the cursorSyntax: close<cursor-name>Ex :- close c1;

creates procedure to display empno and ename of all employees in emp table using cursors.SQL> ED CUR1CREATE OR REPLACE PROCEDURE CUR1ISCURSOR c IS SELECT empno, ename FROM emp;no emp.empno%type; name emp. ename%type; BEGINOPEN c; LOOPFETCH c into no, name; EXIT WHEN c %notfound;DBMS_OUTPUT.PUT_LINE (TO_CHAR(no)|| '--->' || name); END LOOP;CLOSE c; END;/SQL> @C U R1 Procedure created.SQL> EXEC CUR17369--->SMITH7499--->ALLEN7521--->WARD7566--->JONES7654--->MARTIN7698--->BLAKE7782--->CLARK7788--->SCOTT7839--->KING7844--->TURNER7876--->ADAMS7900--->JAMES7902--->FORD7934--->MILLERPL/SQL procedure successfully completed.

Page 49: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

The following code creates procedure to update salaries of employees using cursorsSQL> ed curupdate

CREATE OR REPLACE PROCEDURE curupdateISCURSOR c1 ISSELECT deptno,empno,ename,sal FROM emp FOR UPDATE OF sal; BEGINFOR emp_record IN c1LOOPIF emp_record.sal> 2000 THENUPDATE emp SET sal=emp_record.sal* 1.10WHERE CURRENT OF c1; END IF;END LOOP; END;

SQL> @ c u r u p d a t e 15 /Procedure created.

SQL> exec curupdatePL/SQL procedure successfully completed.

RESULT:The creation of functions and procedures are executed successfully and output verified

Page 50: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Expno: 1.5 Date: 24-7-2012TRIGGERS

Aim:-The aim of the experiment is to create views and triggers and to study the behavior of viewsand triggers.

Theory:A trigger is a procedure that is automatically invoked by the DBMS in response to

specified changes to the database, and is typically specified by the DBA. A database that has a set of associated triggers is called an active database.A trigger description contains three parts:

Event: A change to the database that activates the trigger. Condition: A query or test that is run when the trigger is activated. Action: A procedure that is executed when the trigger is activated and its conditions

true.

SYNTEAX and Description:

CREATE [OR REPLACE] TRIGGER trigger_name{BEFORE | AFTER | INSTEAD OF}{[DELETE] [OR] [INSERT] [OR] [UPDATE [OF column [,...n] ]] ON{table_name | view_name}[FOR EACH { ROW | STATEMENT }] [WHEN (conditions)]code block

Triggers, by default, fire once at the statement level. That is, a single INSERT statement might insert 500 rows into a table, but an insert trigger on that table fires only one time. Some vendors allow a trigger to fi re for each row of the data-modification operation. So, a statement that inserts 500rows into a table that has a row-level insert trigger fi res 500

In addition to being associated with a specific data-modification statement (INSERT, UPDATE, or DELETE) on a given table, t riggers are associated with a specific time of fi ring. In general, triggers can fire BEFORE the data-modification statement is processed, AFTER it is processed, or (when supported by the vendor) INSTEAD OF processing the statement.

Triggers that fire before or instead of the data-modification statement do not see the changes that the statement renders, while those that fire afterwards can see and act upon the changes that the data-modification statement renders. It may be noted that Oracle allows INSTEAD OF triggersto process only against views, not /tables.

Examples:The first trigger is invoked whenever there is an update operation on the emp table rows and if salary is changed. It records these changes in another table to know the changes made to the table.

Page 51: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

First create a table emplog for maintaining changesSQL> create table emplog(work varchar2(10),oempno number,osal number,nempnonumber,nsal number); Table created.

Now create a trigger.

SQL> ed tr1

CREATE OR REPLACE TRIGGER EMPT1BEFORE UPDATE ON EMP FOR EACH ROWWHEN (NEW.SAL <> OLD.SAL) BEGININSERT INTO EMPLOG VALUES ('UPDATED', :OLD.EMPNO,:OLD.SAL, :NEW.EMPNO,:NEW.SAL); END;

SQL> @ t r1 9 /

Trigger created.

Now do the any update operation on emp table on sal columnSQL> update emp set sal=sal+1 where empno=7839;1 row updated.

Now check the emplog table. It has that updated detailsSQL> select * from emplog;WORK OEMPNO OSAL NEMPNO NSAL---------- ---------- ---------- ---------- ---------- UPDATED 7839 5000 7839 5001

Example2:write a trigger to fire before the insert takes place.

SQL> CREATE TABLE PERSON (ID INT, NAME PRIMARY KEY(ID) );Table created.

VARCHAR(30), DOB DATE,

SQL> CREATE OR REPLACE2 TRIGGER PERSON_INSERT_BEFORE3 BEFORE4 INSERT5 ON PERSON6 FOR EACH ROW7 BEGIN8 DBMS_OUTPUT.PUT_LINE('BEFORE INSERT OF ' || :NEW.NAME);9 END;10 /Trigger created.

Page 52: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SQL> create table emp1 as select * from emp; Table created.

SQL> create table empl(work varchar2(15),empno integer,sal number); Table created.

SQL> create table empl1(work varchar2(15),oemp integer,osal number,nempno integer,nsal number);Table created.

SQL> CREATE OR REPLACE TRIGGER EMPT22 AFTER DELETE OR UPDATE OR INSERT ON EMP13 FOR EACH ROW4 BEGIN5 IF DELETING THEN6 INSERT INTO EMPL VALUES ('DELETED', :OLD.EMPNO, :OLD.SAL);7 ELSIF INSERTING THEN8 INSERT INTO EMPL VALUES (' ISERTED',:NEW.EMPNO,:NEW.SAL);9 ELSE10 INSERT INTO EMPL1 VALUES11 ('UPDATED',:OLD.EMPNO,:OLD.SAL,:NEW.EMPNO,:NEW.SAL);12 END IF;13 END;14 /Trigger created.

SQL> INSERT INTO EMP1 VALUES(1237, 'phani', 'officer', 7782,sysdate, 1300, N ULL, 10);1 row created.

SQL> select * from empL;WORK EMPNO SAL--------------- ---------- ---------- ISERTED 1237 1300

SQL> Delete Emp1 Where Empno=1237;1 row deleted.

SQL> SELECT * FROM EMPL;WORK EMPNO SAL--------------- ---------- ----------ISERTED 1237 1300DELETED 1237 1300

SQL> INSERT INTO EMP1 VALUES(1237, 'phani', 'officer', 7782,sysdate, 1300, NULL,10);1 row created.

SQL> update emp1 set sal=sal+2000 where empno=1237;1 row updated.

Page 53: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SQL> SELECT * FROM EMPL1;WORK OEMP OSAL NEMPNO NSAL--------------- ---------- ---------- ---------- ---------- UPDATED 1237 1300 1237 3300

SQL> SELECT * FROM EMPL;WORK EMPNO SAL--------------- ---------- ----------ISERTED 1237 1300DELETED 1237 1300ISERTED 1237 1300

SQL ViewsA VIEW is a virtual table, through which a selective portion of the data from one or

more tables can be seen. Views do not contain data of their own. They are used to restrict access to the database or to hide data complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original table upon which the view is based.

Can you update the data in a view?A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the view. So, yes, you can update the data in a view providing you have the proper privileges to the underlying tables.

Does the view exist if the table is dropped from the database: in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors. If you recreate the table (that you had dropped), the view will again be fine.

THE SYNTAX TO CREATE A SQL VIEW ISCREATE VIEW view_nameASSELECT columnlistFROM tablename [WHERE condition];

In SQL view is said to be updatable (i.e. insert, update or delete) i f the following conditions are all satisfied.

The from clause has only one relation. The select clause contains only attributes of the relation and does not have any

expressions, aggregate functions, or distinct specification. Any attribute not in the select clause can be s et to null.

Another point we can note is that if we insert a row which does not satisfy condition in the where clause of create view then it is allowed and that row doesn't appear in the view. To avoid such insertions we have to use with check option in the create view.

SQL> create view empv as select * from emp; View created.

SQL> create view empview(no,nam,work,sal) as select empno,ename,job,sal from emp ;

Page 54: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

View created.

Page 55: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

SQL> SELECT * FROM EMPVIEW;

NO NAM WORK SAL---------- ---------- --------- ----------

7369 SMITH CLERK 8007499 ALLEN SALESMAN 16007521 WARD SALESMAN 12507566 JONES MANAGER 29757654 MARTIN SALESMAN 12507698 BLAKE MANAGER 28507782 CLARK MANAGER 24507788 SCOTT ANALYST 30007839 KING PRESIDENT 50007844 TURNER SALESMAN 15007876 ADAMS CLERK 11007900 JAMES CLERK 9507902 FORD ANALYST 30007934 MILLER CLERK 13001237 phani officer 1300

15 rows selected.SQL> update empview set sal=sal+1 where no=7363;0 rows updated.SQL> update empv set sal=sal+1 where empno=7363;0 rows updated.SQL> INSERT INTO EMPV VALUES(1237, 'phani', 'officer', 7782,sysdate, 1300, N ULL, 10);1 row created.

SEQUENCE:Sequence is a database object that generates number in sequential order

When will it used Application most often use these numbers when they require a unique value in a table

such as primary key values. Some database management system use an „auto number‟ concept or auto increment

setting on numeric column types

Syntax:Create sequence <s-name>Start with <integer> Maxvalue<integer> Incremented by <integer>;

It has two return valuesNEXTVAL:- Return the next value from the sequenceCURRVAL:- returns the value from the last call to nextvalue by the current user during the current connection

Page 56: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER

Example:SQL> ed sqCREATE SEQUENCE sample_sequenceSTART WITH 0MAXVALUE 20INCREMENT BY 5

SQL> @sqSequence created.SQL> create table sequl(id int,name varchar2(21)); Table created.SQL> insert into sequl(id,name) values(sample_sequence.nextval,'phani');1 row created.SQL> insert into sequl(id,name) values(sample_sequence.nextval,'&phani'); Enter value for phani: nnold 1: insert into sequl(id,name) values(sample_sequence.nextval,'&phani')new 1: insert into sequl(id,name) values(sample_sequence.nextval,'nn')

1 row created. SQL> /Enter value for phani: theirjiold 1: insert into sequl(id,name) values(sample_sequence.nextval,'&phani')new 1: insert into sequl(id,name) values(sample_sequence.nextval,'theirji')1 row created.

SQL> SELECT * FROM SEQUL;

ID NAME---------- ---------------------

1 phani6 nn11 theirji

RESULT:The creation of triggers and views and sequences are executed successfully and output

verified.

Page 57: bphanikrishna.files.wordpress.com · Web viewDisplay all the employees’ names SQL> SELECT ENAME FROM EMP; ENAME----- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER