432 - DBMS - Kishankumar Goud
432 - DBMS - Kishankumar Goud
PRACTICAL NO .01
Manipulating Data
1. CREATING TABLE:
Syntax:
create table tablename
(column1 datatype(size),
column2 datatype(size),
…….
columnN datatype(size)
);
OR
create table tablename(column1 datatype(size), column2 datatype(size),
…..columnN datatype(size));
2. DESCRIBING TABLE:
Syntax:
describe tablename;
OR
desc tablename;
Syntax:
insert into tablename values(data1, data2,…..dataN);
OR
insert into tablename values(data1,
data2,
……,
dataN);
Syntax:
a) For entire table:
select * from tablename;
b) For particular column:
select column from tablename;
c) For multiple columns:
select columnX, columnY,…..from tablename;
d) For particular record with all columns:
select * from tablename where column=’data’;
e) For particular record with particular column:
select column, column from tablename where columnM=’data’;
Syntax:
a) For one column:
insert into tablename (columnX) values (data);
b) For multiple columns:
insert into tablename (columnX, columnY) values (data1, data2);
Syntax:
delete from tablename
where column=’data’;
Syntax:
delete from tablename;
Syntax:
update tablename
set columnA=’newdata’
where column=’data’;
Syntax:
a) One column:
alter table tablename
add (column datatype(size));
b) Multiple column:
alter table tablename
add (column datatype (size)
column datatype (size)
….);
Syntax:
Syntax:
alter table tablename
rename column oldcolumnname to newcolumnname;
Syntax:
rename oldtablename to newtablename;
Syntax:
alter table tablename
drop column columnname;
Syntax:
drop table tablename;
Output:
(104, 'Finanace','Borivali(W)');
insert into dept_53 values
(105, 'Sales','Bandra(E)');
Output:
Output:
Output:
Output:
Output:
PRACTICAL NO .02
Creating and Managing Tables
AIM: a) Creating and Managing Tables
b) Including Constraints
THEORY: CONSTRAINTS
Constraints enforces limits to the data or the type of data that can be
inserted into, updated or deleted from a table.
The purpose of constraints is to maintain data integrity in insertion,
updation or deletion of a table.
TYPES OF CONSTRAINTS:
1. Not Null
2. Unique
3. Default
4. Check
5. Primary Key
6. Foreign Key
1. NOT NULL:
It makes sure that a column does not hold a null value.
When we do not provide values for a particular column while inserting a
record it takes a null value.
By defining not null constraints, we can make sure that a particular
column will have values for all records.
Keyword: not null
2. UNIQUE:
If a column has this constraint, then that column will not have duplicate
values.
Keyword: unique
3. DEFAULT:
This constraint provides the default value to the column. When no value is
provided for a particular record, the default value is set.
Ex. For a particular table consisting column name city, has a default value
set as Mumbai. So when no value is entered for city for a particular record
while inserting, the default value Mumbai will be set as city for those
particular records.
Keyword: default
4. CHECK:
This constraint is used for specifying range of values for a particular
column of a table.
Ex 10<=age<=20
When this constraints is been set to a column, it ensures that the specific
column must have the values fitting into that range.
Keyword: check
5. PRIMARY KEY:
It uniquely identifies a particular record.
The constraints associated with primary key are:
1. not null
2. unique
6. FOREIGN KEY:
The primary key of one table when it is referenced into another table it is
known as Foreign key.
The keyword is references which is used to refer the primary key of
another table.
Keyword: references
OR
alter table tablename
add constraint cn1 constraint (columnP);
Output:
Output:
Output:
Output:
Output:
To check foreign key constraint, try to delete a column from parent table that
has reference in child table.
Query:
Insert a new record in parent table.
insert into stream_b2 values(3,’BA’);
Insert a new record in child table.
insert into student_b2 values(1004,’Joy’,’3’)
Output:
Output:
PRACTICAL NO .03
SQL Statements - I
AIM: a) Writing Basic SQL Select Statement
b) Restricting and Sorting data
c) Single Row Functions
2. WHERE CLAUSE:
3. DISTINCT CLAUSE:
Ex. Consider a situation where duplicate values are present for department name
column in Employee table. We want to know the department names for an
organization. We will not want to have the names repeated multiple times. In
such case distinct clause is very helpful.
Keyword: distinct
Syntax:
4. ORDER BY CLAUSE:
Ascending is the default sorting method. For displaying in descending order the
keyword desc is used.
Syntax:
6. CHARACTER FUNCTIONS:
7. NUMBER FUNCTION:
8. SUBSTRING:
Start position
n
Select empno,substr(fname,1,3) Name from emp1/2/3/4;
length
h
Q2) Display the firstname of all employees along with their ids.
Query:
select F_name,Emp_no from Emp_b1;
Output:
Q3) Display all records from employee table having salary equal to 22000.
Query:
select * from Emp_b1 where E_sal=22000;
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Q10) Combine the firstname and lastname of all the employees and display as
“Full name”.
Query:
select concat(F_name,L_name)"Full Name" from Emp_b1;
Output:
Output:
Output:
Output:
Q14) Display new salary of employee with 1.15% increment and also show the
increased amount.
Query:
select Emp_no,concat(F_name,L_name)"Full Name",E_sal,
(E_sal*1.15/100)"Increment" ,
(E_sal+(E_sal*1.15/100))"New Salary" from Emp_b1;
Output:
Output:
Substring
Query:
select substr(F_name,2,4) from Emp_b1;
Output:
Query:
select substr(F_name,1,3) from Emp_b1;
Output:
Round off
Query:
select round(8.454,1)from dual;
Output:
Query:
select round(8.454,-1)from dual;
Output:
Query:
select round(4.6444,2)from dual;
Output:
Query:
select round(4.6444,0)from dual;
Output:
Truncation
Query:
select trunc(4.6444,1)from dual;
Output:
Query:
select trunc(4.6444,-1)from dual;
Output:
Query:
select trunc(4.6444,0)from dual;
Output:
Modulus
Query:
select mod(15,6) from dual;
Output:
Query:
select mod(20,7) from dual;
Output:
PRACTICAL NO .04
SQL Statements - II
AIM: a) Displaying data from multiple tables
b) Aggregating data using group functions
c) Subqueries
It is often used with the group by clause of the select statement most commonly
used aggregate functions are as follows:
1. Min()
2. Max()
3. Sum()
4. Avg()
5. Count()
Syntax:
2. COUNT():
3. SUM()
Returns addition of all values of specified column of a table
Syntax:
4. MIN():
5. MAX():
6. AVG():
7. SUBQUERY:
Writing a query inside another query is known as subquery or nested query
Syntax:
select column A
from tablename1
where columnP operator (select column P
from tablename2
[where(condition)]);
Operators: = / < / > / in / like / …
There are two wildcards often used in conjunction with the LIKE operator:
8. JOINS:
It combines the matching and unmatching rows from two tables
Types
Inner join and Outer join
1) Left outer join: It displays unmatching records from left table and has null
value for right table columns, along with matching records from both tables.
Syntax:
2) Right outer join: It displays unmatching records from right table and has null
values for left table columns, along with matching records from both tables.
Syntax:
3) It displays all the matching rows from both left and right table along with the
unmatching records if present in either tables with null values.
Syntax:
Part – A
Displaying data from multiple tables.
);
Output:
Query:
insert into empb1 values(1001,'alice','cena',28000,35);
insert into empb1 values(1002,'bob','jose',22000,38);
insert into empb1 values (1003,'john','william',25000,35);
insert into empb1 values(1004,'alice','william',22000,38);
insert into empb1 values(1005,'jesty','jose',20000,38);
Output:
Query:
select count(Fname) from empb1 where Fname='alice';
Output:
Output:
Output:
Q4) Find the total salary of all employees having same firstname.
Query:
select sum(Esal), Fname from empb1 group by Fname;
Output:
Q5) Retrieve the total salary of employees based on same age group.
Query:
select sum (Esal),Eage from empb1 group by Eage;
Output:
Output:
Q7) Find minimum salary of all employees having same last name.
Query:
select Lname,min(Esal) from empb1 group by Lname;
Output:
Output:
Output:
Q10) Find the maximum age of all employees having same firstname.
Query:
select Fname,max(Eage) from empb1 group by Fname;
Output:
Output:
Output:
13) Find the average age of all employees having same salary.
Query:
select avg (Eage) from empb1 group by Esal;
Output:
Part -B
Aggregating data using group functions.
Query:
create table empb_1
(Empid int,
Fname char(15),
Lname varchar(20),
Esal int,
m_id int,
d_id int
);
Query:
insert into empb_1values (123,'Deep','Shah',50000,720,1401);
insert into empb_1values (250,'Bhavini','Shah',50000,123,1401);
insert into empb_1values (723,'Kreena','Shah',50000,450,1402);
insert into empb_1values (752,'Meena','Gala',20000,723,1402);
insert into empb_1values (562,'Teena','Bajaj',12000,456,1450);
insert into empb_1values (633,'Meena','Shah',18000,463,1450);
Query:
create table deptb_1
(d_id number(5),
d_name char(10),
m_id int,
loc_id int
);
Output:
Query:
insert into deptb_1 values(1401,'IT',123,501);
insert into deptb_1 values(1402,'Marketing',850,502);
insert into deptb_1 values(1403,'Shipping',752,503);
insert into deptb_1 values(1404,'sales',462,504);
Output:
Q15) Display full name of all employees who are having salary more than
“Meena Shah”.
Query:
select Empid,Esal,concat(Fname,Lname)"Full Name" from empb_1
where Esal>(select Esal from empb_1 where Fname='Meena' and
Lname='Shah');
Output:
Q16) Display names of all employees who are having salary same as “Deep”.
Query:
select concat(Fname,Lname)"Full name",Empid,Esal from empb_1
where Esal=(select Esal from empb_1 where Fname='Deep');
Output:
Output:
Q18) Display details of those employees who are having ‘a’ in their last name
and who have salary above average.
Query:
select concat(Fname,Lname) "Full Name",Esal,Empid from empb_1 where
Empid in (select Empid from empb_1 where Lname like '%a%') and Esal >
(select avg (Esal) from empb_1);
Output:
Output:
Output:
Part – C
Subqueries:
Q21) Display first name of all employees and their department names from
Employee and Department table.
Query:
select empb_1.d_id,fname,d_name from empb_1 left outer join deptb_1 on
empb_1.d_id=deptb_1.d_id;
Output:
Q22) Display first name of employees and their department names from
Employees and Department table for employee named “Meena”.
Query:
select fname,d_name from empb_1,deptb_1 where
empb_1.d_id=deptb_1.d_id and fname='Meena';
Q25) Display the all department details and all employee details.
Query:
select deptb_1.d_id, d_name, empid, fname, lname from empb_1
full outer join deptb_1 on empb_1.d_id=deptb_1.d_id;
Output:
PRACTICAL NO .05
Creating & Managing Other Database Objects
AIM: a) Creating views
b) Other database objects
c) Controlling user access
THEORY: 1. VIEWS:
Views are virtual tables which stores data as output of query expression.
It is similar to tables but a table has set of definition in which it actually
stores data whereas a view also has set of definition which is built on top
of table or other views.
Syntax:
create view viewname as (query expression);
1. VIEWS CONT.
Updating views: As views are virtual copy of table, they are replaced
when we say updated
Syntax: create or replace view viewname as (query expression);
Dropping View:
Syntax: drop view viewname;
It is a database object from which the user may generate unique integers.
It can be used to automatically generate primary key values.
These are generated independently so can be used for one or more tables.
Syntax:
create sequence seq_name
start with value
increment by value
maxvalue value
nocycle
nocache;
Once new user account is created, we can give/ add privileges to account
by using the grant statement.
It has many options hence it is a powerful statement.
Its core functionality is to manage the privilege of both user and role
throughout the database.
o Connect to a database
o Create table
Syntax:
A) System privilege: grant privilege to username;
B) Object privilege: grant privilege on object to username;
C) Creating role: create role rolename;
D) Role privilege: grant privilege on object to rolename;
E) Revoking privileges:
I – revoke privilege on object from username;
ii – revoke privilege on object from rolename;
Adding user to role
Syntax:
grant rolename to username;
Output:
Q2) Create a view “deptb_1_v1” of department table with only two departments
1401 and 1402.
Query:
create or replace view deptb_1_v1 as (select * from deptb_1 where d_id in
(1401,1402));
Output:
Output:
Q5) Update a view empb_1_v1 and set the d_id values as 1403 for d_id 1450.
Query:
update empb_1 set d_id=1403 where d_id=1450;
Output:
Output:
Q8) Check the current value and next value of empid sequence.
Query:
select emp_b1_seq1.nextval from dual;
Output:
Query:
select emp_b1_seq1.currval from dual;
Output:
Output:
Q12) Revoke the privilege of new_b1/2/3/4 to view the table emp_b1/2/3/4 (of
the system user)
Query:
GRANT SELECT ON empb_1 TO newb_1;
select * from system.empb_1;
Output:
PRACTICAL NO .06
Using Set Operators, Date/ time Functions, group By Clause
(Advanced features) & Advanced Subqueries
b) date/time Functions
c) Enhancements to the Group By clause
d) Advanced Subqueries
4. ADVANCED SUBQUERIES:
Department Table
SET OPERATORS:
Q1) Write a query to retrieved d_id’s present in employee and department table.
Query:
select D_Id from empb_1 union all select D_ID from deptb_1;
Output:
Q2) Write a query to retrieve unique d_id’s present in employee and department
table.
Query:
select D_ID from empb_1 union select D_ID from deptb_1;
Output:
Q3) Write a query to retrieve all d_id’s who are having employees.
Query:
select D_ID from empb_1 intersect select D_ID from deptb_1;
Output:
Q4) Write a query to retrieve all m_id’s which are present in employee table but
not in department table.
Query:
select M_ID from empb_1 minus select M_ID from deptb_1;
Output:
Query:
select current_date from dual;
Output:
Query:
select last_day(sysdate) from dual;
Output:
Query:
select next_day(sysdate,'Monday') from dual;
Output:
Query:
select add_months(sysdate,7) from dual;
Output:
Query:
select systimestamp from dual;
Output:
Query:
select current_timestamp from dual;
Output:
Query:
select extract(year from sysdate) from dual;
Output:
Query:
select extract(month from sysdate) from dual;
Output:
Query:
select extract(day from sysdate)"Today's day" from dual;
Output:
GROUP BY ROLL UP
Q6) Display subtotal values of salaries by department id’s and by manager id’s
of depts. 1401, 1402, 1403 using rollup operator.
Query:
select D_ID,M_Id,sum(Esal)
from empb_1
where D_ID in(1401,1402,1403)
group by rollup(D_ID,M_ID);
Output:
GROUP BY CUBE
Q7) Display subtotal values of salaries by department id’s and by manager id’s
of depts. 1401, 1402, 1403 using cube operator.
Query:
select D_ID,M_Id,sum(Esal)
from empb_1
where D_ID in(1401,1402,1403)
group by cube(D_ID,M_ID);
Output:
Q8) Display details of those employees who earn less than average salary of
their department using subquery.
Query:
select empid,fname,lname,d_id from empb_1 E
where esal<(select avg(esal) from empb_1 where d_id=E.d_id);
Output:
Q9) Display count of all employees whose last name begin with character ‘s’.
Query:
Q11) Retrieve the lowest paid employees of their department using co related
subquery.
Query:
select fname,esal,d_id from empb_1 E1 where
E1.esal in(select min(esal) from empb_1 E2 where E1.d_id=E2.d_id);
Output:
Q13) Retrieve the d_id's where the average salary of each department less than
the average salary for all employees.
Query:
select d_id ,avg(esal) from empb_1 group by d_id
having avg(esal) < (select avg(esal) from empb_1);
Output:
PRACTICAL NO .07
Creating Database Triggers
THEORY: 1. TRIGGERS:
A trigger is a PL/SQL block structure which is fired when a DML statement
like Insert, Update and Delete or a database operation is executed on a
database table.
A trigger is triggered automatically when the statement is executed.
Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE/AFTER/INSTEAD OF} event
[OF col_name]
ON table_name
[FOR EACH ROW/FOR EACH STATEMENT]
[WHEN (condition)]
DECLARE
declaration-statements;
BEGIN
statements;
END;
/
1. Row Level Trigger- Action is taken for each row created, updated or
deleted.
2. Statement Level Trigger- Action is taken for each SQL Statement
executed.
Hierarchy of Trigger execution
1. Before Statement Level
2. Before Row Level
3. After Row Level
4. After Statement Level
Department Table
Q1) Create a trigger to update salary of employee and show the difference
between updated and existing salary.
Query:
> set serveroutput on;
create or replace trigger batch_b1
before update on empb_1
for each row
when(new.esal>0)
DECLARE
sd number;
BEGIN
sd := :new.esal - :old.esal;
dbms_output.put_line('Salary Difference=' || sd);
END;
/
Output:
Updating salary of
employee to show
the difference
between updated
and existing salary.
Query:
update empb_1
set esal=’38000’
where esal=’30000’;
Output:
/
Output:
Query:
insert into empb_1 values(850,'Taehyung','Kim',25000,545,1490);
Q3) Create a trigger to insert the deleted records of employee table in backup
table.
Query:
First we will create the backup table to store the deleted records.
create table emp_backup_b1
(Empid int,
Fname char(15),
Lname varchar(20),
Esal int,
m_id int,
d_id int
);
Output:
Query:
create or replace trigger trg_delb1
after delete
on empb_1
for each row
BEGIN
insert into emp_backup_b1 values(:old.empid,:old.fname,:old.lname,
:old.esal,:old.m_id,:old.d_id);
END;
/
Output:
PRACTICAL NO .08
PL-SQL Basics
result :=a+b;
dbms_output.put_line('Addition of '|| a ||' and '||b ||' is ' ||result);
END;
/
Output:
Q2) Write a PL_SQl program to find largest of two numbers using simple if
statement.
Query:
DECLARE
a number;
b number;
BEGIN
a := &a;
b :=&b;
if (a>b) then
dbms_output.put_line('A is greater than B');
end if;
if(b>a) then
dbms_output.put_line('B is greater than A');
end if;
END;
/
Output:
a :=1;
while(a<11)
LOOP
dbms_output.put_line(a);
a:= a+1;
END LOOP;
END;
/
Output:
Q4) Write a PL_SQl program to find factorial of entered number using loop.
Query:
DECLARE
n number;
i number;
fact number;
BEGIN
fact := 1;
n :=&n;
for i in 1..n
LOOP
fact := fact *i;
END LOOP;
dbms_output.put_line('Factorial for number '||n||' is '||fact);
END;
/
Output: