Documente Academic
Documente Profesional
Documente Cultură
Create Table
Alter Table
Drop Table
Create View
Drop View
EMPLOYEE DETAILS:
TABLE STRUCTURE
EMP_ID NUMBER 4
EMP_NAME ALPHANUMERIC 14
CITY ALPHANUMERIC 14
DESIGNATION ALPHANUMERIC 14
SALARY NUMBER 12
1. Create Command: -
Syntax:
create table < table name> (column-name data type (size) constraints);
Description:
The create command when applied with above specification creates the fields of
different data type.
2. Alter Command:-
Syntax:
a) alter table <table name> add(column-name data type (size));
Description:
The alter command when used with add allows us to add an additional column to an
already existing table.
Syntax:
b) alter table <table name> modify(column-name data type (size));
Description:
The alter command when used with modify redefines the column with the given values but cannot change the
column names.
Syntax:
a) alter table <table name> drop(column-name);
Description:
The alter command when used with drop deletes the specified column in the table.
3. Drop Command:-
Syntax:
Drop Table <Table_Name> ;
Description:
A table can be dropped (deleted) by using a drop table command.
Description:
A view is named, derived, virtual table. A view takes the output of a query and treats it
as a table; therefore, a view can be thought of as a “stored query “ or a “virtual table”. The
tables upon which a view is based are called base tables.
Description:
A View can be dropped (deleted) by using a drop view command.
6. Truncate Command:
Syntax:
Truncate table <table-name>;
Description:
The details in the table is deleted but the table structure remains.
7. Rename Command :
Syntax:
Rename <oldtable-name> to <newtable-name>;
Description:
The old table name is replaced with the new table name.
PROGRAM TO LEARN DDL COMMANDS
CREATE TABLE:
SQL> create table empp(emp_id number(4),emp_name varchar(14),city varchar(14),designation varchar(14),salary
number(14));
Table created.
ALTER TABLE:
SQL> alter table empp add(doj date,basic number(10,2));
Table altered.
Table altered.
CREATE VIEW:
SQL> create view emppview as select * from empp;
View created.
DROP VIEW:
SQL> drop view emppview;
View dropped.
DROP TABLE:
SQL> drop table empp;
Table dropped.
TRUNCATE COMMAND:
SQL> truncate table empp;
Table truncated.
SQL>desc empp;
RESULT:
Thus the DDL command are executed and verified.
DATA MANIPULATION LANGUAGE
1. Insert:
Syntax:
Description:
The ‘insert into’ command insert the values in the specified table .In the insert into SQL sentence the columns and
values have a one to one relationship (i.e) the first value described into the first column, the second value described being
inserted into the second column and so on.
2. Delete:
Syntax:
Description:
3. Update:
Syntax:
Description:
The update command is used to change or modify data values in a table. To update
1. All the rows from a table.
(Or)
2. A select set of rows from a table.
INSERT COMMAND:
SQL> insert into empp values (&emp_id,'&emp_name','&city','&designation','&salary');
Enter value for emp_id: 100
Enter value for emp_name: james
Enter value for city: bangalore
Enter value for designation: modleader
Enter value for salary: 20000
old 1: insert into empp values (&emp_id,'&emp_name','&city','&designation','&salary')
new 1: insert into empp values(100,'james','bangalore','modleader','20000')
1 row created.
SQL> /
Enter value for emp_id: 101
Enter value for emp_name: ganesh
Enter value for city: chennai
Enter value for designation: softengi
Enter value for salary: 21000
old 1: insert into empp values(&emp_id,'&emp_name','&city','&designation','&salary')
new 1: insert into empp values(101,'ganesh','chennai','softengi','21000')
1 row created.
SQL> /
Enter value for emp_id: 103
Enter value for emp_name: priya
Enter value for city: calcutta
Enter value for designation: manager
Enter value for salary: 50000
old 1: insert into empp values (&emp_id,'&emp_name','&city','&designation','&salary')
new 1: insert into empp values(103,'priya','calcutta','manager','50000')
1 row created.
UPDATE COMMAND:
SQL> update empp set designation='engineer'where emp_id=101;
1 row updated.
DELETE COMMAND:
SQL> delete from empp where emp_id=100;
1 row deleted.
1. Select Statement:
Syntax:
Select <attribute list> from <table list>[where clause];
Description:
Select command is used to retrieve data from one or more tables or columns. The attribute list is a list of
attributes name whose values are displayed by query. A missing where clause indicate no condition on tuple selection. The
condition is a Boolean expression that identifies the tuples to be retrieved by the query.
Distinct Clause:
Syntax:
Select distinct <column name> from <table name>;
Description:
Displays the distinct values from a table by eliminating the duplicate values. It performs
Grouping of the specified fields when queried with distinct statement.
2. Order By Clause:
Syntax:
Select <column name> from <table name> order by <column name>;
Description:
Order By sorts the output of any specified column or expression. The Order By clause must always have task
in any select statement. The default order is ascending order. we should specify the keyword ‘desc’ if we want it in
descending order.
3. Group By Clause:
Syntax:
Select <column name> from <table name > group by <column name>;
Description:
. The Group By clause specifies the grouping of function to appear in the select clause. So that the value
resulting from group of tuples appear along with the values of grouping attributes are SUM ,AVERAGE , MAX, MIN,
COUNT,STDDEV
4. Having Clause:
Syntax:
Select <column name> from <table name> where <condition>
Group by <condition> having<condition>;
Description:
The ‘having’ clause is used to specify certain conditions on rows, retrieved by using group by clause. This
clause should be preceded by a ‘group by’ clause.
5. Null Command:
Syntax:
Select <column-name> NVL(substitution column,substituted value) from <table name> where <condition>;
Description:
The NVL function helps in substituting the value in the null fields.but this function only displays the change
and does not update the columns.
SELECT COMMAND:
6 rows selected.
6 rows selected.
SELECT-ORDER BY:
SELECT DISTINCT:
DESIGNATION MAX(SALARY)
-------------- ------------------------------
accountant 15000
ceo 20000
engineer 25000
manager 50000
modleader 20000
projlead 40000
6 rows selected.
SQL> select max(salary),min(salary),sum(salary) from empp group by designation having designation='ceo ';
NULL COMMAND:
SQL> select * from empp;
8 rows selected.
8 rows selected.
BETWEEN CLAUSE:
6 rows selected.
SQL> select * from empp where salary between 20000 and 55000;
SQL> select * from empp where salary not between 20000 and 55000;
RESULT:
TCL COMMANDS
TRANSACTION CONTROL LANGUAGE
The DCL commands are:
Commit
Rollback
Save point
1. COMMIT:
Syntax:
SQL> set auto commit on ;
SQL> set auto commit off ;
SQL>commit ;
Description:
Commit command tells the DBMS to make permanent changes made to temporary copies of the data updating the
permanent database tables to match the updated temporary copies.
2. ROLL BACK:
Syntax:
SQL> rollback ;
Description:
Rollback tells the DBMS to undo any changes made to the DBMS after the most recent commit.
3. SAVE POINT:
Syntax:
SQL>Savepoint<name>;
Description:
Save point are like markers to divide a very lengthy transaction to smaller ones. They are used to identify a point in
transaction to which we can later rollback. Thus savepoint is used in conjunction with rollback to rollback portions of the
current transaction.
4 rows selected.
1 row deleted.
3 rows delected.
SQL> rollback;
Rollback complete.
COMMIT:
SQL> commit;
Commit complete.
Rollback complete.
SAVEPOINT:
Rollback complete.
Rollback complete.
RESULT:
DCL COMMANDS
DATA CONTROL LANGUAGE
The DCL commands are:
Grant
Revoke
1. GRANT:
Syntax:
SQL>grant <privileges> on <table name> to user ;
Description:
Grant gives specific SQL statement access or individual data objects to a user or a group of users.
2. REVOKE:
Syntax:
SQL> Revoke <privileges> on <tablename> from user ;
Description:
Revoke removes specific SQL statement access previously granted on individual database objects from a user or
group of users.
PREDICATES:
SQL>select*from itemlist;
1. ALL
Syntax:
Select*from table_name where column_name >all(column_value)
Example:
Sql>select *from itemlist where code>ALL(I);
2. SOME:
Syntax
Select column_name from table_name where col_name2>some(selectcolumn_name from table_name where collum
_name3=’value’);
Example:
SQL>select item from itemlist where code>some(select code from itemlist where price=20.5);
ITEM
--------
Notebook
Bat
3. ANY
Syntax:
Select column_name from table name where column_name>any (select column_name from table_name where
column_name=’value’);
Example:
SQL>select item from itemlist where price>any(select price from itemlist where code=2);
ITEM
----------
Bat
4. LIKE
SYNTAX:
Select*from table_name ehere column_name like(‘value’)
Example:
SQL>select *from itemlist where item like(‘P%’);
PRIMARY KEY:
Syntax:
Create table table _name (field datatype) constraints <label> primary key(column_name);
SQL> Create table note (id number(6)constraint flo not null, num number(6)primary key);
Table created
Table created
UNIQUE:
Syntax:
Create table table _name (field datatype) constraints <label> unique (column_name);
Syntax:
Create table table _name ( datatypes ……..) constraints from references table_name (column_name);
SQL>desc jeep;
NAME NULL? TYPE
------------ -------------- -------------
ID NUMBER (5)
BUILT-IN FUNCTION
1. Group function or Aggregate function:
2. Character Function:
3. Number Function:
5. Convertion Function:
CHARACTER FUNCTION:
UPPER(NAME)
---------------
MOHAN
PARANDHA
RAJAN
KUMARAN
MIDHUN
LOWER(NAME)
---------------
mohan
parandha
rajan
kumaran
midhun
SQL> select initcap(name) from stud;
INITCAP(NAME)
---------------
Mohan
Parandha
Rajan
Kumaran
Midhun
SUBS
----
giri
LTRI
----
come
RTR
---
wel
LPAD('WELCOME
-------------
$$$$$$welcome
RPAD('WELCOME
-------------
welcome$$$$$$
NAME
---------------
mohan
midhun
REPLACE('JACK
-------------
back bill boy
TRANSLATE('
-----------
bck bll boy
DATE FUNCTION:
SQL> select add_months('25-dec-07',4) from dual;
ADD_MONTH
---------
25-APR-08
LAST_DAY(
---------
31-DEC-07
MONTHS_BETWEEN('15-DEC-07','13-AUG-07')
---------------------------------------
4.06451613
NEXT_DAY(
---------
06-JUL-07
GREATEST(
---------
22-may-07
AGGREGATE FUNCTION:
SQL> select avg(marks) from stud;
AVG(MARKS)
----------
75.2
MIN(MARKS)
----------
50
MAX(MARKS)
----------
90
NUMERIC FUNCTIONS:
SQL> SELECT ABS(-15) FROM DUAL;
ABS(-15)
----------
15
LN(35)
----------
3.55534806
LOG(10,1000)
------------
3
SQRT(25)
----------
5
Operators
Set Operators
1. Union
Description:
Multiple queries can be put together and their output combined using union clause with duplication, the
union clause merges the output of 2 or more queries into single set of rows and columns.
SQL> select c_name from borrower union select c_name from depositor;
C_NAME
----------
adams
curry
hayes
jackson
johnson
jones
lindsay
smith
2. Union All
Description:
Multiple queries can be put together and their output combined using union all clause with duplicate.
SQL> select c_name from borrower union all select c_name from depositor;
C_NAME
----------
adams
curry
hayes
jackson
jones
smith
smith
willams
hayes
johnson
johnson
jones
lindsay
smith
turner
15 rows selected.
3. Intersection
Description:
Multiple queries can be put together and their output combine using union clause intersect clause output
Only rows produced by both the queries intersected.
SQL> select c_name from borrower intersect select c_name from depositor;
C_NAME
----------
hayes
jones
smith
4. Minus
Description:
Multiple queries can be put together and their output can be combines using minus clauses. The minus
Clause output the rows produced by both the first query, after filtering the rows retrieved by second query.
SQL> select c_name from borrower minus select c_name from depositor;
C_NAME
----------
adams
curry
jackson
willams
JOINS:
Joins queries are used to retrieve data from multiple tables.
TYPES OF JOINS:
1. EQUI JOIN
2. CARTESIAN JOIN
3. OUTER JOIN
RIGHT OUTER JOIN
LEFT OUTER JOIN
TABLE STRUCUUTRE:
6 rows selected.
Equi Join:-
Description:-
Equi joins are done by equating tables based on a criteria.It uses ‘=’ symbol.
1)List the employee details with their department name and location.
Cartesian Join:-
2)List all the different possible rows from emp & dept tables.
24 rows selected.
Non equi joins are other than ‘=’ operator if join is formed using any one of the
relational operators(<,>,!=,<>,>=,<=).
3) List the ename & grade of the employees deprnding on their salary.
EMP_NAME GRADE
----------------- ----------
Allwin 5
Computer 5
Poornima 5
Dravid 5
Allwin 6
Poornima 6
Dravid 6
7 rows selected.
Outer Join:-
Description:-
Outer joins retrieves the row returned by equi join as well as the row that do not
match any row from other tables.
4)a.List the name,department & deptno from emp,dept tables even if the department
contain no employees.
SQL> select e.emp_name,d.emp_name,d.dept_no from empl e,dept1 d where
e.emp_name=d.emp_name(+);
6 rows selected.
4)b.List the all the field from emp,dept tables even if the department contain no
employees.
6 rows selected.
PL/SQL PROGRAMS
PROGRAM
declare
x integer;
y integer;
z integer;
begin
x:=&x;
y:=&y;
z:=x+y;
dbms_output.put_line('The Sum of two number is ='||z);
end;
OUTPUT :
SQL>/
FACTORIAL OF A NUMBER
AIM:
PROGRAM:
declare
f number:=1;
i number;
n number:=&n;
begin
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('The factorial of a given no is:'||f);
end;
RESULT:
Thus the PL/SQL program to find the factorial of a number is executed and
verified.
PALINDROME
AIM:
To write the PL/SQL program to check whether the given string is a Palindrome.
PROGRAM:
declare
len number;
a integer;
str1 varchar(10):='&str1';
str2 varchar(10);
begin
len:=length(str1);
a:=len;
for i in 1..a
loop
str2:=str2||substr(str1,len,1);
len:=len-1;
end loop;
if (str1=str2) then
dbms_output.put_line(str1 || ' is a palindrome');
else
dbms_output.put_line(str1 || ' not a palindrome');
end if;
end;
SQL> /
Enter value for str1: faith
old 4: str1 varchar(10):='&str1';
new 4: str1 varchar(10):='faith';
faith not a palindrome
RESULT:
Thus the PL/SQL program to check the given string is a Palindrome or not is
executed and verified.
FIBONACCI
AIM:
PROGRAM:
declare
i number;
c number;
n number:=&n;
a number:=-1;
b number:=1;
begin
for i in 1..n
loop
c:=a+b;
dbms_output.put_line(c);
a:=b;
b:=c;
end loop;
end;
AIM:
PROGRAM:
declare
n number:=&n;
i number;
begin
i:=n*(n+1);
n:=i/2;
dbms_output.put_line('The sum of series is:'||n);
end;
(or)
declare
n number;
s number;
i number;
begin
n:=&n;
s:=0;
for i in 1..n
loop
s:=s+i;
end loop;
dbms_output.put_line('sum='||s);
end;
SAMPLE INPUT OUTPUT :
Thus the PL/SQL program to find the Sum of series is executed and verified.
TRIGGERS
AIM:
To write a PL/SQL program using triggers to replicate the record.
TABLE STRUCTURE 1:
Table name: trig11
TABLE STRUCTURE 1:
Table name: trig12
SQL> /
Trigger created.
Thus the PL/SQL block program using triggers is executed and verified.
TRIGGERS
AIM:
To write a PL/SQL program to display the old and new values of a record after
updating using triggers.
PROGRAM:
SQL>/
Trigger created.
RESULT:
Thus the PL/SQL block program using triggers is executed and verified.
TRIGGERS
AIM:
To write a PL/SQL program to restrict the entries into the table using triggers.
PROGRAM:
SQL> /
Trigger created.
Thus the PL/SQL block program using triggers is executed and verified.
EXCEPTION HANDLING
Predefined Exception
User-defined Exception
An Exception is raised when an error occurs. In case of an error, normal execution stops
and the control is immediately transferred to the exception handling part of the PL\SQL
block. Predefined Exception is raised automatically by the system during run time,
whereas user-defined exceptions are raised explicitly using RAISE statements.
PREDEFINED EXCEPTION:
Syntax:
Begin
Sequence_of_statements;
Exception
When <exception_name> then
Sequence_of_statements;
When others then /* the last exception in the exception handler*/
Sequence_of_statements;
End;
USER-DEFINED EXCEPTION:
User-defined exception should be declared only in the declarative part of the PL/SQL
block.
Syntax:
<exception_name> exception;
The Syntax for a raise statement is as follows.
raise <exception_name>;
USER-DEFINED EXCEPTION
AIM:
PROGRAM:
declare
co number;
exceeds_value exception;
begin
select count(*) into co from employe;
if co <5 then
insert into employe values (&empno,'&empname','&empst',&empsal);
else
raise exceeds_value;
end if;
exception
when exceeds_value then
dbms_output.put_line('rows will not be inserted');
end;
SQL> /
Enter value for empno: 5
Enter value for empname: rajeswari
Enter value for empst: software
Enter value for empsal: 25000
old 7: insert into employe values (&empno,'&empname','&empst',&empsal);
new 7: insert into employe values (5,'rajeswari','software',25000);
SQL> /
Enter value for empno: 6
Enter value for empname: madhavan
Enter value for empst: leader
Enter value for empsal: 24000
old 7: insert into employe values (&empno,'&empname','&empst',&empsal);
new 7: insert into employe values (6,'madhavan','leader',24000);
rows will not be inserted
RESULT:
Thus the PL/SQL block program using user-defined exception handler is executed
and verified.
PREDEFINED EXCEPTION
AIM:
PROGRAM:
declare
empid number(5);
emname varchar(50);
begin
empid:=&empid;
select empname into emname from employe where empno=empid;
dbms_output.put_line('The employe name is:'||emname);
exception
when no_data_found then
dbms_output.put_line('data not found');
end;
SQL> /
Enter value for empid: 5
old 5: empid:=&empid;
new 5: empid:=5;
data not found
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL block program using pre-defined exception handler is executed
and verified.
CURSORS
AIM:
Create a PL/SQL block that deletes student’s records whose department is CSE
and display the number of records deleted and the remaining number of records.
PROGRAM:
declare
cursor c is select * from studdd cse;
a c% rowtype;
n number:=0;
begin
open c;
loop
fetch c into a;
exit when c% notfound;
if a.dept='cse' then
delete from studdd where dept='cse';
n:=n+1;
end if;
end loop;
dbms_output.put_line('Deleted record '||n);
dbms_output.put_line('Remaining records '||(c% rowcount-n));
close c;
commit;
end;
SQL> /
Deleted record 2
Remaining records 3
7 rows selected.
Thus the PL/SQL block program using cursor is executed and verified.
CURSORS
AIM:
Create a PL/SQL block to determine the top 5 scores from the student table and to
insert these records into a new table.
PROGRAM:
declare
cursor c is select * from studddd order by total desc;
a studddd % rowtype;
n number:=0;
begin
open c;
loop
fetch c into a;
exit when c% notfound or c% rowcount>5;
insert into detail1 values(a.rollno,a.name,a.dept,a.total);
end loop;
close c;
commit;
end;
SQL>/
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL block program using cursor is executed and verified.
CURSORS
AIM:
Create a PL/SQL block to update the total and grade of the student table by
comparing marks in the individual subject.
PROGRAM:
declare
cursor c is select * from studdd1;
a c% rowtype;
tot number;
g char;
begin
open c;
loop
fetch c into a;
exit when c% notfound;
tot:=a.m1+a.m2+a.m3;
if a.m1>50 and a.m2>50 and a.m3>50 then
g:='H';
else
g:='F';
end if;
update studdd2 set total=tot,grade=g where rollno=a.rollno;
end loop;
commit;
close c;
end;
SQL> /
ROLLNO NAME M1 M2 M3
--------------------------- -------- ---------- ---------- ----------
1 svs 60 67 67
2 rekka 56 67 78
3 archu 78 45 30
RESULT:
Thus the PL/SQL block program using cursor is executed and verified.
(local declaration)
Begin
(executable statements)
[Exception]
(exception handlers)
end;
AIM:
To write a PL/SQL block using function to check whether the quantity on hand and
reorder level exceeded the maximum level.
PROGRAM:
SQL>/
Function created.
SQL> declare
a varchar2(5);
b number;
begin
a:='&a';
b:=items(a);
dbms_output.put_line('the values returned is ' || b);
end;
Thus the PL/SQL block program using function is executed and verified
FUNCTION
AIM:
To write a PL/SQL block using function to find the grade of the student using
cursors.
PROGRAM:
SQL> create or replace function grade(m1 number,m2 number,m3 number)
return char is
begin
if m1>50 and m2>50 and m3>50 then
return 'PASS';
else
return 'FAIL';
end if;
end;
SQL> /
Function created.
SQL> declare
cursor c is select id,m1,m2,m3 from student;
a c%rowtype;
begin
open c;
loop
fetch c into a;
exit when c%notfound;
update student set grade=grade(a.m1,a.m2,a.m3) where id=a.id;
end loop;
commit;
close c;
end;
SQL>/
PL/SQL procedure successfully completed.
SQL> select * from student;
ID M1 M2 M3 TOTAL GRADE
-----------------------------------------------------------------
cs01 45 90 50 185
cs02 90 70 60 220
cs03 60 50 45 155
cs04 70 80 70 220
cs05 50 40 40 130
SQL> select * from student;
ID M1 M2 M3 TOTAL GRADE
----------------------------------------------------------------
cs01 45 90 50 185 FAIL
cs02 90 70 60 220 PASS
cs03 60 50 45 55 FAIL
cs04 70 80 70 220 PASS
cs05 50 40 40 130 FAIL
RESULT:
Thus the PL/SQL block program using function is executed and verified
PROCEDURE
SYNTAX:
NOTE:
While declaring variables in the declarative part of the procedure body,we should
not specify the width of the datatype.
Eg.
Procedure pro(name char(40)) is
Begin
(set of statements);
End;
SYNTAX TO EXECUTE:
Sql>exec <proc_name>(parameters);
AIM:
To write a PL/SQL block to check whether the quantity on hand is less than the
reorder level then order more quantity of the item and update the table so that the changes
are reflected using procedure(in mode).
PROGRAM:
SQL> /
Procedure created.
RESULT:
Thus the PL/SQL block program using procedure is executed and verified.
PROCEDURE
AIM:
To write a PL/SQL block to check whether the quantity on hand is less than the
reorder level then order more quantity of the item and update the table so that the changes
are reflected using procedure(in & out mode).
PROGRAM:
SQL>/
Procedure created.
RESULT:
Thus the PL/SQL block program using procedure is executed and verified.
PACKAGES
Package Specification:
Syntax:
Create package <package_name> is <declaration>
Begin
(executable statements)
End [package_name]
Package Body
Syntax:
Create package body <package_name> is declaration>
Begin
(executable statements)
End [body_name];
AIM:
PROGRAM:
Package Specification:
create or replace package packs is
procedure display;
function prime(n number)return varchar;
function odd(n number)return varchar;
function positive(n number)return varchar;
end packs;
SAMPLE INPUT OUTPUT:
SQL>/
Package created.
Package Body
create or replace package body packs as
procedure display is
a varchar(15);
m number;
begin
m:=&m;
a:=prime(m);
if a='prime' then
dbms_output.put_line(m || 'is a prime');
else
dbms_output.put_line(m || 'is not prime');
end if;
a:=odd(m);
if a='odd' then
dbms_output.put_line(m || 'is odd');
else
dbms_output.put_line(m || 'is even');
end if;
a:=positive(m);
if a='positive' then
dbms_output.put_line(m || 'is a positive number');
else
dbms_output.put_line(m || 'is a negative number');
end if;
end display;
function prime(n number)return varchar is
i number;
flag number;
begin
flag:=0;
for i in 2..n/2
loop
if mod(n,i)=0 then
flag:=1;
return 'Not prime';
end if;
end loop;
if flag=0 then
return 'prime';
end if;
end prime;
function odd(n number)return varchar is
begin
if mod(n,2)=0 then
return 'even';
else
return 'odd';
end if;
end odd;
function positive(n number)return varchar is
begin
if n>0 then
return 'positive';
else
return 'negative';
end if;
end positive;
end packs;
Thus the PL/SQL block program using package is executed and verified.