0% found this document useful (0 votes)
5 views

Types of Data

Uploaded by

jimpakchimpak007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Types of Data

Uploaded by

jimpakchimpak007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 121

Types of Data

==============

We have two types of data.

1) Unstructured Data

2) Structured Data

1) Unstructured Data

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

A data which is not in readable format such type of data is called unstructured.

In general, meaningless data is called unstructured data.

ex:

201 Lakemba SYD NSW AUS

2) Structured Data

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

A data which is in readable format such type of data is called structured data.

In general, meaning full data is called structured data.

ex:

unitno locality city state country

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

201 Lakemba SYD NSW AUS

Oracle

========

Oracle is one of the database which is used to store structured data.

Oracle is a product of Oracle Corporation.

Oracle is classified into two types.

Oracle

|-------------------------------------------------|

SQL PL/SQL

(Structured Query Language) (Procedural / Structured Query Language)

Client/Server Architecture

==========================

Diagram: oracle1.1
In Client-Server architecture we need to see , how our data will store from frontend to backend.

Frontend
-------------------

The one which is visible to the enduser to perform some operations is called frontend.

ex:

Java, .Net, Python, Perl and etc.

Communication Channel

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

Communication channel acts like a bridge between frontend and backend.

ex:

JDBC - Java Database Connectivity

PDBC - Python Database Connectivity

ODBC - Open Database Connectivity

BackEnd

-------

The one which is not visible to the enduser but it performs operations based on the instructions given by frontend is
called backend.

ex:

Oracle, MySQL, SQL Server , MongoDB, DB2 , Sybase, Teradata, NoSQL and etc.

Management System
=============================

It is a software which is used to manage the database.

Using management system we can perform following acitivities very easily.

1) Adding the new data

2) Modifying the existing data


3) Deleting the unnecessary data

4) Selecting the required data.

DBMS
========

A database along with software which is used to manage the database is called database management system.

RDBMS
=========

If database is created based on relational theories is called relational database management system.

ex:

Oracle

MySQL

SQL Server

PostgreSQL

Teradata

Sybase

and etc.

Q)What is the difference between DBMS and RDBMS database?

DBMS RDBMS

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

DBMS stands Database Management RDBMS stands for Relational Database

System Management System.

It stores the data in the form of files. It stores the data in the form of tables.

It is designed to handle small amount of data. It is designed to handle large amount of data.

It provides support for a single user It provides support for multiple users at a time.

at a time.

Normalization is not possible for DBMS. Normalization is possible for RDBMS.

No security of data. High security of data.

SQL
=====

SQL stands for Structured Query Language which is pronounce as SEQUEL.

This language is used to interact with oracle database.

It is a case insensitive language.


It is a command based language.

Every command must starts with verbs.

ex:

select, update, delete, merge and etc.

Every command must ends with semicolon.

It is developed by Mr.Codd in 1972 (By IBM).

Sub languages of SQL


====================

We have five types of sub languages of SQL.

1) DDL (Data Definition Language)

2) DML (Data Manipulation Language)

3) DRL/DQL (Data Retrive/Query Language)

4) DCL (Data Control Language)

5) TCL (Transaction Control Language)

1) DDL (Data Definition Language)

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

It is used to maintain the objects in database.

It is a collection of five commands.

ex:

create, alter, drop , truncate and rename

2) DML (Data Manipulation Language)

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

It is used to mainpulate the data present in database.

It is a collection of four commands.

ex:

insert, update, delete and merge

3) DRL/DQL (Data Retrive/Query Language)

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

It is used to retrieve the data present in database.

It is a collection of one command.

ex:
select

4) DCL (Data Control Language)

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

This language which is used to control the access of data.

It is a collection of two commands.

ex:

grant and revoke

5) TCL (Transaction Control Language)

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

This language is used to maintain the transaction of database.

It is a collection of three commands.

ex:

commit, rollback and savepoint

Table
=======

A table is an object that is used to represent the data.

A table is used to store the data in the form of rows and columns.

A data which is stored inside the table is a case sensitive.

ex:

No Name Add

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

101 | Alan | Florida

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

102 | Jose | Texas

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

103 | Ana | Vegas

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

Oracle

========

Version : 21c

Vendor : Oracle Corporation

Software : Express Edition

Website :www.oracle.com/in/oracle
Port No : 1521

username : system (default)

password : admin

Download link :

https://drive.google.com/file/d/1tBx4vH14_cF9XClgnOF6L_1kdODbHSM5/view?usp=drive_link

Establish the connection with database software

================================================

To perform any operation in a database we need to establish the connection.

Once work with database is completed we need to close the connection.

1)

SQL> connect

username : system

password : admin

SQL> disconnect

2)

SQL> conn

username : system

password : admin

SQL> disc

3)

SQL> conn system/admin

SQL> disc

create command
===================

It is used to create table in a database.

syntax:

-----

create table <table_name>(col1 datatype(size1),col2 datatype(size),......,

colN datatype(size));

ex:

create table student(sno number(3),sname varchar2(10),sadd varchar2(12));


create table dept(deptno number(3),dname varchar2(10),dloc varchar2(12));

create table emp(eid number(3),ename varchar2(10),esal number(10,2),

deptno number(3),job varchar2(14),comm number(6));

describe command

=================

It wil display the structure of the table.

syntax:

desc <table_name>;

ex:

desc student;

desc emp;

desc dept;

insert command

==============

It is used to insert the row/record in a database table.

syntax:

-----

insert into <table_name> values(val1,val2,....,valN);

ex:

insert into student values(101,'raja','hyd');

insert into student values('ravi',102,'delhi'); // invalid

insert into student values(102,'ravi'); //invalid


A null is a operator which represent undefined or unavailable.

insert into student values(102,'ravi',null);

approach2

---------

insert into student(sno,sname,sadd) values(103,'ramana','vizag');

insert into student(sno,sname) values(104,'ramulu');

approach3

---------

Using '&' symbol we can read dynamic values.

insert into student values(&sno,'&sname','&sadd');

commit command

==============

It is used to make the changes permanent to database.

syntax:

commit;

dept table

=========

create table dept(deptno number(3),dname varchar2(10),dloc varchar2(12));

insert into dept values(10,'ECE','HYD');

insert into dept values(20,'EEE','DELHI');

insert into dept values(30,'CSE','PUNE');

insert into dept values(40,'MEC','VIZAG');

commit;
emp table

==========

create table emp(eid number(3),ename varchar2(10),esal number(10,2),

deptno number(3),job varchar2(14),comm number(6));

insert into emp values(201,'Alan',9000,10,'Clerk',null);

insert into emp values(202,'Jose',19000,10,'Clerk',500);

insert into emp values(203,'Kelvin',49000,20,'HR',500);

insert into emp values(204,'Linda',23000,20,'HR',900);

insert into emp values(205,'Nancy',31000,30,'Manager',400);

insert into emp values(206,'Erick',29000,30,'Manager',900);

commit;

select command

===============

It is used to select the records/rows from database table.

syntax:

-------

select * from <table_name>

Here '*' means all rows and columns.

ex:

select * from emp;

select * from dept;

select * from student;

Projection

----------

Selecting specific columns from database table is called projection.


ex:

select sno,sname,sadd from student;

select sno,sname from student;

select dloc from dept;

In select command we can perform arithmetic operations also.

ex:

select sno+100,sname,sadd from student;

select sno-100,sname,sadd from student;

Column Alias

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

A userdefined heading given to a column is called column alias.

Column alias can be applied to any column.

Column alias is temperory.Once the query is executed we will loss the column alias.

ex:

select sno as ROLL_NO,

sname as NAME,

sadd as CITY

from student;

select sno+100 as SNO,sname,sadd from student;

select sno-100 as SNO,sname,sadd from student;

Interview Queries
=================

Q) Write a query to display employee details from employee table?

select * from emp;

Q) Write a query to display employee id , employee name and employee salary from employee table?

select eid,ename,esal from emp;

Q) Write a query to display list of tables present in database?

select * from tab;

Q) Write a query to display list of users present in database?

select username from all_users;

Q) Write a query to see display logical database name?

select * from global_name; //XE

Q) Write a query to display employee id ,employee name, employee salary and

annual salary as ANNUAL_SAL from employee table?

select eid,ename,esal,esal*12 from emp;


Q) Write a query to display employee id ,employee name, employee salary and annual salary

from employee table?

select eid,ename,esal,esal*12 as ANNUAL_SAL from emp;

where clause

============

It is used to select specific records from database table.

ex:

select * from <table_name> where condition;

ex:

select * from student where sno=101;

select * from student where sname='ramana';

select * from student where sadd='pune';

Interview Queries

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

Q) Write a query to display employees information those who are working in 10 department?

select * from emp where deptno=10;

Q) Write a query to display employees information those who are working as a Manager?

select * from emp where job='Manager';

Q) Write a query to display employees information whose salary is greater then 30000?

select * from emp where esal>30000;


Q) Write a query to display student information whose is living in hyderabad?

select * from student where sadd='hyd';

Q) Write a query to display employees information whose commission is null?

select * from emp where comm is null;

update command

==============

It is used to update the records which are present in database table.

syntax:

------

update <table_name> set <col_name>=value where condition;

ex:

update student set sname='rani' where sno=101;

