Professional Documents
Culture Documents
Institute of Engineering and Management
Institute of Engineering and Management
Department of
Computer Science and Engineering
Lab Manual
Syllabus
Contact: 3P
Credits: 2
1. Structured Query Language
➢ Creating Database
➢ Creating a Database
➢ Creating a Table
➢ Specifying Relational Data Types
➢ Specifying Constraints
➢ Creating Indexes
2. Table and Record Handling
➢ INSERT statement
➢ Using SELECT and INSERT together
➢ DELETE, UPDATE, TRUNCATE statements
➢ DROP, ALTER statements
3. Retrieving Data from a Database
➢ The SELECT statement
➢ Using the WHERE clause
➢ Using Logical Operators in the WHERE clause
➢ Using IN, BETWEEN, LIKE , ORDER BY, GROUP BY and
HAVING
➢ Clause
➢ Using Aggregate Functions
➢ Combining Tables Using JOINS
➢ Subqueries
4. Database Management
➢ Creating Views
➢ Creating Column Aliases
➢ Creating Database Users
➢ Using GRANT and REVOKE
Cursors in Oracle PL / SQL
Writing Oracle PL / SQL Stored Procedures
2
CSE DBMS Lab Manual
Oracle Class I
AIM:
To create a DDL to perform creation of table, alter, modify and drop column.
DDL COMMANDS
1.The Create Table Command: - it defines each column of the table uniquely.
Each column has minimum of three attributes, a name , data type and size.
Syntax:
a) Add new
columns Syntax:
Syntax:
Alter table <tablename> drop column <col>; Ex:alter table emp drop
column sal;
Syntax:
3
CSE DBMS Lab Manual
7.Destroying tables.
CREATION OF TABLE:
EXAMPLE:
4
CSE DBMS Lab Manual
SYNTAX:
alter table <tablename> add (col1 datatype, col2 datatype..);
OUTPUT:
2 Sharmi Tennis 19
ALTER TABLE WITH MODIFY:
SYNTAX:
EXAMPLE:
SQL> alter table student modify (id number(6), game varchar(25));
OUTPUT:
MODIFY desc student;
DROP:
SYNTAX: drop table<tablename>;
EXAMPLE:
SQL>drop table student; SQL>Table dropped
5
CSE DBMS Lab Manual
TRUNCATE TABLE
CONSTRAINTS:
DOMAIN INTEGRITY
Example: Create table cust(custid number(6) not null, name char(10)); Alter
table cust modify (name not null);
CHECK CONSTRAINT
Example: Create table student (regno number (6), mark number (3)
constraint b check (mark
>=0 and mark <=100)); Alter table student add constraint
b2 check (length(regno<=4));
6
CSE DBMS Lab Manual
ENTITY INTEGRITY
Assignment -I
4. create the emp1 table with ename and empno, add constraints to
check the empno value while entering (i.e) empno > 100.
Output-
7
CSE DBMS Lab Manual
Oracle Class II
SELECT
• Selecting some of the columns -> Projection
• Alias names if contains space or special symbol , then it needs to be put
in
double quotes
• Distinct and unique can be used to remove duplicates comparison
operators =; !=
or <>; <; >;<=, => are allowed in the conditions of a where clause.
• One useful query to get the number of queries is count(*)
• Order by , by default gives result in ascending order
• For string type of data like can be used.
• | | is used as a concatenation operator for strings and string literal is to be
enclosed within single quotes.
• Multiple conditions can be concatenated using and or etc
• for range queries we can use between and .
• Example : Select emailto, email from email where size between 10 and
20;
• IN for multiple values
• Select city, population from citydetails where city in
(‘kol’,’mum’,’del’,’chn’);
Similarly not in can be used
• Like to be used for pattern matching ‘a%’,‘%a%’ and ‘%a’
• An input value can be taken form the user , using and &
• select * from dept where deptno=&no;
• Syntax -
[DISTINCT | UNIQUE] (*, columnname [ AS alias], …) FROM
tablename [WHERE
condition] [GROUP BY
group_by_expression]
[HAVING group_condition]
[ORDER BY columnname];
Case sensitivity,whitespace, terminators
• SQL commands have the same meaning whether used with uppercase or
lowercase characters
• various SQL elements, or "words", must be separated by
whitespace (usually a "space" character), the use of extra spaces,
tabs, and end-of-line character has
little effect on the syntactical correctness of the statement.
8
CSE DBMS Lab Manual
The only column in dual is DUMMY, and the only row value
is X. Select sysdate from dual;
Assignment -II
1. Write query to select all the columns of emp table.
2. Write query to select only Empname, Ename andJob.
3. Write query to select unique Jobs.
4. write query to select only those employees who are salesman
5. select employee name , grade and salary , in the order of their salary
6. Mgmt is considering a pay raise , however they want to find out , if they
give a flat 200$ increment to all , then what % each person is getting . So
in your result display , ename , salary and pctincr
7. Express work experience of each of the employees by using sysdate and
hiredate in terms of no of years.
Hints : you would need to use cast ; use emp table and use different columns
and string concatenation to display a message like below for each of the
employees
9
CSE DBMS Lab Manual
Output Example :
• use emp table to display only those employees who have joined
in the year 80 and 81.
Output:
10
CSE DBMS Lab Manual
Group By]
• Group by The result will return # rows based in the group columns, basically based
• Some aggregate functions needs to be used on the columns. Example : Sum, Avg, Min, Max
, count(*) etc
Syntax-
Select <column(s)>
from <table(s)>
[where <condition>]
Insert/Update/Delete
• For each of the listed columns, a corresponding (matching) value must be specified.
• Insertion does not necessarily have to follow the order of the attributes as
specified in the create table statement
11
CSE DBMS Lab Manual
[where <condition>];
• Upper • Lower
• Initcap • Length
• Lpad • Rpad
• Rtrim • • Ltrim
Syntax-
• SQL commands have the same meaning whether used with uppercase or lowercase
characters
• In Oracle SQL, two statement terminators can be used; the semicolon (;) and the
forward slash (/). The two are similar in their use, the main difference being that the
forward slash can only be used on a separate line.
• Aliasing:
12
CSE DBMS Lab Manual
Set operators
• Both the sets need to have the same no of columns and compatible datatypes
Assignment -III
d. Apart from ‘Delete’ a‘Truncate’ statement can also be used for deleting
the rows. Comment on their difference.
g. You want to add a new row in the employees table with employee id
10000, First Name = ‘Scott’ , Last Name = ‘Tiger’ , Email = Stiger, Hire
Date , 01/02/2014, Job id PR_Prsdnt ( Title ‘Company President’ )
Department_id 280 ( Department_Name ‘Database’ ) Salary 50000
i. After the update is over in the email column , use instr and substr to
display email id and domain information separately.
j. Display day , month and year of the hire date of the employees.
13
CSE DBMS Lab Manual
Output
14
CSE DBMS Lab Manual
Oracle Class IV
Joins Subquery
Join
join query differs from a regular query in at least the following two ways:
that relates the rows of one table to the rows of another table.
Syntax
locations.state_province FROM
ON departments.location_id = locations.location_id;
Type of Joins
• Inner Join : Inner joins are the regular joins.An inner join returns the
rows that
• Outer Join : Outer joins are an extension to inner joins.An outer join
returns the rows that satisfy the join condition and also the rows from
one table for which no corresponding rows(i.e., that satisfy the join
15
CSE DBMS Lab Manual
when you don't specify a join condition when joining two tables
• Self joins
Subquery
16
CSE DBMS Lab Manual
• Scaler subqueries can be used for both where and having clause.
Correlated subquery
• With a correlated subquery, the database must run the subquery for
each evaluation because it is based on the outer query’s data.
Syntax-
select book_key, store_key, quantityfrom sales s
Where quantity <
(select max(quantity) from sales where book_key = s.book_key);
Syntax-
SELECT fname, lname FROM employee WHERE dept_id = 30 AND salary >= ALL
(SELECT salary FROM employee WHERE dept_id = 30);
SELECT fname, lname FROM employee WHERE dept_id = 30 AND NOT salary <
ANY (SELECT salary FROM employee WHERE dept_id = 30);
Assignment –IV
a. Display name of employees , department name and job name for each employee
b. Display the department name along with no of employees and average salary
of that department
c. For each department, find out no. of jobs the employees are assigned to.
d. Check for correctness of the above queries in terms of count, if you want
to bring in all entries, how would you achieve the same?
e. Group by the employees based on the first character of employee first
name. Display the results in alphabetic order (descending) of first
character.
Output-
18
CSE DBMS Lab Manual
Oracle Class V
PL/SQL basics
Architecture -
Single Unit-
What Is PL/SQL?
PL/SQL is a procedural programming language from Oracle that combines the following
elements:
19
CSE DBMS Lab Manual
Example – procedure
DECLARE
v_sal numeric(7,2); v_ename varchar(10); BEGIN
SELECT max(sal) INTO v_sal FROM emp;
20
CSE DBMS Lab Manual
Assignment –V
1. Create a function which takes two parameters table name and column name
and returns second max value of the columns.
Output-
21
CSE DBMS Lab Manual
Oracle Class VI
Exception Block Cursors, For Loops
Some exceptions
22
CSE DBMS Lab Manual
DECLARE
• Exception to indicate an error condition
• e_DuplicateAuthors EXCEPTION; RAISE e_DuplicateAuthors;
EXCEPTION
WHEN e_DuplicateAuthors THEN WHEN OTHERS THEN
Packages
Loops
DECLARE
v_count PLS_INTEGER := 0; BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Ah -- Much better'); v_count := v_count + 1;
EXIT WHEN v_count = 20;
END LOOP;
END;
/
END LOOP;
WHILE condition
LOOP
action;
END LOOP;
Cursor-
If data is added, deleted, or modified after the cursor is opened, the new
or changed data is not reflected in the cursor result set.
Declaration of a cursor:
CURSOR author_cur1
IS
SELECT rowid FROM authors WHERE id > 50;
Opening a cursor
OPEN author_cur1;
%FOUND
The %FOUND attribute tests whether a FETCH returned a
record.The return value is of Boolean type. If TRUE, a row was
returned by the FETCH. If FALSE, a row was not returned.
%ISOPEN
This attribute tests to see if a cursor is already open.If TRUE, the cursor is open.
If FALSE, it is not open.
%NOTFOUND
%NOTFOUND is the opposite of %FOUND. It returns TRUE if a row was
not returned by the FETCH and FALSE if one was returned.
%ROWCOUNT
This tests for the number of rows fetched from the cursor at any given time
and returns a number.
24
CSE DBMS Lab Manual
Fetch:
FETCH auth_cur INTO v_first_name, v_last_name, v_book_count; Exit:
EXIT WHEN auth_cur%NOTFOUND;
End Loop
END LOOP;
Close Cursor
CLOSE auth_cur;
Assignment –VI
1. Write a simple procedure , which executed now will return the time that of
two hours earlier
2. For emp table in scott, write a stored procedure that creates a table for each
unique department_id and stores the employee records that belong to that
particular department.
3. Create a stored procedure which given a table name will display the name of
the constraints available for the table. Handle all possible type of exception
4. Write a simple procedure, similar to previous assignments , given an email id , this
displays username and domain respectively , have correct messages displayed.
Output-
25
CSE DBMS Lab Manual
After a sequence has been created, you can access its values in SQL
statements with these
pseudocolumns:
• CURRVAL returns the current value of the sequence.
NEXTVAL increments the sequence and returns the new value
• We can use a maxvalue or minvalue to indicate the maximum value a
sequence can have
• CYCLE is used to indicate , if maxvalue is reached , then the values will
be cycled (NOCYCLE by default)
Example of sequence:
For each row in the database, the ROWID pseudocolumn returns the
address of the row.
Use of Rowid:
• They are the fastest way to access a single row.
• They can show you how the rows in a table are stored.
• They are unique identifiers for rows in a table.
26
CSE DBMS Lab Manual
Views
Use the CREATE VIEW statement to define a view, which is a logical table
based on one or more tables or views. A view contains no data itself.The
tables upon which a view is based are called base tables.
Types of View :
-Simple View
-Complex View
-Inline View
-Materialized View
Example :
Create view emp10 As select * from emp where deptno=10;
Exception
Differentiate error and exception
More example :
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE ('A number cannot be divided by zero.');
VALUE_ERROR : When there is conversion or type mismatch error.
TOO_MANY_ROWS : This exception is raised when a SELECT INTO
statement returns more than one row.
27
CSE DBMS Lab Manual
RAISE e_exception1
Assignment – VII(View)
1. Modify the procedure that takes salary and returns the name ,handle the handle
the exception so that if user gives a nonnumeric value this exits gracefully.
2. Create a table books, which has columns as bookid and bookname . Insert two rows
with booknames ‘database fundamentals’ and ‘database technologies’. Use a
sequence to populate the bookid for both therows.
3. Create a view , which hides the salary column from the user.
4. Cerate a view which has ename and dname respectively , check if you can update/insert
into the views , justify your results
Output-
28
CSE DBMS Lab Manual
Triggers
Syntax-
CREATE [OR REPLACE] TRIGGER Ttrigger_name
{BEFORE|AFTER} Triggering_event ON table_name
[FOR EACH ROW]
[FOLLOWS another_trigger]
Example-
CREATE OR REPLACE TRIGGER student_bi
BEFORE INSERT ON students FOR EACH ROW
DECLARE
sid int;
BEGIN
select max(stid)+1 into sid from students;
dbms_output.put_line('hello'); :new.stid:=sid;
END; /
29
CSE DBMS Lab Manual
Assignment – VIII(Trigger)
1. There is a circular from federal govt. no employees can get salary less than 1000$ .
So in case some employees are being inserted in the table with salary less than 1000
automatically this should be updated to 1000, Write a trigger for the same. Do it first
by a just changing the below in insert before , and also by an update command after
insert is done.
2. Create a trigger on emp table such that when a new employee is inserted with a
deptno that is new , first insert that record in department and then insert the same in
emp to avoid foreign key error.
Output-
30