Dbms Lab Manual
Dbms Lab Manual
6. Develop a program that includes the features NESTED IF, CASE and CASE
expression. The program can be extended using the NULLIF and COALESCE
functions.
7. Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops
using ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE-
APPLICATION ERROR.
8. Programs development using creation of procedures, passing parameters IN and OUT
of PROCEDURES.
9. Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.
10. Develop programs using features parameters in a CURSOR, FOR UPDATE
CURSOR, WHERE CURRENT of clause and CURSOR variables.
11. Develop Programs using BEFORE and AFTER Triggers, Row and Statement
Triggers and INSTEAD OF Triggers
12. Create a table and perform the search operation on table using indexing and non-
indexing techniques.
13. Write a Java program that connects to a database using JDBC
14. Write a Java program to connect to a database using JDBC and insert values into it
15. Write a Java program to connect to a database using JDBC and delete values from it
EXERCISE -1
1. Creation, altering and dropping of tables and inserting rows into a table
(use constraints while creating tables) examples using SELECT command.
CREATION:
The SQL CREATE TABLE Statement The CREATE TABLE statement is used to create
a new table in a database.
Syntax:
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date,
etc.).
Example:
2
SQL> DESC PROG;
PROF1 VARCHAR2(20)
PROF2 VARCHAR2(20)
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table gets the same column definitions. All columns or specific columns can be
selected.
If you create a new table using an existing table, the new table will be filled with the
existing values from the old table.
Syntax:
Example:
Table created.
3
SQL>desc new_prog;
PROF1 VARCHAR2(20)
PROF2 VARCHAR2(20)
ALTERING:
The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table. You should also use the ALTER TABLE command to add and drop various
constraints on an existing table.
Syntax:
The basic syntax of an ALTER TABLE command to add a New Column in an existing table is
as follows.
Example:
SQL>ALTER TABLE PROG ADD PROGNO NUMBER(10);
Table altered.
The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as
follows.
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a
table is as follows.
4
SQL>ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column
in a table is as follows.
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.
The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table
is as follows.
The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a
table is as follows.
The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as
follows.
DROPING:
The SQL DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints and permission specifications for that table.
NOTE − You should be very careful while using this command because once a table is deleted
then all the information available in that table will also be lost forever.
Syntax:
Table Dropped.
5
EXERCISE -2
2. Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSET, Constraints. Example:- Select the roll
number and name of the student who secured fourth rank in the class.
The ANY and ALL operators are used with a WHERE or HAVING clause.
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax:
SQL>SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Example:
SQL> SELECT SName FROM STU1 WHERE SNO = ANY (SELECT SNO FROM STU1
WHERE SAGE = 20);
SNAME
RAMA
ALL Syntax:
SQL>SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Example:
SQL>SELECT SName FROM STU1 WHERE SNO = ALL (SELECT SNO FROM STU1
WHERE SAGE <20);
SNAME
KRISHNA
6
The SQL EXISTS Operator:
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.
Syntax:
SQL>SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example:
SQL> SELECT SNAME FROM STU1 WHERE EXISTS (SELECT SNO FROM STU WHERE
SNO = STU.SNO AND SAGE < 20);
SNAME
KRISHNA
The IN operator allows you to specify multiple values in a WHERE clause. The IN
Syntax:
Example:
7
SQL Constraints:
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the constraint
and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
Example:
8
EXERCISE -3
The SQL GROUP BY clause is used in collaboration with the SELECT statement to
arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a
SELECT statement and precedes the ORDER BY clause.
Syntax:
The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY
clause must follow the conditions in the WHERE clause and must precede the ORDER BY
clause if one is used.
Using group by, we can create groups of related information. Columns used in select must be
used with group by;otherwise it was not a group by expression.
6 rows selected.
CLERK
SALESMAN
SR.SALESMAN
MANAGER
9
SQL> select job,SUM(SAL) from EMP group by job;
JOB SUM(SAL)
CLERK 8000
SALESMAN 8000
SR.SALESMAN 34000.55
MANAGER 75000
HAVING:
The HAVING Clause enables you to specify conditions that filter which group results
appear in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING
clause places conditions on groups created by the GROUP BY clause.
Syntax:
The following code block shows the position of the HAVING Clause in a query.
The HAVING clause must follow the GROUP BY clause in a query and must also
precede the ORDER BY clause if used. The following code block has the syntax of the SELECT
statement including the HAVING clause −
10
SUM, MAX, AVG, COUNT FUNCTIONS:
SUM:
Syntax:
SQL>SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example:
SUM(SAL)
120500.55
MAX:
The MAX() function returns the largest value of the selected column.
Syntax:
SQL>SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example:
MAX(SAL)
75000
MIN:
The MIN() function returns the smallest value of the selected column.
11
Example:
MIN(SAL)
5000
AVERAGE:
Syntax:
SQL>SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example:
AVG(SAL)
20083.425
COUNT:
The COUNT() function returns the number of rows that matches a specified criteria.
Syntax:
SQL>SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example:
COUNT(SAL)
12
VIEWS:
A view is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a predefined SQL
query.
A view can contain all rows of a table or select rows from a table. A view can be created
from one or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
CREATION OF A VIEW:
Database views are created using the CREATE VIEW statement. Views can be created
from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the
specific implementation.
Example:
View Created.
13
DESCRIPTION OF VIEW
EMPLOYEE_NAME VARCHAR2(10)
E MPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DROP A VIEW:
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed.
Syntax:
Example:
14
EXERCISE -4
Conversion functions:
SQL Conversion functions are single row functions which are capable of typecasting
column value, literal or an expression . TO_CHAR, TO_NUMBER and TO_DATE are the three
functions which perform cross modification of data types.
TO_CHAR function:
TO_CHAR function is used to typecast a numeric or date input to character type with a
format model (optional).
Syntax:
Example:
SQL> SELECT first_name,
TO_CHAR (hire_date, 'MONTH DD, YYYY') HIRE_DATE,
TO_CHAR (salary, '$99999.99') Salary
FROM employees
WHERE rownum < 5;
TO_NUMBER function:
Syntax:
15
Example:
TO_NUMBER('121.23','9G999D99')
121.23
TO_DATE function:
The function takes character values as input and returns formatted date equivalent of the
same. The TO_DATE function allows users to enter a date in any format, and then it converts the
entry into the default format used by Oracle 11g.
Syntax:
Example:
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MIA.M.',
'NLS_DATE_LANGUAGE = American') FROM DUAL;
TO_DATE('
15-JAN-89
CHARACTER/STRING FUNCTION:
CONCATENTION:
Returns concatenated string
CONCAT(SAI,TIRUMALA)
SAI TIRUMALA
16
LPAD:
Returns the string argument, left-padded with the specified string
***hai
RPAD:
Appends string the specified number of times
hai***
UPPER:
Converts to uppercase
UPPER(‘WELCOME’)
WELCOME
LOWER:
Returns the argument in lowercase
Hai
INITCAP:
INITCAP returns char, with the first letter of each word in uppercase, all other
letters in lowercase. Words are delimited by white space or characters that are not
alphanumeric.
char can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or VARCHAR2. The
return value is the same datatype as char.
Hello World
17
LTRIM:
Removes leading spaces
RTRIM:
Removes trailing spaces
Hai
LENGTH:
The LENGTH() function returns the length of the value in a text field.
SUBSTRING:
The forms without a len argument return a substring from string str starting at
position pos. The forms with a len argument return a substring len characters long from string
str, starting at position pos. The forms that use FROM are standard SQL syntax. It is also
possible to use a negative value for pos. In this case, the beginning of the substring is pos
characters from the end of the string, rather than the beginning. A negative value may be used for
pos in any of the forms of this function.
TIRU
18
DATE & TIME FUNCTION:
SYSDATE:
Returns the time at which the function executes.
SQL> select sysdate from dual;
SYSDATE
07-APR-10
ADD_MONTHS:
ADD_MONTHS function adds the specified number of months to a
datetime value
SQL> select add_months(sysdate,3)from dual;
ADD_MONTH
-
07-JUL-10
LAST_DAY:
Returns the last day of the month for the argument
30-APR-10
MONTHS_BETWEEN:
Example:
Months
1.03225806
19
GREATEST:
SQL>SELECT GREATEST(’01-JAN-98’,’10-DEC-97’) FROM DUAL; GREATEST(
10-DEC-97
LEAST:
LEAST('01
01-JAN-98
NEXT_DAY:
NEXT_DAY returns the date of the first weekday named by char that is later
than the date date. The return type is always DATE, regardless of the datatype of date. The
argument char must be a day of the week in the date language of your session, either the full
name or the abbreviation. The minimum number of letters required is the number of letters in the
abbreviated version. Any characters immediately following the valid abbreviation are ignored.
The return value has the same hours, minutes, and seconds component as the argument date.
13-APR-10
ROUND:
The ROUND() function is used to get the date rounded to the unit specified by the
format model. It operates according to the rules of the Gregorian calendar.
07-APR-10
20
TO_CHAR:
SQL>SELECT TO_CHAR(CURRENT_DATE, 'DD-MON-YYYY HH:MI:SS') FROM DUAL;
TO_CHAR(CURRENT_DATE 24-
SEP-2017 04:04:57
TRUNC:
- first day of the month
SQL> SELECT TO_CHAR(TRUNC(SYSDATE, 'MM'), 'DD-MON-YYYY HH:MI:SS')
FROM DUAL;
TO_CHAR(TRUNC(SYSDAT 01-
SEP-2017 12:00:00
TO_DATE:
-- Specify a datetime string and its exact format
05-JUN-12
21
EXERCISE -5
SQL> DECLARE
c_id student.id%type;
c_name student.sname%type;
c_addr student.address%type;
c_grade student.grade%type;
BEGIN
SELECT sname, address INTO c_name, c_addr
FROM student WHERE id = c_id;
If( c_grade ='a') then
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
End if;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such record');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
No such record
PL/SQL procedure successfully completed.
22
ii)Insert data into student table and use COMMIT, ROLLBACK and
SAVEPOINT in PL/SQL block.
Commit:
The COMMIT statement to make changes permanent save to a database during the
current transaction and visible to other users,
Syntax :
Commit comments are only supported for backward compatibility. In a future release
commit comment will come to a deprecated.
Commit Example:
SQL> BEGIN
WHERE sname='raju';
COMMIT;
END;
1 akhil nrt b
2 balu sap d
3 raju cpt c
23
ROLLBACK:
The ROLLBACK statement ends the current transaction and undoes any changes made
during that transaction. If you make a mistake, such as deleting the wrong row from a table, a
rollback restores the original data. If you cannot finish a transaction because an exception is
raised or a SQL statement fails, a rollback lets you take corrective action and perhaps start over.
ROLLBACK Syntax:
ROLLBACK Example :
SQL> DECLARE
C_id STUDENT.id%TYPE;
BEGIN
SAVEPOINT sp1;
EXCEPTION
ROLLBACK TO sp1;
END;
24
SAVEPOINT:
SAVEPOINT Syntax :
SQL>SAVEPOINT SAVEPOINT_NAME;
SAVEPOINT Example :
SQL> DECLARE
C_id STUDENT.id%TYPE;
BEGIN
SAVEPOINT sp1;
EXCEPTION
ROLLBACK TO sp1;
END;
25
EXERCISE -6
6. Develop a program that includes the features NESTED IF, CASE and
CASE expression. The program can be extended using the NULLIF and
COALESCE functions.
NESTED IF:
It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you
can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).
Syntax:
SQL>DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname ='ACCOUNTING';
if dno = 10 then
dbms_output.put_line('Location is NEW YORK');
elsif dno = 20 then
dbms_output.put_line('Location is DALLAS');
elsif dno = 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end if;
END;
/
26
CASE:
In SQL ,the CASE statement has the functionality of an IF-THEN-ELSE statement. You
can use the CASE statement within a SQL statement.
Syntax:
SQL> Case test-variable
When value 1 then sequence of statements;
When value 2 then sequence of statements;
When value n then sequence of statements;
Else sequence of statements;
End case;
Example:
SQL> DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname ='ACCOUNTING';
case dno
when 10 then
dbms_output.put_line('Location is NEWYORK');
when 20 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end case;
END;
/
27
CASE WITHOUT ELSE:
Syntax:
SQL>Case test-variable
When value-1 then sequence of statements;
When value-2 then sequence of statements;
……
When value-n then sequence of statements;
End case;
Example:
SQL>DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname ='ACCOUNTING';
case dno
when 10 then
dbms_output.put_line('Location is NEWYORK');
when 20 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
when 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
/
28
EXERCISE -7
SQL>DECLARE
name VARCHAR2(20) := 'SMYTHE';
answer VARCHAR2(3) := 'NO';
suffix NUMBER := 1;
BEGIN
FOR i IN 1..5 LOOP -- Try transaction at most 5 times.
29
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE(' failed; trying again.');
ROLLBACK TO start_transaction; -- Undo changes.
suffix := suffix + 1; -- Try to fix problem.
name := name || TO_CHAR(suffix);
END; -- sub-block ends
END LOOP;
END;
/
SQL>DECLARE
name VARCHAR2(20) := 'SMYTHE';
answer VARCHAR2(3) := 'NO';
suffix NUMBER := 1;
BEGIN
WHILE i< 5 LOOP -- Try transaction at most 5 times.
DBMS_OUTPUT.PUT('Try #' || i);
30
BEGIN -- sub-block begins
SAVEPOINT start_transaction;
-- transaction begins
DELETE FROM results WHERE res_answer = 'NO';
INSERT INTO results (res_name, res_answer) VALUES (name, answer);
-- Nonunique name raises DUP_VAL_ON_INDEX.
-- If transaction succeeded:
COMMIT;
DBMS_OUTPUT.PUT_LINE(' succeeded.');
EXIT;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE(' failed; trying again.');
ROLLBACK TO start_transaction; -- Undo changes.
suffix := suffix + 1; -- Try to fix problem.
name := name || TO_CHAR(suffix);
END; -- sub-block ends
i:=i+1;
END LOOP;
END;
/
31
EXERCISE -8
Procedures − These subprograms do not return a value directly; mainly used to perform an
action.
Creating a Procedure:
Syntax:
The following table lists out the parameter modes in PL/SQL subprograms −
IN:
OUT:
An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value and reference the value after
assigning it. The actual parameter must be variable and it is passed by value.
IN OUT:
32
SQL> DECLARE
a number;
b number;
c number;
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
END;
MINIMUM OF(23,45) : 23
33
EXERCISE -9
RETURN return_datatype
{IS | AS}
BEGIN
<function_body>
END [function_name];
6 Komal 22 MP 4500.00
34
SQL>CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
FROM customers;
RETURN total;
END;
Function created.
Calling a Function:
SQL> DECLARE
c number(2);
BEGIN
c := totalCustomers();
END;
35
Invoking a Simple PL/SQL Function:
SQL> DECLARE
a number;
b number;
c number;
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
36
Maximum of (23,45): 45
Complex function:
SQL>DECLARE
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
END;
Factorial 6 is 720
37
EXERCISE -10
10. Develop programs using features parameters in a CURSOR, FOR
UPDATE CURSOR, WHERE CURRENT of clause and CURSOR
variables.
6 Komal 22 MP 4500.00
PARAMETERS IN CURSOR:
SQL>DECLARE
c_idcustomers.id%type;
c_namecustomerS.No.ame%type;
c_addrcustomers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
38
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
UPDATE CURSOR:
SQL>DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
6 customers selected
39
EXERCISE -11
11. Develop Programs using BEFORE and AFTER Triggers, Row and
Statement Triggers and INSTEAD OF Triggers.
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
− This specifies when the trigger will be executed. The INSTEAD OF clause is
used for creating trigger on a view
40
BEFORE INSERT Trigger:
Description
A BEFORE INSERT Trigger means that Oracle will fire this trigger before the
INSERT operation is executed.
Syntax:
41
-- Update create_date field to current system date
:new.create_date := sysdate;
-- Update created_by field to the username of the person performing the
INSERT
:new.created_by := v_username;
END;
/
Trigger created.
An AFTER INSERT Trigger means that Oracle will fire this trigger after the INSERT
operation is executed.
Syntax:
Example:
SQL> CREATE TABLE orders
( order_id number(5),
quantity number(4),
cost_per_item number(6,2),
total_cost number(8,2)
);
Table Created
SQL> CREATE OR REPLACE TRIGGER orders_after_insert
AFTER INSERT
ON orders
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
-- Find username of person performing the INSERT into the table
42
SELECT user INTO v_username
FROM dual;
-- Insert record into audit table
INSERT INTO orders_audit
( order_id,
quantity,
cost_per_item,
total_cost,
username )
VALUES
( :new.order_id,
:new.quantity,
:new.cost_per_item,
:new.total_cost,
v_username );
END;
/
ROW AND STATEMENT TRIGGERS:
A trigger if specified FOR EACH ROW; it is fired for each of the table being affected by the
triggering statement. For example if a trigger needs to be fired when rows of a table are deleted,
it will be fired as many times the rows are deleted. If FOR
EACH ROW is not specified, it is application to a statement and the trigger is executed at a
statement level.
Row-level:
They get fired once for each row in a table affected by the statements.
Statement-level:
INSTEAD OF INSERT triggers can be defined on a view or table to replace the standard
action of the INSERT statement. Usually, the INSTEAD OF INSERT trigger is defined on a
view to insert data into one or more base tables.
43
SQL>CREATE TABLE BaseTable (
ID number(10) PRIMARY KEY ,
Color varchar2(10) NOT NULL,
Material varchar2(10) NOT NULL,
);
Table Created.
--Create a view that contains all columns from the base table.
SQL>CREATE VIEW InsteadView AS SELECT ID, Color, Material FROM BaseTable;
View Created.
Trigger Created.
44
EXERCISE-12
12. Create a table and perform the search operation on table using
indexing and non-indexing techniques.
Just like we have index present in the textbooks to help us find the particular topic in the book,
Oracle index behaves the same way, we have different types of indexes in oracle.
Indexes are used to search the rows in the oracle table quickly. If the index is not present the select
quiry has to read the whole table and return the rows. With index,the rows can be retrieved quickly.
Create an Index
Syntax
UNIQUE it indicates that the combination of values in the indexed columns must be unique.
Table _name The name of the table in which to create the index.
Column1, column2, … column_n The columns to use in the index.
EXAMPLE:
Output:
Index created.
45