update student set sname='jojo',sadd='delhi' where sno=105;

update student set sadd='pune' where sname='ravi';

Note:

----

If we won't use where clause then all rows will be updated.

ex:

update student set sname='raja';


update student set sno=101;

update student set sadd='hyd';

Delete command

============

It is used to delete records from database table.

syntax:

-------

delete from <table_name> where condition;

ex:

delete from student where sno=105;

delete from student where sname='raja';

delete from student where sadd is null;

Note:

-----

If we won't use where clause then all rows will be deleted.

ex:

delete from student;

delete from emp;

delete from dept;

Q) Write a query to terminate employee whose commission is null?

delete from emp where comm is null;

Q) Write a query to promote employees from Clerk to Salesman?


update emp set job='Salesman' where job='Clerk';

Logical Operators

==================

We have three types of logical operators.

1) AND

2) OR

3) NOT

1) AND

---------

It will return the records if all conditions are true.

In logical AND operator, all conditions must be from same row.

ex:

select * from emp where eid=201 AND ename='Alan';

select * from emp where eid=201 AND ename='Lisa'; // no rows selected

select * from emp where eid=201 AND ename='Kelvin'; // no rows selected

2) OR

-----

It will return the records if condition is true.

In logical OR operator , condition can be from any row.


ex:

select * from emp where eid=201 OR ename='Alan';

select * from emp where eid=201 OR ename='Lisa';

select * from emp where eid=201 OR ename='Kelvin';

3) NOT

-------

It will return the records except the condition.

A <> symbol denoted as not operator.

ex:

select * from emp where NOT eid=201;

select * from emp where eid<>201;

select * from emp where NOT ename='Alan';

select * from emp where ename<>'Alan';

Interview Queries

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

Q) Write a query to display employees information whose employee id is 201,202,203?

select * from emp where eid=201 OR eid=202 OR eid=203;

Q) Write a query to display employees information whose salary is greater then equals to 30000 and less then equals
to 50000?

select * from emp where esal>=30000 AND esal<=50000;


Q) Write a query to display employees information those who are not working in 10 department?

select * from emp where deptno<>10;

Between operator

=================

Between operator will return the records those who are in the range of values.

In between operator , first we need to write lower limit then higher limit.

Between operator takes the support of AND operator.

ex:

select * from emp where eid between 201 AND 206;

select * from emp where deptno between 10 AND 30;

select * from emp where esal between 30000 AND 50000;

IN operator

===========

IN operator is a replacement of OR operator.

It will return the records those who are matching in the list of values.

ex:

select * from emp where eid IN(201,202,203);


select * from emp where deptno IN(10,20,30,40);

select * from emp where ename IN('Alan','Kelvin','Lisa');

Pattern Matching operators

============================

Pattern matching operatores are used to select the letters from database table.

Pattern matching operators take the support of like keyword.

We have two types of pattern matching operators.

1) Percentage(%)

2) Underscore(_)

1) Percentage(%)

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

Q) Write a query to display employee information whose employee name starts with 'A' letter?

select * from emp where ename like 'A%';

Q) Write a query to display employee information whose employee name ends with 'n' letter?

select * from emp where ename like '%n';

Q) Write a query to display employee information whose employee name middle letter as 'l'?

select * from emp where ename like '%l%';

2) Underscore (_)

=================
Q) Write a query to display employee information whose employee name second letter is 'l'?

select * from emp where ename like '_l%';

Q) Write a query to display employee information whose employee name having second last

letter is 'c'?

select * from emp where ename like '%c_';

Q) Write a query to display employee information whose employee name having third letter as 'n'?

select * from emp where ename like '__n%';

DDL commands

============

1) create (tables)

2) alter (columns)

3) drop (tables)

4) truncate (rows/records )

5) rename (tables)

2) alter command

=================

Using alter command we can perform following activities very easily.

i) Add the new columns

ii) Modifying the existing columns


iii) drop the columns

iv) Renaming the columns

i) Add the new columns

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

Using alter command we can add new columns in a database table.

syntax:

------

alter table <table_name> ADD (col1 datatype(size),col2 datatype(size)

,...,colN datatype(size));

ex:

---

alter table student ADD (state varchar2(10),pincode number(8));

update student set state='Telangana' where sno=101;

ii) Modifying the existing columns

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

Using alter command we can modify the columns.

We can increase and decrease the size of column only when existing values are fit into new size.

We can change datatype of a column only when that column is empty.

syntax:

------

alter table <table_name> modify (col datatype(size));


ex:

desc student;

alter table student modify (state varchar2(15));

desc student;

alter table student modify (pincode varchar2(8));

desc student;

iii) drop the columns

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

Using alter command we can drop the columns.

syntax:

------

alter table <table_name> drop (col1,col2,...,colN);

ex:

alter table student drop (pincode,state);

iv) Renaming the columns

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

Using alter command we can rename the column names.

syntax:

-------

alter table <table_name> rename column <old_name> to <new_name>;

ex:
alter table student rename column sadd to city;

alter table emp rename column salary to dailywages;

alter table emp rename column job to designation;

3) drop command

=================

A drop command is used to drop the table from database.

syntax:

drop table <table_name>;

ex:

drop table emp;

drop table student;

drop table dept;

4) truncate command

====================

A truncate command is used to delete the rows permanently.

syntax:

-----

truncate table <table_name>;

ex:

truncate table student;

truncate table dept;

truncate table emp;

Q) What is the difference between delete and truncate command?


delete truncate

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

It is a DML command. It is a DDL command.

It deletes the records temperory. It deletes the records permanently.

We can rollback the data. We can't rollback the data.

Where clause can be used. Where clause can't be use.

5) rename command

=================

It is used to rename the table name.

syntax:

-----

rename <old_name> to <new_name>;

ex:

rename student to students;

rename dept to department;

rename emp to employees;

Duplicate table or Copy of a table

====================================

Using create and select command we can create duplicate or copy of a table.

ex:

create table stud as select * from student;

create table stud as select * from emp;

create table stud as select eid,ename,esal from emp;

create table stud as select * from emp where deptno=10;


create table stud as select * from emp where eid IN(201,202,203);

create table stud as select * from emp where esal is null;

create table stud as select * from emp where esal>=30000 AND esal<=50000;

create table stud as select * from emp where ename like 'A%';

cl scr

======

It is used to clear the output screen of SQL command prompt.

ex:

cl scr

What is dual table

==================

A dual table is a dummy table which contains one row and one column.

It is used to perform arithmetic operations and to see the current system date.

ex:

select 10+20 from dual;

select 10*3 from dual;

select sysdate from dual;

select current_date from dual;

Functions

=========

Functions are used to manipulate the data items and gives the result.

We have two types of functions.


1) Group functions / Multiple row functions

2) Scalar functions / Single Row functions

1) Group functions

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

Group functions are applicable for multiple rows.

We have following list of group functions.

ex:

sum(), avg(), max(), min(),count(*) and count(expression).

Q) Write a query to display sum of salary of each employee?

select sum(esal) from emp;

Q) Write a query to display average salary of each employee?

select avg(esal) from emp;

Q) Write a query to display highest salary from emp table?

select max(esal) from emp;

Q) Write a query to display least salary from emp table?

select min(esal) from emp;

Q) Write a query to display number of records present in a database table?


select count(*) from emp;

Q) What is the difference between count(*) and count(expression)?

count(*)

--------

It will return number of records present in database table.

It will include null records.

ex:

select count(*) from emp;

count(expression)

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

It will return number of values present in databaset table column.

It will not include null values.

ex:

select count(eid) from emp;

select count(comm) from emp;

userlist table

==============

drop table userlist;

create table userlist(uname varchar2(10), pwd varchar2(10));

insert into userlist values('raja','rani');

insert into userlist values('king','kingdom');


commit;

Q) Write a query to check username and password is valid or not?

select count(*) from userlist where uname='raja' AND pwd='rani';//1

select count(*) from userlist where uname='raja' AND pwd='rani2';//0

2) Scalar Functions / Single Row Functions

==========================================

We have following list of scalar functions.

i) Character functions

ii) Number functions

iii) Date functions

iv) Conversion functions

i) Character functions

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

We have following list of character functions.

upper()

-------

It is used to convert lowercase to uppercase.

ex:

select upper('oracle training') from dual;


lower()

---------

It is used to convert uppercase to lowercase.

ex:

select lower('ORACLE TRAINING') from dual;

initcap()

---------

It is used to display the text with initial letter capital.

ex:

select initcap('oracle training') from dual;'

lpad()

-------

It is used to pad the characters left side.

ex:

select lpad('oracle',10,'z') from dual; //zzzzoracle

rpad()

------

It is used to pad the characters right side.

ex:

select rpad('oracle',10,'z') from dual; //oraclezzzz

ltrim()

--------

It is used trim the characters from left side.

ex:

select ltrim('zzoraclezz','z') from dual;//oraclezz

rtrim()

-------

It is used trim the characters from right side.


ex:

select rtrim('zzoraclezz','z') from dual;//zzoracle

trim()

-------

It is used to trim the characters from both the sides.

ex:

select trim('z' from 'zzoraclezz') from dual;

concat()

--------

It is used to concatinate two strings.

ex:

select concat('mega','star') from dual;

select concat(concat('mega','star'),'chiru') from dual;

ii) Number functions

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

We have following list of number functions.

abs()

-----

It always return absoluate value.

ex:

select abs(-10.89) from dual; // 10.89

select abs(-7) from dual; // 7

sqrt()

------

It will return exact square root.

ex:

select sqrt(25) from dual; //5


select sqrt(36) from dual; //6

select sqrt(37) from dual; //6.08

power(A,B)

----------

It will return power value.

ex:

select power(5,3) from dual; //125

ceil()

------

It will return ceil value.

ex:

select ceil(10.2) from dual; // 11

select ceil(11.7) from dual; // 12

floor()

--------

It will return floor value.

ex:

select floor(10.9) from dual; //10

select floor(11.2) from dual; //11

round()

--------

It will return nearest value.

ex:

select round(10.7) from dual; // 11

select round(10.5) from dual; // 11

select round(10.4) from dual; // 10

trunc()

-------

It will remove the decimals.


ex:

select trunc(10.56) from dual; //10

select trunc(67.45) from dual; // 67

greatest()

----------

It will return greatest value.

ex:

select greatest(101,102,103) from dual;

least()

--------

It will return least value.

ex:

select least(101,102,103) from dual;

Working with Date values

=========================

Every database supports to insert date values.

Each database having different date patterns.

ex:

oracle --> dd-MMM-yy

Mysql --> yyyy-MM-dd

ex:

---

drop table emp1;

create table emp1(eid number(3),ename varchar2(10),edoj date);


insert into emp1 values(201,'Alan','01-JAN-24');

insert into emp1 values(202,'Jack',sysdate);

insert into emp1 values(203,'Brook',current_date);

commit;

iii) Date functions

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

We have following list of date functions.

ADD_MONTHS()

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

It is used to add the months in a given date.

ex:

select ADD_MONTHS('01-JAN-24',9) from dual;

select ADD_MONTHS(sysdate,3) from dual;

MONTHS_BETWEEN()

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

It will return number of months between two dates.

ex:

select MONTHS_BETWEEN('01-JAN-24','01-JUL-24') from dual;

select ABS(MONTHS_BETWEEN('01-JAN-24','01-JUL-24')) from dual;

select ABS(MONTHS_BETWEEN('01-JAN-24','15-JUL-24')) from dual;


NEXT_DAY()

--------

It will return next date of a given day in a week.

ex:

select NEXT_DAY(sysdate,'SUNDAY') from dual;

select NEXT_DAY('26-JUL-24','FRIDAY') from dual;

LAST_DAY()

---------

It will return last date of a month.

ex:

select LAST_DAY('23-FEB-24') from dual;

select LAST_DAY(sysdate) from dual;

iv) Conversion functions

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

A process of converting from one type to another type is called conversion function.

ex:

TO_CHAR()

We have two pseudos for TO_CHAR() function.

1) Number TO_CHAR()

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

It supports '9' in digits , dollar and euros symbol.

ex:

select eid,ename,esal from emp;

select eid,ename,TO_CHAR(esal,'9,999') from emp;

select eid,ename,TO_CHAR(esal,'99,999') from emp;

select eid,ename,TO_CHAR(esal,'$99,999') from emp;

2) Date TO_CHAR()
-----------------

select sysdate from dual;

select TO_CHAR(sysdate,'dd-MM-yyyy') from dual;

select TO_CHAR(sysdate,'yyyy-MM-dd') from dual;

select TO_CHAR(sysdate,'year') from dual;

select TO_CHAR(sysdate,'MONTH') from dual;

select TO_CHAR(sysdate,'DAY') from dual;

select TO_CHAR(sysdate,'yyyy') from dual;

select TO_CHAR(sysdate,'MON') from dual;

select TO_CHAR(sysdate,'dd') from dual;

select TO_CHAR(sysdate,'HH:MI:SS') from dual;

select TO_CHAR(sysdate,'dd-MM-yyyy HH:MI:SS') from dual;

Group by clause

================

It is used to divide the rows into groups so that we can apply group functions.

A column which we used in select clause then same column name we should use in group by clause.

ex:

Q) Write a query to display sum of salary of each department?

select sum(esal),deptno from emp group by deptno;

Q) Write a query to display average of each job?

select avg(esal),job from emp group by job;

Q) Write a query to display employee maximum salary of each department?


select max(esal),deptno from emp group by deptno;

Q) Write a query to display minimum salary of each job?

select min(esal),job from emp group by job;

Q) Write a query to display number of employees working in each department?

select count(*),deptno from emp group by deptno;

Having clause

==============

It is used to filter the rows from group by clause.

Having clause must placed after group by clause.

ex:

Q) Write a query to display sum of salary of each department whose sum of salary is

greater then 30000?

select sum(esal),deptno from emp group by deptno having sum(esal)>30000;

Q) Write a query to display maximum salary of each job whose maximum salary is

greater then 20000?

select max(esal),job from emp group by job having max(esal)>20000;


Order by clause

================

It is used to arrange the rows in a table.

By default it will arrange in ascending order.

ex:

select * from emp order by eid;

select * from emp order by ename;

select * from emp order by eid desc;

select * from emp order by ename desc;s

Note:

-----

where clause, group by clause, having clause and order by clause.

select sum(esal),deptno from emp where deptno<>10

group by deptno

having ssum(esal)>50000

order by deptno;

Integrity Constraints

======================

Constraints are the rules which are applied on the tables.

Using constraints we can achieve accuracy and quality of data.

We have five types of constraints.

1) NOT NULL

2) UNIQUE

3) PRIMARY KEY

4) FOREIGN KEY
5) CHECK

Constraints are created at two levels.

i) Table level

ii) Column level

1) NOT NULL

-----------

NOT NULL constraint does not accept null values.

NOT NULL will accept duplicate values.

NOT NULL constraint can be created only at column level.

column level

-----------

drop table student;

create table student(sno number(3) NOT NULL,sname varchar2(10),sadd varchar2(12));

insert into student values(101,'raja','hyd');

insert into student values(101,'ravi','delhi');

insert into student values(null,'ravi','delhi'); //invalid

commit;

Note:

----
NOT NULL constraint can be applied to multiple columns.

ex:

drop table student;

create table student(sno number(3) NOT NULL,

sname varchar2(10) NOT NULL,

sadd varchar2(12) NOT NULL);

insert into student values(101,'raja','hyd');

insert into student values(null,'ravi','delhi'); //invalid

insert into student values(102,null,'delhi'); //invalid

insert into student values(102,'ravi',null); //invalid

commit;

2) UNIQUE

----------

UNIQUE constraint does not accept duplicate values.

UNIQUE constraint can accept null values.

UNIQUE constraint can be created at column level and table level.

column level

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

drop table student;

create table student(sno number(3) UNIQUE,sname varchar2(10),sadd varchar2(12));


insert into student values(101,'raja','hyd');

insert into student values(null,'ravi','delhi');

insert into student values(101,'ramana','vizag'); // invalid

commit;

table level

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

drop table student;

create table student(sno number(3) ,sname varchar2(10),sadd varchar2(12),UNIQUE(sno));

insert into student values(101,'raja','hyd');

insert into student values(null,'ravi','delhi');

insert into student values(101,'ramana','vizag'); // invalid

commit;

Note:

-----

UNIQUE constraint can be created for multiple columns.

ex:

drop table student;

create table student(sno number(3) UNIQUE,

sname varchar2(10) UNIQUE,

sadd varchar2(12) UNIQUE);


insert into student values(101,'raja','hyd');

insert into student values(101,'ravi','delhi');//invalid

insert into student values(102,'raja','delhi'); //invalid

insert into student values(103,'ramana','hyd'); //invalid

3) Primary Key

===============

Primary key is a combination of NOT NULL and UNIQUE constraint.

Primary key does not accept null values and duplicate values.

A table can have only one primary key.

Primary key can be created at column level and table level.

column level

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

drop table student;

create table student(sno number(3) primary key,sname varchar2(10),sadd varchar2(12));

insert into student values(101,'raja','hyd');

insert into student values(101,'ravi','delhi'); // invalid

insert into student values(null,'ravi','delhi'); // invalid

commit;
table level

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

drop table student;

create table student(sno number(3) ,sname varchar2(10),sadd varchar2(12),primary key(sno));

insert into student values(101,'raja','hyd');

insert into student values(101,'ravi','delhi'); // invalid

insert into student values(null,'ravi','delhi'); // invalid

commit;

4) Foreign key or Referential Integrity constraint

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

Foreign key is used to establish the relationship between two tables.

This relationship is called parent and child relationship or master and detailed relationship.

To establish the relationship , a parent table must have primary key or unique key and child table must have foreign
key.

Foreign key will accept only those values which are present in primary key.

Foreign key can have duplicates and null values.

A primary key column name and foreign key column name may or may not match but datatype must match.

Diagram: oracle6.1

parent table
------------

drop table college;

create table college(sno number(3) primary key,

sname varchar2(10),

sadd varchar2(12));

insert into college values(101,'raja','hyd');

insert into college values(102,'ravi','delhi');

insert into college values(103,'ramana','vizag');

commit;

child table

----------

drop table library;

create table library (roll_no number(3) REFERENCES college(sno),

book_name varchar2(12));

insert into library values(101,'java');

insert into library values(102,'oracle');

insert into library values(103,'HTML');

insert into library values(103,'python');

insert into library values(null,'CSS');

insert into library values(104,'JS'); //invalid

commit;
How to drop the tables

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

In order to drop the tables. First we need to delete child table then parent table.

ex:

drop table library;

drop table college;

5) CHECK

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

It is used to describe domain of a column.

A domain means what type of values a column must accept.

It can be created at column level and table level.

column level

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

drop table student;

create table student(sno number(3),sname varchar2(10),

smarks number(3) check(smarks<=100));

insert into student values(101,'raja',98);

insert into student values(102,'ravi',120); //invalid

insert into student values(103,'ramana',999); //invalid

commit;

ex:

----
drop table student;

create table student(sno number(3),

sname varchar2(10) CHECK(sname=lower(sname)),

sadd varchar2(12));

insert into student values(101,'raja','hyd');

insert into student values(102,'RAVI','delhi'); //invalid

insert into student values(103,'RaMaNa','vizag'); //invalid

commit;

ex:

----

drop table student;

create table student(sno number(3),

sname varchar2(10) CHECK(sname=upper(sname)),

sadd varchar2(12));

insert into student values(101,'RAJA','hyd');

insert into student values(102,'ravi','delhi'); //invalid

insert into student values(103,'RaMaNa','vizag'); //invalid

commit;

table level

-----------
ex:

----

drop table student;

create table student(sno number(3),

sname varchar2(10) ,

sadd varchar2(12), CHECK(sname=upper(sname)));

insert into student values(101,'RAJA','hyd');

insert into student values(102,'ravi','delhi'); //invalid

insert into student values(103,'RaMaNa','vizag'); //invalid

commit;

Q) How can we add the constraint to the existing table?

alter table emp add primary key(eid);

Q) How to delete the constraint from table?

alter table emp drop primary key;

Assignment

----------

Customer table

custId

custName

custAddress
Item table

item_custId

itemId

itemName

itemPrice

Payment table

pay_custId

paymentId

paymentAmount

paymentMode

TCL commands

=============

We have three TCL commands.

1) commit

2) rollback

3) savepoint

1) commit

----------

It is used to make the changes permanent to database.

syntax:

------

commit;

ex:

drop table student;

create table student(sno number(3),sname varchar2(10),sadd varchar2(12));


insert into student values(101,'raja','hyd');

insert into student values(102,'ravi','delhi');

select * from student;// 2 records display

commit;

2) rollback

-----------

It is used to undo the changes which are not permanent.

syntax:

------

rollback;

ex:

---

drop table student;

create table student(sno number(3),sname varchar2(10),sadd varchar2(12));

insert into student values(101,'raja','hyd');

insert into student values(102,'ravi','delhi');

commit;

insert into student values(103,'Alan','Florida');

insert into student values(104,'Jose','Texas');

select * from student; // 4 records


rollback;

select * from student; // 2 records

3) savepoint

-----------

It is used mark logical transaction in a database.

Instead of complete rollback we can rollback upto savepoint.

syntax:

savepoint <save_pointe_name>;

ex:

drop table student;

create table student(sno number(3),sname varchar2(10),sadd varchar2(12));

insert into student values(101,'raja','hyd');

insert into student values(102,'ravi','delhi');

savepoint sp1;

insert into student values(103,'Alan','Florida');

insert into student values(104,'Jose','Texas');

savepoint sp2;

insert into student values(105,'Jacky','China');


insert into student values(106,'John','Japan');

select * from student; // 6 records

rollback to sp2;

select * from student; // 4 records

PSEUDO columns

===============

PSEUDO means a column which is not real.

We have two pseudo columns.

1) ROWNUM

2) ROWID

1) ROWNUM

--------

ROWNUM always start with 1 and increment by 1.

ROWNUM values are temperory.

Once the query is executed we will loss the rownum values.

ex:

select eid,ename,esal from emp;

select rownum,eid,ename,esal from emp;

select rownum,sno,sname,sadd from student;

2) ROWID
---------

ROWID is a hexadecimal number.

ROWID is permanent.

ROWID is a memory location where our records will store in a table.

ex:

select rowid,eid,ename,esal from emp;

select rowid,rownum,eid,ename,esal from emp;

Interview Queries

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

Q) Write a query to display first four records from emp table?

select * from emp where rownum<=4;

or

select * from emp where rownum<=4 order by rownum;

select * from emp where rownum<=4 order by rownum desc;

Q) Write a query to display fourth record from emp table?

select * from emp where rownum<=4

minus

select * from emp where rownum<=3;

DCL commands

============

We have two DCL commands.


1) grant

2) revoke

Schema :

-------

Schema is a memory location which is used to run SQL commands.

Privileges

---------

Permission given to a user is called privileges.

Rights given to a user is called privileges.

We have two types of privileges.

1) System privilege

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

Permission given by DBA to user.

2) Object privilege

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

Permission given by one user to user.

grant

------

Grant command is used to grant the permissions.

syntax:

grant <privilege1>,<privilege2> to <user_name>;


revoke

-------

Revoke command is used to revoke the permissions.

syntax:

revoke <privilge1>,<privilege2> from <user_name>;

DBA> alter session set "_ORACLE_SCRIPT"=true;

DBA> create user hemanth identified by hemanth;

DBA> create user tejaswini identified by tejaswini;

DBA> grant all privileges to hemanth,tejaswini;

Hemanth> conn hemanth/hemanth --logon denied

Tejaswini> conn tejaswini/tejaswini --logon denied

DBA> grant connect,resource to hemanth,tejaswini;

Hemanth> conn hemanth/hemanth -- connected

Tejaswini> conn tejaswini/tejaswini -- connected

Hemanth>
create table employee(eid number(3),ename varchar2(10),esal number(10));

ALTER USER hemanth quota unlimited on employee;

insert into employee values(201,'Alan',10000);

insert into employee values(202,'Jose',20000);

insert into employee values(203,'Kelvin',30000);

commit;

select * from employee;

Tejaswini> select * from employee; // table or view does not exist

Hemanth> grant select on employee to tejaswini;

Tejaswini> select * from hemanth.employee;

Tejaswini> delete from hemanth.employee;

Tejaswini> commit;

Hemanth > select * from employee ; // no rows selected

Hemanth > revoke select on employee from tejaswini;

Hemanth> disc

Tejaswini> disc

DBA> revoke connect,resource from hemanth,tejaswini;

DBA> revoke all privileges from hemanth,tejaswini;

Sequences
===========

Sequence is an object which is used to generate the numbers.

Sequence starts with 1 and increment by 1.

syntax:

------

create sequence <sequence_name> start with <value> increment by <value>;

ex:

create sequence sq1 start with 1 increment by 1;

create sequence sq2 start with 10 increment by 10;

create sequence sq3 start with 101 increment by 1;

We have two pseudo in sequence.

1) NEXTVAL

---------

It will return next number in a sequence.

ex:

drop table student;

create sequence sq1 start with 101 increment by 1;

create table student(sno number(3),sname varchar2(10),sadd varchar2(12));

insert into student values(sq1.NEXTVAL,'raja','hyd');

insert into student values(sq1.NEXTVAL,'ravi','delhi');

insert into student values(sq1.NEXTVAL,'ramana','ramana');


commit;

2) CURRVAL

---------

It will return the last number generated by the sequence.

ex:

select sq1.CURRVAL from dual;

Q) Write a query to see the list of sequences present in database?

select sequence_name from user_sequences;

Q) Write a query to drop the sequence?

drop sequence sq1;

Synonym

===========

Alternate name given to a table is called synonym.

Using snonym length of the table will reduce.

We can use synonym instead of table name for all the commands.

syntax:

-----

create synonym <synonym_name> for <object_name>;

ex:

create synonym syn1 for emp;

create synonym syn2 for student;


create synonym syn3 for dept;

select * from syn1;

delete from syn1;

select * from emp; //no rows selected

rollback;

select * from emp; //6 records

select * from syn1;

Q) Write a query to display list of synonms present in database?

select synonym_name from user_synonyms;

Q) Write a query to drop the synonym?

drop synonym syn1;

Joins

=======

select * from dept; // 4 records

select * from emp; // 6 records

select * from emp,dept; // 6*4=24 records

select eid,ename,esal,deptno,dname,dloc from emp,dept; --column ambiguously defined


To overcome this limitation we need to declare table_name.column_name.

select emp.eid,emp.ename,dept.deptno,dept.dname,dept.dloc from emp,dept; // 6*4=24 records

Table alias

-----------

A userdefined name given to a table is called table alias.

Table alias is temperory.

Once the query is executed we will loss the table alias.

Using table alias length of the query will reduce mean while performance is maintained.

ex:

select e.eid,e.ename,e.esal,d.deptno,d.dname,d.dloc from emp e,dept d; // 6*4 = 24 records

Definition of joins

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

Joins is used to retrieve the data from one or more then one table.

We have following list of joins.

1) Equi join

2) Non-Equi join

3) Self join

4) Cartisian product
5) Inner join

6) Outer join

1) Equi join

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

When two tables are joined based on common column then we need to use equi join.

In equi join we will use join operator.

ex:

select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e,dept d

where(e.deptno=d.deptno); //6

2) Non-Equi join

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

When tables are not joined based on equi join operator is called non-equi join.

ex:

select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e,dept d

where e.esal>30000 and e.esal<50000; // 1 * 4 = 4 records

3) Self join

-----------

When table joined to itself is called self join.

In self join we need to create two table alias for same.

ex:

select e1.eid,e1.ename,e1.esal,e2.job,e2.comm from emp e1,emp e2


where(e1.deptno=e2.deptno); // 6 + 6 =12 records

4) Cartisian product

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

When two tables are joined without any condition is called cartisian product.

ex:

select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e,dept d;//6*4=24 records

5) Inner join

-----------

It is similar to equi join.

Inner join given by ANSI people.

ANSI stands for American National Standards Insitute.

ex:

select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e INNER JOIN dept d

ON(e.deptno=d.deptno); //6

select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e JOIN dept d

ON(e.deptno=d.deptno); //6

6) Outer join

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

It is a extension of equi join.

It will return matching as well as not matching records.

A '+' symbol denoted as outer join operator.

We have three types of outer join.


1) Left Outer join

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

SQL

---

select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from emp e,dept d

where(e.deptno=d.deptno(+));

ANSI

----

select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc

from emp e LEFT OUTER JOIN dept d

ON(e.deptno=d.deptno);

2) Right Outer join

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

SQL

---

select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc from emp e,dept d

where(e.deptno(+)=d.deptno);

ANSI

----

select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc

from emp e RIGHT OUTER JOIN dept d

ON(e.deptno=d.deptno);

3) Full Outer join

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

ANSI

-----

select e.eid,e.ename,e.esal,e.deptno,d.deptno,d.dname,d.dloc

from emp e FULL OUTER JOIN dept d

ON(e.deptno=d.deptno);
What is the difference between RDBMS and MongoDB database?

RDBMS MongoDB

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

It is a relational database. It is a non-relational or document based database.

It can’t stores the data in key and value pair. It stores the data in key and value pair.

Not suitable for hierarchical data storage. Suitable for hierarchical data storage.

It has a predefined(static) schema. It has a dynamic schema.

It contains tables. It contains Collections.

It is a row based. It is a document based.

It is a column based. It is a field based.

It is slower. It is faster.

It supports SQL query language. It supports JSON query language.

Assignment

===========

Input:

AABBBCCCCAABB

output:

A2B3C4A2B2

Indexes

==========

Index is an object which is used to improve the performance of select stmt.


Index in a database is same as index in a book.

We need to create index only to those columns which are widely used in a where clause.

Whenever we create index , two columns will be generated.One contains ROWID and another contains indexed
column. All the records will store in ascending order in indexed column.

index table

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

ROWID | INDEX-COLUMN

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

| 9000

| 17000

| 18000

| 19000

| 29000

| 34000

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

We have two types of indexes.

1)simple index

2)complex index

1)simple index

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

When index is created only for one column is called simple index.

syntax:

create index <index_name> on <table_name>(column_name);

ex:
create index idx1 on emp(eid);

select * from emp where eid=205;

Here index is used when we call "eid" in where condition.

2)complex index

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

When index is created for multiple columns is called complex index.

syntax:

create index <index_name> on <table_name>(column1,column2,..,columnN);

ex:

create index idx2 on emp(job,comm);

select * from emp where job='Clerk' and comm=100;

Here index is used when we call job and comm in where condition.

Views

=====

View is a virtual representation of a data from one or more then one table.

A table which is used to create a view is called base table or above table.

ex:

create view v1 as select * from emp;

View does not consumes the memory.

View does not have any data.


View will get the data from based table when we execute select command.

We have different types of views.

1) Simple view

2) Complex view

3) with read only view

4) with check option view

5) Materialized view

1) Simple view

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

If a view is created by using one base table is called simple view.

In simple view DML operations are allowed.

ex:

create view v1 as select * from emp;

select * from v1;

delete from v1;

select * from v1;

select * from emp;

rollback;
2) Complex view

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

If a view is created using more then one base table is called complex view.

In complex view DML operations are not allowed.

ex:

create view v2 as select e.eid,e.ename,e.esal,d.dname,d.dloc from emp e,dept d

where(e.deptno=d.deptno);

select * from v2;

delete from v2; // delete not possible

3) with read only view

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

If a view is created by using one base table and DML operation is not required then we need to use with read only
view.

ex:

create view v3 as select * from emp with read only;

select * from v3;

delete from v3;// cannot perform DML operation

4) with check option view

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

If a view is created by using one base table and DML operation is allowed only when condition is true.
ex:

create view v4 as select * from emp where deptno=30 with check option;

select * from v4;

insert into v4 values(207,'Lara',40000,50,'Salesman',500); //invalid

insert into v4 values(207,'Lara',40000,30,'Salesman',500);

select * from v4;

select * from emp;

5) Materialized view

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

Materialized view is also known as SNAPSHOT.

To create a materialized view a table must have primary key.

ex:

alter table emp add primary key(eid);

create materialized view v5 as select * from emp;

select * from v5; // 7 records

delete from emp where eid=207;

commit;

select * from emp; // 6 records

select * from v5; // 7 records

EXEC DBMS_SNAPSHOT.REFRESH('v5');
select * from emp; // 6 records

select * from v5; // 6 records

Q) Write a query to display list of views present in database?

select view_name from user_views;

Q) Write a quety to drop the view?

drop view v1;

drop view v2;

drop view v3;

drop view v4;

drop materialized view v5;

Sub Queries

==========

If we declare a query inside another query such concept is called sub query.

In subquery , first inner query will execute then outer query.

We have list of sub queries.

1) Single row subquery

2) Multiple row subquery

3) Multiple column subquery


1) Single row subquery

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

If a sub query returns only one row is called single row subquery.

Sub queries can be nested upto 32 levels.

ex:

SQL

-----

select * from emp where ename='Alan';

Sub Query

--------

select * from emp where ename=(select ename from emp where eid=201);

ex:

---

SQL

----

select * from emp where eid=201 AND ename='Alan';

Sub Query

-------

select * from emp where

eid=(select eid from emp where ename='Alan')

AND

ename=(select ename from emp where esal=9000);

Q) Write a query to display employee information whose salary is greater then Nelson?

select * from emp where esal > (select esal from emp where ename='Nelson');
Q) Write a query to display second highest salary from employee table?

select max(esal) from emp where esal<(select max(esal) from emp);

2) Multiple row subquery

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

If a sub query returns more then one row is called multiple row sub query.

To perform multiple row sub query we need to use multiple row operators.

1) ANY

2) ALL

3) IN

ex:

select * from emp where esal > ANY (select esal from emp where deptno=10);

select * from emp where esal < ANY (select esal from emp where deptno=10);

ex:

select * from emp where esal > ALL (select esal from emp where deptno=10);

select * from emp where esal < ALL (select esal from emp where deptno=10);

ex:

select * from emp where esal IN (select esal from emp where deptno=10);

3) Multiple column subquery

---------------------------
When subquery returns more then one column is called multiple column sub query.

In multiple column subquery we need to use IN operator.

ex:

select * from emp where(eid,ename,esal) IN (select eid,ename,esal from emp);

select eid,ename,esal from emp where(eid,ename,esal) IN (select eid,ename,esal from emp);

Merge Command

==============

Merge command is a combination of insert and upate command.

student10 table

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

create table student10(sno number(3),sname varchar2(10), sadd varchar2(12));

insert into student10 values(101,'raja','hyd');

insert into student10 values(102,'ravi','delhi');

insert into student10 values(103,'ramana','vizag');

commit;

student20 table

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

create table student20(sno number(3),sname varchar2(10), sadd varchar2(12));

insert into student20 values(103,'Alan','Texas');

insert into student20 values(104,'Jose','Florida');

commit;

ex:

merge into student10 s1

using student20 s2

ON(s1.sno=s2.sno)

when matched then

update set sname=s2.sname,sadd=s2.sadd

when not matched then


insert values(s2.sno,s2.sname,s2.sadd);

select * from student10; // 2 records merge

select * from student20;

Q) What is the difference between Normalization and Denormalization?

Normalization Denormalization

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

It is a process of dividing big table It is a process of creating big table from

into small tables. small tables.

It is increases the complexity because of It will reduce complexity because of single table.

multiple tales.

No redundent data. Redundent data.

Need of joins. No need of joins.

Slower reads. Slower writes.

No waste of memory. Waste of memory.

PL/SQL

=======

PL/SQL stands for Procedural Language extensions to Structured Query Language.

PL/SQL is a extension of SQL and contains following features.

1) We can achieve programming features like control statements, loops and etc.
2) It reduces network traffic.

3) We can display custom error messages by using the concept of exception handling.

4) We can perform related operations by using concept of triggers.

PL/SQL Block

=============

PL/SQL block is also known as PL/SQL program.

ex:

DECLARE

- // Declaration Section

BEGIN

- // Executale Section

EXCEPTION

- // Exception Section

END;

Declaration Section

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

It is used to declare variables, exceptions, cursors and etc.

It is a optional section.
Executable Section

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

It is used to declare actual code of a PL/SQL block.

It is a mandatory section.

Exception Section

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

It contains lines of code which is executed when exception is raised.

It is a optional section.

To see the output in PL/SQL we need to set serveroutput on?

ex:

SQL> set serveroutput on

Q) Write a PL/SQL program to display Hello World?

BEGIN

DBMS_OUTPUT.PUT_LINE('Hello World');

END;

Here DBMS_OUTPUT is a package name.

Here PUT_LINE is a procedure name.

'/' is used to submit the PL/SQL program into database.

Q) Write a PL/SQL program to perform sum of two numbers?

DECLARE

A number;

B number;
C number;

BEGIN

A:=10;

B:=20;

C:=A+B;

DBMS_OUTPUT.PUT_LINE(C);

END;

Declaration and initialization using single line.

ex:

DECLARE

A number:=10;

B number:=20;

C number:=A+B;

BEGIN

DBMS_OUTPUT.PUT_LINE('sum of two numbers is '||C);

END;

Using '&' symbol we can take dynamic values.

ex:

---

DECLARE

A number(3);

B number(3);

C number(6);

BEGIN

A:=&a;

B:=&b;

C:=A+B;

DBMS_OUTPUT.PUT_LINE('sum of two numbers is ='||C);

END;
/

To see the output in PL/SQL we need to use execute below command.

ex:

SQL> set serveroutput on

In PL/SQL we can perform DML operations also.

Write a PL/SQL program to insert a record into student table?

ex:

DECLARE

L_sno number(3);

L_sname varchar2(10);

L_sadd varchar2(12);

BEGIN

L_sno:=&sno;

L_sname:='&sname';

L_sadd:='&sadd';

insert into student values(L_sno,L_sname,L_sadd);

DBMS_OUTPUT.PUT_LINE('Record Inserted');

END;

Write a PL/SQL program to update student name based on student number?

ex:

DECLARE

L_sno number(3);

BEGIN

L_sno:=&sno;

update student set sname='rani' where sno=L_sno;


DBMS_OUTPUT.PUT_LINE('Record Updated');

END;

Q) Write a PL/SQL program to delete student record based on student number?

ex:

DECLARE

L_sno number(3);

BEGIN

L_sno:=&sno;

delete from student where sno=L_sno;

DBMS_OUTPUT.PUT_LINE('Record Deleted');

END;

In P/SQL we can perform DRL operations also.

To execute select statement in PL/SQL we need to use "into" clause.

Q) Write a Pl/SQL program to display employee name whose employee id is 201?

ex:

DECLARE

L_empName varchar2(10);

BEGIN

select ename into L_empName from emp where eid=201;

DBMS_OUTPUT.PUT_LINE(L_empName);

END;

/
Q) Write a Pl/SQL program to display employee name and employee salary whose employee id is 205?

ex:

DECLARE

L_empName varchar2(10);

L_empSal number(10,2);

BEGIN

select ename,esal into L_empName,L_empSal from emp where eid=205;

DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);

END;

Q) Write a PL/SQL program to display employee name, employee salary based on employee id ?

ex:

DECLARE

L_empName varchar2(10);

L_empSal number(10,2);

L_empId number(3);

BEGIN

L_empId:=&eid;

select ename,esal into L_empName,L_empSal from emp where eid=L_empId;

DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);

END;

Percentage(%) TYPE attribute

==============================

It is used to declare a local variable with respect to a column type.

syntax:
-------

variable_name table_name.col_name%TYPE;

ex:

A emp.eid%TYPE;

Q) Write a PL/SQL program to display employee name, employee salary based on employee id ?

ex:

DECLARE

L_empName emp.ename%TYPE;

L_empSal emp.esal%TYPE;

L_empId emp.eid%TYPE;

BEGIN

L_empId:=&eid;

select ename,esal into L_empName,L_empSal from emp where eid=L_empId;

DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);

END;

Percentage(%) ROWTYPE attribute

=============================

It is used to declare a local variable which holds complete row of a table.

syntax:

-------

variable_name table_name%ROWTYPE;

ROWTYPE attribute we can't print directly. We need to use table_name.column_name.

ex:
Q) Write a PL/SQL program to display employee information whose employee id is 206?

ex:

DECLARE

A emp%ROWTYPE;

BEGIN

select * into A from emp where eid=206;

DBMS_OUTPUT.PUT_LINE(A.eid||' '||A.ename||' '||A.esal||' '||A.deptno||' '||A.job||' '||A.comm);

END;

Control Statements

===================

We have three control statements.

1) IF THEN

2) IF THEN ELSE

3) IF THEN ELSIF THEN ELSE

1) IF THEN

-----------

It will evaluate the source code only if our condition is true.

ex:
DECLARE

A number:=5000;

BEGIN

IF A>2000 THEN

DBMS_OUTPUT.PUT_LINE('It is greatest');

END IF;

END;

ex:

DECLARE

A number:=1000;

BEGIN

IF A>2000 THEN

DBMS_OUTPUT.PUT_LINE('It is greatest');

END IF;

END;

2) IF THEN ELSE

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

It will evaluate the code either our condition is true or false.

ex:

---

DECLARE

A number:=5000;

BEGIN
IF A>2000 THEN

DBMS_OUTPUT.PUT_LINE('It is too high');

ELSE

DBMS_OUTPUT.PUT_LINE('It is too low');

END IF;

END;

ex:

---

DECLARE

A number:=1000;

BEGIN

IF A>2000 THEN

DBMS_OUTPUT.PUT_LINE('It is too high');

ELSE

DBMS_OUTPUT.PUT_LINE('It is too low');

END IF;

END;

3) IF THEN ELSIF THEN ELSE

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

It will evaluate the code based on multiple conditions.

ex:
DECLARE

A number:=103;

BEGIN

IF A=100 THEN

DBMS_OUTPUT.PUT_LINE('It is police number');

ELSIF A=103 THEN

DBMS_OUTPUT.PUT_LINE('It is enquiry number');

ELSIF A=108 THEN

DBMS_OUTPUT.PUT_LINE('It is emergency numer');

ELSE

DBMS_OUTPUT.PUT_LINE('Invalid option');

END IF;

END;

LOOPS

=====

We have three types of loops in PL/SQL.

1) Simple loop

2) while loop

3) for loop

1) Simple loop

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

It will evaluate the code how long our condition is true.

ex:
DECLARE

A number:=1;

BEGIN

DBMS_OUTPUT.PUT_LINE('Welcome');

LOOP

DBMS_OUTPUT.PUT_LINE('Hello');

EXIT WHEN A=4;

A:=A+1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Thankyou');

END;

2) while loop

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

It will evaluate the code how long our condition is true.

ex:

DECLARE

A number:=1;

BEGIN

DBMS_OUTPUT.PUT_LINE('Welcome');

WHILE A<=4 LOOP

DBMS_OUTPUT.PUT_LINE('Hello');

A:=A+1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Thankyou');

END;
/

3) for loop

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

It will evaluate the code how long our condition is true.

ex

DECLARE

A number;

BEGIN

DBMS_OUTPUT.PUT_LINE('welcome');

FOR A IN 1 .. 4 LOOP

DBMS_OUTPUT.PUT_LINE('Hello');

END LOOP;

DBMS_OUTPUT.PUT_LINE('thankyou');

END;

Interview Skills

=================

Q) Write a program to display 10 natural numbers?

java

----

class Test

public static void main(String[] args)

for(int i=1;i<=10;i++)
{

System.out.println(i);

PL/SQL

------

DECLARE

A number;

BEGIN

FOR A IN 1 .. 10 LOOP

DBMS_OUTPUT.PUT_LINE(A);

END LOOP;

END;

To see the output in PL/SQL we need to execute below command.

ex:

SQL> set serveroutput on

Exceptions

===========

Runtime errors are called exceptions.

We have two types of exceptions in PL/SQL.

1) Predefined exceptions

2) Userdefined exceptions

1) Predefined exceptions

------------------------
Built-In exceptions are called predefined exceptions.

We have following list of predefined exceptions.

i) NO_DATA_FOUND Exception

ii) TOO_MANY_ROWS Exception

iii) ZERO_DIVIDE Exception

iv) VALUE_ERROR Exception

v) DUP_VAL_ON_INDEX Exception

vi) OTHERS

i) NO_DATA_FOUND Exception

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

This exception will raise when select statement does not return any row.

ex:

DECLARE

L_empName emp.ename%TYPE;

BEGIN

select ename into L_empName from emp where eid=209;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('Please check employee id');

END;

/
ii) TOO_MANY_ROWS Exception

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

This exception will raise when select statement returns more then one row.

ex:

---

DECLARE

L_empName emp.ename%TYPE;

BEGIN

select ename into L_empName from emp where deptno=10;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN TOO_MANY_ROWS THEN

DBMS_OUTPUT.PUT_LINE('select stmt returns more then one row');

END;

iii) ZERO_DIVIDE Exception

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

This exception will raise when we divide any number with zero.

ex:

--

DECLARE

A number;

BEGIN

A:=10/0;

DBMS_OUTPUT.PUT_LINE(A);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Dont divide by zero');

END;

/
iv) VALUE_ERROR Exception

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

This exception will raise when there is a mismatch with datatype or size.

ex:

DECLARE

L_empSal emp.esal%TYPE;

BEGIN

select ename into L_empSal from emp where eid=201;

DBMS_OUTPUT.PUT_LINE(L_empSal);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('Please check datatype');

END;

ex:

----

DECLARE

A number(3);

BEGIN

A:=1234;

DBMS_OUTPUT.PUT_LINE(A);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('Please check the size');

END;

v) DUP_VAL_ON_INDEX Exception

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

This exception will raise when we insert duplicate values on primary key.
ex:

alter table emp add primary key(eid);

BEGIN

insert into emp values(206,'Lara',45000,50,'Salesman',600);

DBMS_OUTPUT.PUT_LINE('Record Inserted');

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

DBMS_OUTPUT.PUT_LINE('Duplicate not allowed');

END;

vi) OTHERS

----------

It is a universal angular exception which handle all types of exceptions.

ex:

DECLARE

L_empName emp.ename%TYPE;

BEGIN

select ename into L_empName from emp where eid=209;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('Please check employee id');

END;

2) Userdefined exceptions

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

Exceptions which are created by the user based on the application requirement are called

userdefined exceptions.
step1:

-------

Declare the exception

step2:

-----

Raise the exception

step3:

------

Handle the exception

ex:

---

DECLARE

MY_EX1 Exception;

SALARY number:=5000;

BEGIN

IF SALARY>2000 THEN

RAISE MY_EX1;

END IF;

DBMS_OUTPUT.PUT_LINE(SALARY);

EXCEPTION

WHEN MY_EX1 THEN

DBMS_OUTPUT.PUT_LINE('Salary is too high');

END;

Cursors

========

Cursor is a memory location which is used to run SQL commands.


We have two types of cursors.

1) Implicit cursor

2) Explicit cursor

1) Implicit cursor

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

All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
automatically is called implicit cursor.

We have four types of implicit cursor attributes.

i) SQL%ISOPEN

-----------

It is a boolean attribute which always returns false.

ii) SQL%FOUND

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

It is a boolean attribute which returns true if SQL command is success and returns

false SQL command is failed.

iii) SQL%NOTFOUND

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

It is inverse of SQL%FOUND.

It is a boolean attribute which returns false if SQL command is success and returns

true SQL command is failed.

iv) SQL%ROWCOUNT

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

It will return number of records effected in a database table.


i) SQL%ISOPEN

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

BEGIN

IF SQL%ISOPEN THEN

DBMS_OUTPUT.PUT_LINE('Cursor is opened');

ELSE

DBMS_OUTPUT.PUT_LINE('Cursor is closed');

END IF;

END;

ii) SQL%FOUND

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

BEGIN

update student set sname='rani' where sno=101;

IF SQL%FOUND THEN

DBMS_OUTPUT.PUT_LINE('Record Updated');

ELSE

DBMS_OUTPUT.PUT_LINE('Record Not Updated');

END IF;

END;

iii) SQL%NOTFOUND

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

BEGIN

update student set sname='gogo' where sno=101;

IF SQL%NOTFOUND THEN

DBMS_OUTPUT.PUT_LINE('Record Updated');

ELSE
DBMS_OUTPUT.PUT_LINE('Record Not Updated');

END IF;

END;

iv) SQL%ROWCOUNT

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

BEGIN

delete from student;

DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' records deleted ');

END;

2) Explicit cursor

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

All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
by user is called explicit cursor.

We need to explicit cursor when select statement returns more then one row.

We have four types of explicit cursor attributes.

i) %ISOPEN

---------

It will return true if cursor is opened and returns false if cursor is closed.

ii) %FOUND

---------

It will return true if SQL command is success and returns false if SQL command failed.

iii) %NOTFOUND

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

It is inverse of %FOUND.
It will return false if SQL command is success and returns true if SQL command failed.

iv) %ROWCOUNT

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

It will return number of records effected in a database table.

Q) Write a PL/SQL program to select employee names from employee table?

ex:

DECLARE

CURSOR C1 is select ename from emp;

L_empName emp.ename%TYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 into L_empName;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(L_empName);

END LOOP;

CLOSE C1;

END;

Q) Write a PL/SQL program to select employee names,employee salarys from employee table?

ex:

DECLARE

CURSOR C1 is select ename,esal from emp;

L_empName emp.ename%TYPE;

L_empSal emp.esal%TYPE;
BEGIN

OPEN C1;

LOOP

FETCH C1 into L_empName,L_empSal;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);

END LOOP;

CLOSE C1;

END;

Q) Write a PL/SQL program to select employees information from employee table?

ex:

DECLARE

CURSOR C1 is select * from emp;

A emp%ROWTYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 into A;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(A.eid||' '||A.ename||' '||A.esal||' '||A.deptno||' '||A.job);

END LOOP;

CLOSE C1;

END;

/
PL/SQL procedures

==================

It is a named PL/SQL block which is used to compiled and permanently stored in a database for repeated execution.

syntax:

-----

create or replace procedure <procedure_name>

is

begin

end;

Q) Write a PL/SQL procedure to display Hello World?

create or replace procedure p1

is

begin

DBMS_OUTPUT.PUT_LINE('Hello World');

END;

To execute the procedure we need to run below command.

ex:

exec p1;

To see the output in PL/SQL we need to execute below command.

ex:

SQL> set serveroutput on


Exceptions

===========

Runtime errors are called exceptions.

We have two types of exceptions in PL/SQL.

1) Predefined exceptions

2) Userdefined exceptions

1) Predefined exceptions

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

Built-In exceptions are called predefined exceptions.

We have following list of predefined exceptions.

i) NO_DATA_FOUND Exception

ii) TOO_MANY_ROWS Exception

iii) ZERO_DIVIDE Exception

iv) VALUE_ERROR Exception

v) DUP_VAL_ON_INDEX Exception

vi) OTHERS

i) NO_DATA_FOUND Exception

--------------------------
This exception will raise when select statement does not return any row.

ex:

DECLARE

L_empName emp.ename%TYPE;

BEGIN

select ename into L_empName from emp where eid=209;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('Please check employee id');

END;

ii) TOO_MANY_ROWS Exception

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

This exception will raise when select statement returns more then one row.

ex:

---

DECLARE

L_empName emp.ename%TYPE;

BEGIN

select ename into L_empName from emp where deptno=10;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN TOO_MANY_ROWS THEN

DBMS_OUTPUT.PUT_LINE('select stmt returns more then one row');

END;

iii) ZERO_DIVIDE Exception

------------------------
This exception will raise when we divide any number with zero.

ex:

--

DECLARE

A number;

BEGIN

A:=10/0;

DBMS_OUTPUT.PUT_LINE(A);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Dont divide by zero');

END;

iv) VALUE_ERROR Exception

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

This exception will raise when there is a mismatch with datatype or size.

ex:

DECLARE

L_empSal emp.esal%TYPE;

BEGIN

select ename into L_empSal from emp where eid=201;

DBMS_OUTPUT.PUT_LINE(L_empSal);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('Please check datatype');

END;

ex:

----
DECLARE

A number(3);

BEGIN

A:=1234;

DBMS_OUTPUT.PUT_LINE(A);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('Please check the size');

END;

v) DUP_VAL_ON_INDEX Exception

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

This exception will raise when we insert duplicate values on primary key.

ex:

alter table emp add primary key(eid);

BEGIN

insert into emp values(206,'Lara',45000,50,'Salesman',600);

DBMS_OUTPUT.PUT_LINE('Record Inserted');

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

DBMS_OUTPUT.PUT_LINE('Duplicate not allowed');

END;

vi) OTHERS

----------

It is a universal angular exception which handle all types of exceptions.

ex:

DECLARE

L_empName emp.ename%TYPE;
BEGIN

select ename into L_empName from emp where eid=209;

DBMS_OUTPUT.PUT_LINE(L_empName);

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('Please check employee id');

END;

2) Userdefined exceptions

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

Exceptions which are created by the user based on the application requirement are called

userdefined exceptions.

step1:

-------

Declare the exception

step2:

-----

Raise the exception

step3:

------

Handle the exception

ex:

---

DECLARE

MY_EX1 Exception;

SALARY number:=5000;

BEGIN
IF SALARY>2000 THEN

RAISE MY_EX1;

END IF;

DBMS_OUTPUT.PUT_LINE(SALARY);

EXCEPTION

WHEN MY_EX1 THEN

DBMS_OUTPUT.PUT_LINE('Salary is too high');

END;

Cursors

========

Cursor is a memory location which is used to run SQL commands.

We have two types of cursors.

1) Implicit cursor

2) Explicit cursor

1) Implicit cursor

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

All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
automatically is called implicit cursor.

We have four types of implicit cursor attributes.

i) SQL%ISOPEN

-----------

It is a boolean attribute which always returns false.

ii) SQL%FOUND
--------------

It is a boolean attribute which returns true if SQL command is success and returns

false SQL command is failed.

iii) SQL%NOTFOUND

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

It is inverse of SQL%FOUND.

It is a boolean attribute which returns false if SQL command is success and returns

true SQL command is failed.

iv) SQL%ROWCOUNT

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

It will return number of records effected in a database table.

i) SQL%ISOPEN

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

BEGIN

IF SQL%ISOPEN THEN

DBMS_OUTPUT.PUT_LINE('Cursor is opened');

ELSE

DBMS_OUTPUT.PUT_LINE('Cursor is closed');

END IF;

END;

ii) SQL%FOUND

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

BEGIN

update student set sname='rani' where sno=101;

IF SQL%FOUND THEN

DBMS_OUTPUT.PUT_LINE('Record Updated');
ELSE

DBMS_OUTPUT.PUT_LINE('Record Not Updated');

END IF;

END;

iii) SQL%NOTFOUND

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

BEGIN

update student set sname='gogo' where sno=101;

IF SQL%NOTFOUND THEN

DBMS_OUTPUT.PUT_LINE('Record Updated');

ELSE

DBMS_OUTPUT.PUT_LINE('Record Not Updated');

END IF;

END;

iv) SQL%ROWCOUNT

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

BEGIN

delete from student;

DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' records deleted ');

END;

2) Explicit cursor

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

All the activities related to cursor like opening the cursor, processing the cursor and closing the cursor which is done
by user is called explicit cursor.

We need to explicit cursor when select statement returns more then one row.
We have four types of explicit cursor attributes.

i) %ISOPEN

---------

It will return true if cursor is opened and returns false if cursor is closed.

ii) %FOUND

---------

It will return true if SQL command is success and returns false if SQL command failed.

iii) %NOTFOUND

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

It is inverse of %FOUND.

It will return false if SQL command is success and returns true if SQL command failed.

iv) %ROWCOUNT

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

It will return number of records effected in a database table.

Q) Write a PL/SQL program to select employee names from employee table?

ex:

DECLARE

CURSOR C1 is select ename from emp;

L_empName emp.ename%TYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 into L_empName;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(L_empName);
END LOOP;

CLOSE C1;

END;

Q) Write a PL/SQL program to select employee names,employee salarys from employee table?

ex:

DECLARE

CURSOR C1 is select ename,esal from emp;

L_empName emp.ename%TYPE;

L_empSal emp.esal%TYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 into L_empName,L_empSal;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(L_empName||' '||L_empSal);

END LOOP;

CLOSE C1;

END;

Q) Write a PL/SQL program to select employees information from employee table?

ex:

DECLARE

CURSOR C1 is select * from emp;


A emp%ROWTYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 into A;

EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(A.eid||' '||A.ename||' '||A.esal||' '||A.deptno||' '||A.job);

END LOOP;

CLOSE C1;

END;

PL/SQL procedures

==================

It is a named PL/SQL block which is used to compiled and permanently stored in a database for repeated execution.

syntax:

-----

create or replace procedure <procedure_name>

is

begin

end;

Q) Write a PL/SQL procedure to display Hello World?


create or replace procedure p1

is

begin

DBMS_OUTPUT.PUT_LINE('Hello World');

END;

To execute the procedure we need to run below command.

ex:

exec p1;

To see the output in PL/SQL we need to run below command.

ex:

SQL> set serveroutput on

Procedure may contains three parameters.

1) IN Parameter

2) OUT Parameter

3) IN OUT Parameter

1) IN Parameter

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

It is used to accept the values from the user.

Q) Write a procedure to perform sum of two numbers?

create or replace procedure sum(A IN number,B IN number)

is

C number;
begin

C:=A+B;

DBMS_OUTPUT.PUT_LINE('sum of two numbers is ='||C);

END;

To invoke the procedure we need to use below command.

ex:

exec sum(10,20);

Q) Write a procedure to delete student record based on student number?

create or replace procedure delete_record(L_Sno IN student.sno%TYPE)

is

BEGIN

delete from student where sno=L_Sno;

DBMS_OUTPUT.PUT_LINE('Record Deleted');

END;

To invoke the procedure we need to use below command.

ex:

exec delete_record(103);

2) OUT Parameter

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

It is used to return the value to the user.

Q) Write a procedure to accept two numbers and return sum?

create or replace procedure ret_sum(A IN number,B IN number,C OUT number)


is

begin

C:=A+B;

END;

Steps to call a procedure having OUT parameter

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

step1:

----

Declare a bind variable

ex:

variable N number;

step2:

-----

Execute the procedure

ex:

exec ret_sum(10,20,:N);

step3:

-----

Print the bind variable

ex:

print N;

3) IN OUT parameter

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

It is used to accept and return value from/to the user.

Q) Write a procedure to perform cube of a given number?

create or replace procedure ret_cube(A IN OUT NUMBER)


is

BEGIN

A:=A*A*A;

END;

steps to call a procedure having IN OUT parameter

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

step1:

-----

Declare a bind variable.

ex:

variable N number;

step2:

-----

Initialize the bind variable.

ex:

BEGIN

:N:=5;

END;

step3:

------

Execute the procedure.

ex:

exec ret_cube(:N);

step4:

------

Print bind variable

ex:

print N;
Q) Write a query to see the list of procedures present in database?

select object_name from user_objects where object_type='PROCEDURE';

Q) Write query to see the source code of a procedure?

select text from user_source where name='P1';

Q) Write a query to drop the procedure?

drop procedure p1;

drop procedure ret_sum;

Functions

===========

Function is a named PL/SQL block which must and should returns a value.

syntax:

------

create or replace function <function_name>

return datatype

is

begin

return <value>;

END;

/
Q) Write a function to perform sum of two numbers and return sum?

create or replace function f1(A number,B number)

return number

is

C number;

begin

C:=A+B;

return C;

END;

To invoke a function we need to use below command.

ex:

select f1(10,20) from dual;

Q) Write a function to accept one salary and find out 10% of TDS?

create or replace function f2(salary number)

return number

is

TAX number;

begin

TAX:=salary*10/100;

return TAX;

END;

To invoke a function we need to use below command.

ex:

select f2(1000) from dual;


Q) Write a query to see the list of functions present in database?

select object_name from user_objects where object_type='FUNCTION';

Q) Write query to see the source code of a function?

select text from user_source where name='F1';

Q) Write a query to drop the function?

drop function f1;

drop function f2;

Q) What is the difference between procedures and functions?

procedure function

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

A procedure may or may not returns a value. A function always returns a value.

DML operations are allowed. DML operations are not allowed.

Can't by invoke by using select command. Can by invoke by using select command.

Packages
=========

A package is a collection of logical related sub programs.

PL/SQL procedures and functions are called logical related sub programs.

Every package creation involved in two steps.

1) Package specification

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

It is a declaration of logical related sub programs.

2) package body

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

It contains definition of logical related sub programs.

ex:1

-----

package specification

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

create or replace package pkg1

is

procedure sum(A IN number,B IN number);

end pkg1;

package body

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

create or replace package body pkg1

is

procedure sum(A IN number,B IN number)


is

C number;

begin

C:=A+B;

DBMS_OUTPUT.PUT_LINE(C);

END;

end pkg1;

To execute a package we need to use below command.

ex:

exec pkg1.sum(20,30);

ex:2

----

package specification

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

create or replace package pkg2

is

function ret_sum(A number,B number)

return number;

end pkg2;

package body

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

create or replace package body pkg2

is

function ret_sum(A number,B number)


return number

is

C number;

begin

C:=A+B;

return C;

END;

end pkg2;

To execute a package we need to use below command.

ex:

select pkg2.ret_sum(10,20) from dual;

Q) Write a query to see the list of packages present in database?

select object_name from user_objects where object_type='PACKAGE';

Q) Write query to see the source code of a package?

select text from user_source where name='PKG1';

Q) Write a query to drop the package?

drop package body pkg1;


drop package pkg1;

drop package body pkg2;

drop package pkg2;

Triggers

=========

Trigger is a PL/SQL block which executes based on events.

Triggers events are insert, update and delete.

Triggers timings are before, after and insteadof.

syntax:

------

create or replace trigger <trigger_name> <timing> <event> on <object_name>

is

begin

END;

ex:

---

create or replace trigger trg1 before insert on student

begin

DBMS_OUTPUT.PUT_LINE('Thanks for inserting the record');

END;

select * from student;


insert into student values(104,'ramulu','pune'); // trigger will execute

Note:

-----

Trigger can be created on multiple events.

ex:

create or replace trigger trg2 after insert OR update OR delete on student

begin

if inserting then

DBMS_OUTPUT.PUT_LINE('Yahoo! inserted');

elsIf updating then

DBMS_OUTPUT.PUT_LINE('Yahoo! updated');

else

DBMS_OUTPUT.PUT_LINE('Yahoo! deleted');

end if;

end;

insert into student values(105,'raj','TS');

update student set sname='rani' where sno=105;

delete from student where sno=105;

We have two types of triggers.

1) Statement level trigger

2) Row level trigger

1) Statement level trigger


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

Statement level trigger will execute only for one time irrespective of number of records

effected in a database table.

By default every trigger is a statement level trigger.

ex:

create or replace trigger trg3 after delete on student

begin

DBMS_OUTPUT.PUT_LINE('Deleted');

END;

delete from student;

2) ROW level trigger

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

Row level trigger will execute irrespective of number of records effected in a database table.

To create a row level trigger we need to "for each row" clause.

ex:

create or replace trigger trg4 after delete on student for each row

begin

DBMS_OUTPUT.PUT_LINE('Deleted');

END;

delete from student;

Q) Write a query to see the list of triggers present in database?


select object_name from user_objects where object_type='TRIGGER';

Q) Write query to see the source code of a trigger?

select text from user_source where name='TRG1';

Q) Write a query to drop the trigger?

drop trigger trg1;

drop trigger trg2;

drop trigger trg3;

drop trigger trg4;

You might also like