0% found this document useful (0 votes)
8 views42 pages

DBMS Lab 2-2

The document outlines various SQL commands and concepts, including Data Definition Language (DDL), Data Query Language (DQL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL). It provides examples of creating, altering, and dropping tables, as well as inserting and querying data using various SQL functions and clauses. Additionally, it covers aggregate functions, conversion functions, and string manipulation functions within SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views42 pages

DBMS Lab 2-2

The document outlines various SQL commands and concepts, including Data Definition Language (DDL), Data Query Language (DQL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL). It provides examples of creating, altering, and dropping tables, as well as inserting and querying data using various SQL functions and clauses. Additionally, it covers aggregate functions, conversion functions, and string manipulation functions within SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

R23_DBMS LAB Programs 1 & 2

1. Creating, altering and dropping of tables and Inserting rows into a table.(Use Constraints while
Creating Tables) examples using SELECT Command.

AIM: By using SQL Queries, Creating, altering and dropping of tables and Inserting rows into a table.

DESCRIPTION:

SQL Languages: 5 Different Types of SQL Languages:

1. DDL or Data Definition Language. - Data definition language (DDL) is a collection of


SQL commands that are used to build, change, and delete database structures.
 CREATE – Creates a new database and objects, Such as a table, Index, view or
stored procedure
SYNTAX: CREATE TABLE TABLE_NAME (COLUMN1 DATATYPE1, COLUMN2 DATATYPE2,…..);

 ALTER – Add, Delete or Modifies Column an Existing table


SYNTAX: ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATATYPE;

 DROP – Used to drop an Existing table in a Database.


SYNTAX: DROP TABLE TABLE_NAME;

 TRUNCATE – Used to delete the data inside a table, but not the table itself.
SYNTAX: TRUNCATE TABLE TABLE_NAME;

 RENAME - It is used while renaming an existing object in the system of the


database.
SYNTAX: RENAME TABLE OLD_TABLE_NAME TO NEW_TABLE_NAME;

2. DQL or Data Query Language. – Data query language (DQL) is a set of SQL commands
that are used to query data inside schema objects
 SELECT – Retrieves data from a database
SYNTAX: SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE_NAME;

3. DML or Data Manipulation Language. – Refers to SQL instructions that deal with the
alteration of information stored within a database.
 INSERT – Adds new records to a table
SYNTAX: INSERT INTO TABLE_NAME (COLUMN1, COLUMN2) VALUES (VALUE1, VALUE2);

 UPDATE – Used to modify existing records in a table


SYNTAX: UPDATE TABLE_NAME SET COLUMN1=VALUE1, COLUMN2=VALUE2 WHERE CONDITION;

 DELETE – Removes records from a table


SYNTAX: DELETE FROM TABLE_NAME WHERE CONDITION;

4. DCL or Data Control Language. – Which primarily interact with the database system’s
rights, permits, and other restrictions?
 GRANT – Used to give specific privileges to users or roles.
SYNTAX: GRANT SELECT, INSERT ON TABLE_NAME TO USER_NAME;

 REVOKE – Used to take away privileges previously granted to users or roles.


Syntax: REVOKE SELECT, INSERT ON table_name from user_name;
5. TCL or Transaction Control Language. – A transaction is a collection of tasks that are
executed as a single entity.
 COMMIT - This command commits or terminates a transaction. It is used to
permanently save changes made during a transaction to the database.
Syntax: COMMIT;

 ROLLBACK - This command reverts a transaction if an error appears. It will


undo changes made during a transaction and are not saved to the database.
Syntax: ROLLBACK;

 SAVEPOINT - It creates a transaction save point. You can set a point within a
transaction to which you can later roll back. It does not rollback the entire
transaction but only up to a certain point.
Syntax: SAVEPOINT savepoint_name; /* Create a SAVEPOINT */
ROLLBACK TO SAVEPOINT savepoint_name; /* Rollback to the SAVEPOINT */

SQL QUERIES:

1. Create Table with Constraints


SQL>CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary > 0));

 Primary Key: Uniquely identifies each row in the table.


 NOT NULL: Ensures that the column cannot have null values.
 UNIQUE: Ensures that all values in the column are unique.
 CHECK: Ensures that the value satisfies a given condition.
 FOREIGN KEY: Links to a primary key of another table (referential integrity).

2. Inserting Rows into a Table


SQL>INSERT INTO Employees (EmployeeID, FirstName, LastName, Email, Salary)
VALUES
(1, 'John', 'Doe', '[email protected]', 55000.00),
(2, 'Jane', 'Smith', '[email protected]', 60000.00),
(3, 'Alice', 'Johnson', '[email protected]', 45000.00);

3. Select Command to Retrieve Data


SQL>SELECT * FROM Employees;

SQL>SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000;
(This will display the FirstName, LastName, and Salary for employees who have a salary greater
than 50,000)

4. Alter Table to Add a New Column


SQL>ALTER TABLE Employees ADD DateOfBirth DATE;

5. Alter Table to Modify an Existing Column


SQL>ALTER TABLE Employees MODIFY COLUMN Salary DECIMAL(12, 2);

6. Alter Table to Drop a Column


SQL>ALTER TABLE Employees DROP COLUMN DateOfBirth;

7. Drop Table
SQL>DROP TABLE Employees;

2. Queries (along with Sub Queries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT,
Constraints. Example: - Select the Roll No. & Name of the student who Secured fourth rank in the
class.

DESCRIPTION:

 ANY: Compares a value to any value in a subquery result set.


 ALL: Compares a value to all values in a subquery result set.
 IN: Checks if a value exists in a list of values from a subquery.
 EXISTS: Checks if a subquery returns any rows.
 NOT EXISTS: Checks if a subquery returns no rows.
 UNION: Combines two result sets and removes duplicates.
 INTERSECT: Returns common rows from two result sets.

SQL QUERIES:
We want to select the Roll No. & Name of the student who secured fourth rank in the class.
Let's assume you have a table Students with the following structure:
SQL>CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(100),
Marks INT);

SQL>INSERT INTO Students(RollNo,Name,Marks)


VALUES
(203,'Naresh', 1800),
(202,'Kumar', 1500),
(204,'Sravan', 1100),
(205,'Reddy', 1500),(206,'Naresh', 800),(207,'Deepika', 900),(208,'Saraswathi',
1200),(201,'Deepika', 1200);

SQL>Select *FROM Students;

1. Using Subqueries with ANY


SQL> SELECT RollNo, Name
FROM Students
WHERE Marks = ANY (SELECT DISTINCT Marks FROM Students);

2. Using Subqueries with ALL


SQL> SELECT RollNo, Name
FROM Students
WHERE Marks >= ALL (
SELECT DISTINCT Marks
FROM Students);
3. Using Subqueries with IN

IN allows you to check if a value exists in a list or result set.

SQL> SELECT RollNo, Name


FROM Students
WHERE Marks IN (
SELECT DISTINCT Marks
FROM Students);

4. Using Subqueries with EXISTS

EXISTS checks if the subquery returns any rows.

SQL> SELECT RollNo, Name


FROM Students s
WHERE EXISTS (
SELECT distinct Marks
WHERE s.Marks = 1100);

5. Using Subqueries with NOT EXISTS

NOT EXISTS checks if the subquery returns no rows.

SQL> SELECT RollNo, Name


FROM Students s
WHERE NOT EXISTS (
SELECT *
FROM Students
WHERE Marks > s.Marks)
AND EXISTS (
SELECT *
FROM Students
WHERE Marks = s.Marks);

6. Using UNION

UNION combines the result sets of two queries.

SQL> select RollNo,Name from Students UNION select EmployeeID, FirstName FROM Employees;
7. Using INTERSECT

INTERSECT returns the common rows from two queries.

SQL> select RollNo,Name from Students INTERSECT select EmployeeID, FirstName FROM
Employees;
R23_DBMS LAB Programs - 3

3. Queries using Aggregate Functions ( COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and
Creation and Dropping of Views.

AIM: By using SQL Queries, implement aggregate functions

DESCRIPTION:
Aggregate Functions: An aggregate function in SQL returns one value after calculating multiple column
values. We often use aggregate functions with the SELECT statement's GROUP BY and HAVING clauses.

There are five types of SQL aggregate functions:


 Count() - The COUNT() function returns the number of rows in a database table.
 Sum() - The SUM() function returns the total sum of a numeric column.
 Avg() - The AVG() function calculates the average of a set of values.
 Min() - The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL
values.
 Max() - The MAX() aggregate function returns the highest value (maximum) in a set of non-NULL
values.

SQL QUERIES:

>> Create table product(Pid int,Item_name varchar(30), Company varchar(30), Qty int,Rate
int, Cost int);
Command(s) completed successfully.

>> Insert into product (Pid,Item_name,Company,Qty,Rate,Cost)


values (1123,'Iphone-5s','Apple',2,50000,1000000),
(1134,'Realme Narzo','Realme',4,12000,48000),
(1154,'43-OLED TV','LG',3,27000,81000),
(1981,'22 watt LED Bulb','Crompton',9,250,2250),
(1876,'Geysers','Bajaj',5,3250,16250),
(1161,'Washing Machine','Realme',4,15000,20000)
(6 row(s) affected)

>> Select *From product

>> SELECT COUNT(*) FROM product


>> SELECT COUNT(*) FROM product WHERE RATE>=15000;

>> SELECT Company, COUNT(*) FROM product GROUP BY Company;

>> SELECT Company, COUNT(*) FROM product GROUP BY Company HAVING COUNT(*)>1;

>> SELECT SUM(COST) FROM product;

>> SELECT COMPANY, SUM(COST) FROM product GROUP BY COMPANY HAVING SUM(COST)>=12000;

>> SELECT AVG(COST) FROM product;

>> SELECT MAX(RATE) FROM product;

>> SELECT MIN(RATE) FROM product;


R23_DBMS LAB Programs - 4

4. Queries using Conversion Functions (to_char, to_number and to_date), String Functions
(Concatenation, lpad, rpad, ltim, lower, upper, initcap, length, substr and instr), Date Functions
(Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk, round, to_char,
to_date)

SQL QUERIES with DECRIPTION:

1. SQL CONVERSION FUNCTIONS:


SQL Conversion Functions, also known as data type conversion or casting functions,
are used to change the data type of a value from one type to another. As a user, we can use the
following two functions to convert explicitly.
 TO_CHAR()
 TO_DATE()
 TO_NUMBER()
1. TO_CHAR
Purpose: Converts a value (number, date, or other types) into a string. It's frequently used for
formatting dates and numbers.
Syntax: TO_CHAR (value, 'format')
For Dates: You can format a date into a string with a specific date format.
For Numbers: You can format a number into a string with a specific number format.

Examples:
Converting Date to String:
SQL>SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD') AS "Formatted Date" FROM dual;
This converts the current date into the string YYYY-MM-DD.
Converting Number to String:
SQL>SELECT TO_CHAR (12345.678, '99999.99') AS "Formatted Number" FROM dual;
This converts the number 12345.678 into the string '12345.68' (formatted as 99999.99).
Date with Time:
SQL>SELECT TO_CHAR (SYSDATE, 'DD-Mon-YYYY HH24:MI:SS') AS "Date with Time"
FROM dual;
This will output the current date and time in the format DD-Mon-YYYY HH24:MI:SS, e.g., 10-
Feb-2025 14:30:45.

2. TO_NUMBER
Purpose: Converts a string or other value to a numeric type (e.g., integer, decimal). It is
commonly used to convert a string to a number for mathematical operations or comparisons.
Syntax: TO_NUMBER (value, 'format')

Examples:
Converting String to Number:
SQL>SELECT TO_NUMBER ('12345.67') AS "Converted Number" FROM dual;
This converts the string '12345.67' to a numeric value 12345.67.
With Formatting:
SQL>SELECT TO_NUMBER ('1,234,567.89', '9,999,999.99') AS "Formatted Number" FROM
dual;
This converts the string '1,234,567.89' to the number 1234567.89, removing the commas.
Handling Invalid Input: If the string is not numeric, Oracle throws an error. To handle non-
numeric strings, use TO_NUMBER with the DEFAULT parameter:
SQL>SELECT TO_NUMBER ('abc', '999') DEFAULT 0 ON CONVERSION ERROR FROM
dual;
This will return 0 when the conversion fails.

3. TO_DATE
Purpose: Converts a string to a date using a specified date format.
Syntax: TO_DATE (string, 'format')

Examples:
Converting String to Date:
SQL>SELECT TO_DATE ('2025-02-10', 'YYYY-MM-DD') AS "Converted Date" FROM dual;
This converts the string '2025-02-10' into a date value.
Using Time in the Date:
SQL>SELECT TO_DATE ('2025-02-10 14:30:00', 'YYYY-MM-DD HH24:MI:SS') AS "Date
with Time" FROM dual;
This converts the string '2025-02-10 14:30:00' into a date-time value.
Converting Date to String: While TO_DATE converts strings to dates, you can use TO_CHAR
to convert a date back to a string in your desired format.

2. SQL STRING FUNCTIONS:


String functions in a Database Management System (DBMS) are operations used to
manipulate and modify text data within a database, allowing you to perform actions like extracting
substrings, converting case, concatenating strings, removing spaces, and more, commonly used in
SQL queries to process textual data within columns.

1. ASCII (): This function is used to find the ASCII value of a character.
Syntax: SELECT ascii('t');
Output: 116

2. CHAR_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server. This
function is used to find the length of a word.
Syntax: SELECT char_length ('Hello!');
Output: 6

3. CHARACTER_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server.
This function is used to find the length of a line.
Syntax: SELECT CHARACTER_LENGTH ('geeks for geeks');
Output: 15

4. CONCAT (): This function is used to add two words or strings.


Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;
Output: ‘GeeksforGeeks’

5. CONCAT_WS (): This function is used to add two words or strings with a symbol as
concatenating symbol.
Syntax: SELECT CONCAT_WS ('_', 'geeks', 'for', 'geeks');
Output: geeks_for_geeks

6. FIND_IN_SET (): This function is used to find a symbol from a set of symbols.
Syntax: SELECT FIND_IN_SET ('b', 'a, b, c, d, e, f');
Output: 2

7. FORMAT (): This function is used to display a number in the given format.
Syntax: Format ("0.981", "Percent");
Output: ‘98.10%’

8. INSERT (): This function is used to insert the data into a database.
Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000, 'abc');
Output: successfully updated

9. INSTR (): This function is used to find the occurrence of an alphabet.


Syntax: INSTR ('geeks for geeks', 'e');
Output: 2 (the first occurrence of ‘e’)
Syntax: INSTR ('geeks for geeks', 'e', 1, 2);
Output: 3 (the second occurrence of ‘e’)

10. LCASE (): This function is used to convert the given string into lower case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn

11. LEFT (): This function is used to SELECT a sub string from the left of given size or
characters.
Syntax: SELECT LEFT ('geeksforgeeks.org', 5);
Output: geeks

12. LENGTH (): This function is used to find the length of a word.
Syntax: LENGTH ('GeeksForGeeks');
Output: 13

13. LOCATE (): This function is used to find the nth position of the given word in a string.
Syntax: SELECT LOCATE ('for', 'geeksforgeeks', 1);
Output: 6

14. LOWER (): This function is used to convert the upper case string into lower case.
Syntax: SELECT LOWER ('GEEKSFORGEEKS.ORG');
Output: geeksforgeeks.org

15. LPAD (): This function is used to make the given string of the given size by adding the given
symbol.
Syntax: LPAD ('geeks', 8, '0');
Output: 000geeks

16. LTRIM (): This function is used to cut the given sub string from the original string.
Syntax: LTRIM ('123123geeks', '123');
Output: geeks

17. MID (): This function is to find a word from the given position and of the given size.
Syntax: Mid ("geeksforgeeks", 6, 2);
Output: for

18. POSITION (): This function is used to find position of the first occurrence of the given
alphabet.
Syntax: SELECT POSITION ('e' IN 'geeksforgeeks');
Output: 2

19. REPEAT (): This function is used to write the given string again and again till the number of
times mentioned.
Syntax: SELECT REPEAT ('geeks', 2);
Output: geeksgeeks

20. REPLACE (): This function is used to cut the given string by removing the given sub string.
Syntax: REPLACE ('123geeks123', '123');
Output: geeks

21. REVERSE (): This function is used to reverse a string.


Syntax: SELECT REVERSE ('geeksforgeeks.org');
Output: ‘gro.skeegrofskeeg’

22. RIGHT (): This function is used to SELECT a sub string from the right end of the given size.
Syntax: SELECT RIGHT ('geeksforgeeks.org', 4);
Output: ‘.org’

23. RPAD (): This function is used to make the given string as long as the given size by adding
the given symbol on the right.
Syntax: RPAD ('geeks', 8, '0');
Output: ‘geeks000’

24. RTRIM (): This function is used to cut the given sub string from the original string.
Syntax: RTRIM ('geeksxyxzyyy', 'xyz');
Output: ‘geeks’
25. SPACE (): This function is used to write the given number of spaces.
Syntax: SELECT SPACE (7);
Output: ‘ ‘

26. STRCMP (): This function is used to compare 2 strings.


If string1 and string2 are the same, the STRCMP function will return 0.
If string1 is smaller than string2, the STRCMP function will return -1. If string1 is larger than
string2, the STRCMP function will return 1.
Syntax: SELECT STRCMP ('google.com', 'geeksforgeeks.com');
Output: -1

27. SUBSTR (): This function is used to find a sub string from the a string from the given
position.
Syntax:SUBSTR('geeksforgeeks', 1, 5);
Output: ‘geeks’

28. SUBSTRING (): This function is used to find an alphabet from the mentioned size and the
given string.
Syntax: SELECT SUBSTRING ('GeeksForGeeks.org', 9, 1);
Output: ‘G’

29. SUBSTRING_INDEX (): This function is used to find a sub string before the given symbol.
Syntax: SELECT SUBSTRING_INDEX ('www.geeksforgeeks.org', '.', 1);
Output: ‘www’

30. TRIM (): This function is used to cut the given symbol from the string.
Syntax: TRIM (LEADING '0' FROM '000123');
Output: 123

31. UCASE (): This function is used to make the string in upper case.
Syntax: UCASE ("GeeksForGeeks");
Output: GEEKSFORGEEKS

3. SQL DATE FUNCTIONS:

Date functions are functions that help to format dates and carry out date-related calculations on
your data.

1. SYSDATE
Purpose: Returns the current date and time from the system where the database is running.
Syntax: SYSDATE
Example:
SQL>SELECT SYSDATE FROM dual;
This returns the current date and time (e.g., 2025-02-10 14:30:00).
2. NEXT_DAY
Purpose: Returns the date of the next specified day of the week after a given date.
Syntax: NEXT_DAY(date, 'day_of_week')
Example:
SQL>SELECT NEXT_DAY(SYSDATE, 'MONDAY') FROM dual;
This returns the next Monday after the current date.

3. ADD_MONTHS
Purpose: Adds a specified number of months to a date.
Syntax: ADD_MONTHS(date, num_months)
Example:
SQL>SELECT ADD_MONTHS(SYSDATE, 3) FROM dual;
This adds 3 months to the current date.

4. LAST_DAY
Purpose: Returns the last day of the month for a given date.
Syntax: LAST_DAY(date)
Example:
SQL>SELECT LAST_DAY(SYSDATE) FROM dual;
This returns the last day of the current month.

5. MONTHS_BETWEEN
Purpose: Returns the number of months between two dates.
Syntax: MONTHS_BETWEEN(date1, date2)
Example:
SQL>SELECT MONTHS_BETWEEN(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-
DD')) FROM dual;
This returns the number of months between the current date and January 1st, 2025.

6. LEAST
Purpose: Returns the smallest (earliest) date from a list of dates.
Syntax: LEAST(date1, date2, ...)
Example:
SQL>SELECT LEAST(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-DD'),
TO_DATE('2025-12-31', 'YYYY-MM-DD')) FROM dual;
This returns the earliest date from the given dates.

7. GREATEST
Purpose: Returns the largest (latest) date from a list of dates.
Syntax: GREATEST(date1, date2, ...)
Example:
SQL>SELECT GREATEST(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-DD'),
TO_DATE('2025-12-31', 'YYYY-MM-DD')) FROM dual;
This returns the latest date from the given dates.
8. TRUNC
Purpose: Truncates a date to a specified unit (e.g., day, month, year).
Syntax: TRUNC(date, 'format')
Example:
SQL>SELECT TRUNC(SYSDATE, 'MM') FROM dual;
This truncates the current date to the first day of the current month.

9. ROUND
Purpose: Rounds a date to a specified unit (e.g., day, month).
Syntax: ROUND(date, 'format')
Example:
SQL>SELECT ROUND(SYSDATE, 'MONTH') FROM dual;
This rounds the current date to the nearest month.

10. TO_CHAR
Purpose: Converts a date to a string format.
Syntax: TO_CHAR (date, 'format')
Example:
SQL>SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD') FROM dual;
This converts the current date to a string in the format YYYY-MM-DD.

11. TO_DATE
Purpose: Converts a string to a date.
Syntax: TO_DATE (string, 'format')
Example:
SQL>SELECT TO_DATE ('2025-02-10', 'YYYY-MM-DD') FROM dual;
This converts the string '2025-02-10' into a date.
R23_DBMS LAB Programs - 5

5.
I) create a simple PL/SQL Program which includes declaration section, executable section and exception-
Handling section (Ex. Student Marks can be selected from the table and printed for those who secured
first class and an exception can be raised if no records were found).

II) Insert Data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.

DESCRIPTION:
PL/SQL:

PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that
can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension
of SQL" that is used in Oracle.

Structure of PL/SQL Block:

Typically, each block performs a logical action in the program. A block has the following
structure:
DECLARE
Declaration statements;

BEGIN
Executable statements

EXCEPTIONS
Exception handling statements

END;

 Declare section starts with DECLARE keyword in which variables, constants, records as
cursors can be declared which stores data temporarily. It basically consists definition of
PL/SQL identifiers. This part of the code is optional.

 Execution section starts with BEGIN and ends with END keyword. This is a mandatory
section and here the program logic is written to perform any task like loops and conditional
statements. It supports all DML commands, DDL commands and SQL*PLUS built-in
functions as well.
 Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can be
handled in this section.

SQL QUERIES

i) we have to create the student table and insert the records in to the table as follows:

SQL> create table student(sid number(10),sname varchar2(20),rank varchar(10));


Table created.

SQL> insert into student values(501,'Ravi','second');


1 row created.

SQL> insert into student values(502,'Raju','third');


1 row created.

SQL> insert into student values(503,'Ramu','');


1 row created.

SQL> select *from student;

SID SNAME RANK

501 Ravi second


502 Raju third
503 Ramu

PL/SQL CODE:

SQL>ed 5a
Enter the following code into the text editor and save the file with .sql format
set serveroutput on;
DECLARE
temp1 number(10);
temp2 varchar2 (10);
BEGIN
Select sid,sname into temp1,temp2 from student where rank='first';
dbms_output.put_line('Student No:'|| temp1 ||' Name:'||temp2||' got first rank');
Exception when no_data_found then
dbms_output.put_line ('********************************************');
dbms_output.put_line('# Error: there is no student got first rank');
END;
/

SQL> @5a;
**********************************
**********
# Error: there is no student got first rank

PL/SQL procedure successfully completed.

SQL> update student set rank='first'


where sid=503; 1 row updated.

SQL> select *from student;

SID SNAME RANK

501 Ravi second


502 Raju third
503 Ramu first

SQL> @5a
Student No:503 Name:Ramu got first rank

PL/SQL procedure successfully completed.


ii) SQL> select *from student;

SID SNAME RANK

501 Ravi second


502 Raju third
503 Ramu first

PL/SQL CODE:

SQL>ed 5b
Enter the following code into the text editor and save the file with .sql format

set serveroutput on;


DECLARE
Sno student.sid%type;
Name student.sname%type;
srank student.rank%type;
BEGIN
sno := &sno;
Name: = '&name';
srank := '&srank';
INSERT into student values (sno,name,srank);
dbms_output.put_line('One record inserted');
COMMIT;
-- adding savepoint
SAVEPOINT s1;
-- Second time asking user for input
sno := &sno;
name: = '&name';
srank: = '&srank';
INSERT into student values (sno, name, srank);
dbms_output.put_line (‘one record inserted');
ROLLBACK TO SAVEPOINT s1;
END;
/

SQL> @5b
Enter value for sno: 504
Old 7 : Sno: = &sno;
New 7 : Sno: = 504;
Enter value for name: Naresh
Old 8: Name: = '&name';
New 8: Name: = 'Naresh';
Enter value for srank: first
Old 9: Srank: = '&srank';
New 9: Srank: = 'first';
One record inserted

Enter value for sno: 505


Old 16: Sno: = &sno;
New 16: Sno: = 505;
Enter value for name: Deepika
Old 17: Name: = '&name';
New 17: Name: = 'Deepika';
Enter value for srank: third
Old 18: Srank: = '&srank';
New 18: Srank: = 'third';
One record inserted

PL/SQL procedure successfully completed.

SQL> select *from student;

SID SNAME RANK

501 Ravi second


502 Raju third
503 Ramu first
504 Naresh first
505 Deepika third
R23_DBMS LAB Programs – 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.

A. NESTED IF:
A nested if-then is an if statement that is the target of another if statement. Nested if -then
statements mean an if statement inside another if statement
Syntax:-
if (condition1) then
-- Executes when condition1
is true if (condition2) then
-- Executes when condition2
is true end if;
end if;

PL/SQL CODE: PL/SQL Program to find biggest of three number using nested
if. SQL>ed 6a
Enter the following code into the text editor and save the file with .sql format

Declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c); if a>b AND a>c then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;
/

SQL> @6a
a=10 b=12 c=5
b is greatest

PL/SQL procedure successfully completed.


B. CASE and CASE Expression:

CASE statement selects one sequence of statements to execute. However, to select the
sequence, the CASE statement uses a selector rather than multiple Boolean expressions.
A selector is an expression, the value of which is used to select one of several
alternatives.
Syntax:
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;

SQL> create table emp(eno number(5), ename varchar2(10), loc varchar(10), salary
number(10,2));
Table created.
SQL> insert into emp values (101,'ali','vja', 15000);
1 row created.
SQL> insert into emp values (102,'ravi','hyd', 25000);
1 row created.
SQL> insert into emp values (103,'raju','gnt', 35000);
1 row created.
SQL> insert into emp values (104,'rakesh','vja', 45000);
1 row created.
SQL> select *from emp;

ENO ENAME LOC SALARY

101 ali vja 15000


102 ravi hyd 25000
103 raju gnt 35000
104 rakesh vja 45000

Example of CASE Expression:


SQL> select loc, case(loc) when 'vja' then salary+2000 when 'hyd' then salary+1000 else
salary end "rev_salary" from emp;
LOC rev_salary

vja 17000
hyd 26000
gnt 35000
vja 47000
PL/SQL CODE: PL/SQL CODE to demonstrate CASE

SQL> ed 6b

set serveroutput on;


declare
grade char(1);
begin
grade:='&grade'; case
when grade='a' then
dbms_output.put_line('Excellent');
when grade='b' then
dbms_output.put_line('very good');
when grade='c' then
dbms_output.put_line('good');
when grade='d' then
dbms_output.put_line('fair');
when grade='f' then
dbms_output.put_line('poor');
else
dbms_output.put_line('No such grade');
end case;
end;
/

SQL> @6b
Enter value for grade: c
old 4: grade:='&grade';
new 4: grade:='c'; good

PL/SQL procedure successfully completed.


C. NULLIF: Takes two arguments. If the two arguments are equal, then NULL is returned.
otherwise the first argument is returned.
Syntax:
select column_name, NULLIF(argument1,arguement2) from table_name;

Example:
SQL> select ename, nullif('ali','ali1') from emp;
ENAME NUL

ali ali
ravi ali
raju ali
rakesh ali

SQL> select ename, nullif('ali','ali') from emp;


ENAME NUL

ali
ravi
raju
rakesh

D. COALESCE: COALESCE () function accepts a list of arguments and returns the first one that
evaluates to a non-null value.
Syntax: coalesce ("expression1","expression2",...);

Example:
SQL> select coalesce (NULL,'CRRCOE','IT') from dual;
COALE
--------
CRRCOE
R23_DBMS LAB Program – 7

7. Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION
ERROR.

AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISEAPPLICATION ERROR.

WHILE LOOP: A WHILE LOOP statement in PL/SQL programming language repeatedly executes
a target statement as long as a given condition is true.
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;

PL/SQL Code: A PL/SQL Program to find sum of ODD number upto given number using While loop
SQL> ed 7a

set serveroutput on;


declare
inval number;
endval number;
s number default 0;
begin
inval:=1; endval:=&endval;
while inval<endval loop
s:=s+inval;
inval:=inval+2;
end loop;
dbms_output.put_line('sum of odd numbers between 1 and '||endval||' is '|| s);
end;
/

SQL> @7a
Enter value for endval: 100
Old 7: endval: =&endval;
New 7 : endval: =100;
Sum of odd numbers between 1 and 100 is 2500

PL/SQL procedure successfully completed.

FOR Loop: A FOR LOOP is a repetition control structure that allows us to efficiently write a
loop that needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value
LOOP sequence_of_statements;
END LOOP;
PL/SQL CODE: A PL/SQL code to print multiplication table using for loop
SQL> ed 7b

set serveroutput on;


DECLARE
VAR1 NUMBER;
VAR2 NUMBER;
BEGIN
dbms_output.put_line('Enter number to print multiplication table');
VAR1:=&VAR1;
FOR VAR2 IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(VAR1||'X'||VAR2||'='||VAR1*VAR2);
END LOOP;
END;
/

SQL> @7b
Enter value for var1: 2
Old 6: VAR1:=&VAR1;
New 6 : VAR1:=2;
Enter numer to print multiplication table 2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18
2X10=20

PL/SQL procedure successfully completed.

NESTED LOOP: PL/SQL allows using one loop inside another loop. It may be either basic, while or
for loop.
Syntax:
WHILE condition1 LOOP sequence_of_statements1
WHILE condition2 LOOP sequence_of_statements2
END LOOP;
END LOOP;

PL/SQL CODE: A PL/SQL program to print n prime number using nested loop.

SQL> ed 7c

Set Serveroutput on
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/

SQL> @7c

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed.


Week 8.
Programs development u s i n g creation of p r o c e d u r e s , passing Parameters IN and OUT of
PROCEDURES.

Aim: To develop u s i n g creation of p r o c e d u r e s , passing Parameters IN and OUT of


PROCEDURES.

Description:

Procedures in SQL:

SQL procedures, also known as stored procedures, are precompiled SQL code that can be
executed multiple times without rewriting the entire SQL query. They help in improving
performance, managing tasks, and organizing code.

Here are the key procedures and steps involved:

1. Create Procedure: You use CREATE PROCEDURE to define a procedure. For example:

CREATE PROCEDURE MyProcedure


AS
BEGIN
SELECT * FROM TableName;
END;

2. Execute Procedure: Once created, you can call it with the EXEC command:

EXEC MyProcedure;

3. Parameters in Procedures: Procedures can accept input parameters to make them dynamic:

CREATE PROCEDURE GetCustomersByCity


@City NVARCHAR(50)
AS
BEGIN
SELECT * FROM Customers WHERE City = @City;
END;

4. Modify Procedure: Use ALTER PROCEDURE to update an existing procedure.

5. Delete Procedure: Procedures can be removed with the DROP PROCEDURE statement:

DROP PROCEDURE MyProcedure;


SQL Queries:

SQL> create table enquiry (enqno1 number(3), fname varchar2(30));


Table created.

SQL> insert into enquiry values (111,'Deepika');


1 row created.

SQL> insert into enquiry values (112,'Naresh Kumar');


1 row created.

PL/SQL CODE to create procedure:

SQL> ed findname

Create procedure findname(enquiryno1 IN number, fname1 OUT varchar2) is fname2


varchar2(30);
Begin
Select fname into fname2 from enquiry where enqno1=enquiryno1;
fname1:=fname2;
Exception when no_data_found then
raise_application_error(-20100,'The given number is not present');
End;
/

SQL> @findname Procedure created.

SQL> ed pro8

Set serveroutput on;


Declare
enqno2 number(5);
fname2 varchar2(30);
Begin
enqno2:=&enqno2;
findname(enqno2,fname2);
dbms_output.put_line('Person name of equiry id '||enqno2||' is '||fname2);
End;
/

SQL> @pro8

Enter value for enqno2: 114


old 5: enqno2:=&enqno2;
new 5: enqno2:=114; declare
*
ERROR at line 1:
ORA-20100: The given number is not present ORA-06512: at
"SYSTEM.FINDNAME", line 7
ORA-06512: at line 6

SQL> @pro8

Enter value for enqno2: 112


old 5: enqno2:=&enqno2;
new 5: enqno2:=112;

Person name of equiry id 112 is Naresh Kumar

PL/SQL procedure successfully completed.


Week 9. Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.

Aim: A Program t o development using creation of stored functions, invoke functions in SQL
Statements and writing complex functions.

Description:

Stored Functions:

In SQL, a stored function is a database object that allows you to store reusable logic in the
database.

It is similar to a stored procedure but with a key difference: a function returns a value (while a
stored procedure does not).

Functions can be called from queries just like a regular expression, and can be used in SELECT,
WHERE, and other clauses.

Key Features of Stored Functions:

 Return Value: A stored function always returns a value. It can return a scalar value (e.g.,
INTEGER, VARCHAR, and DATE) or a table (in some databases).
 Reusable Logic: Functions allow you to encapsulate complex logic and reuse it across
multiple queries.
 Called from SQL Queries: Functions can be called directly in SQL expressions.

Syntax for Creating a Stored Function:

The basic syntax for creating a stored function in SQL is as follows:

CREATE FUNCTION function_name (parameters)


RETURNS return_type
AS
BEGIN
-- SQL logic
RETURN value;
END;
Example of a Simple Stored Function:

Suppose you want to create a function that calculates the square of a number. Here's how you
might write that:

CREATE FUNCTION calculate_square(num INT)


RETURNS INT
AS
BEGIN
RETURN num * num;
END;

Now, you can use the calculate_square function in your SQL queries:

SELECT calculate_square(5); -- Returns 25

Example with Multiple Parameters:

You can also create functions with multiple parameters. For example, a function to calculate the
area of a rectangle:

CREATE FUNCTION calculate_area(length INT, width INT)


RETURNS INT
AS
BEGIN
RETURN length * width;
END;

You can call this function like this:

SELECT calculate_area(10, 5); -- Returns 50

Invoke Functions:

Invoking functions in SQL statements allows you to reuse logic and streamline data operations
efficiently.

General Syntax for Invoking a Stored Function:

In most cases, the syntax to invoke a function is:

SELECT function_name(parameters);
SQL Queries:

SQL> create table dept(deptno int,dname varchar(10));


Table created.
SQL> insert into dept values(121, 'Naresh');
1 row created.

PL/SQL Code:

PL/SQL CODE to create user define function

create or replace function getname(dno number) return varchar2 as


fname1 varchar2(30);
begin
select dname into fname1 from dept where deptno=dno;
return(fname1);
exception
when no_data_found then
raise_application_error(-20100,'Your entered Department number is
not exists');
end;
/

SQL> @getname
Function created.

PL/SQL Code for calling function in program

SQL> ed pro9

Set serveroutput on;


Declare
fname2 varchar2(30);
deptno2 number(5);
Begin
deptno2:=&deptno;
fname2:=getname(deptno2);
dbms_output.put_line(fname2||' is in dept no '||deptno2);
End;
/
SQL> @pro9
Enter value for deptno: 121
old 5: deptno2:=&deptno;
new 5: deptno2:=121;
Naresh is in dept no 121

PL/SQL procedure successfully completed.

SQL> @pro9
Enter value for deptno: 1001
old 5: deptno2:=&deptno;
new 5: deptno2:=1001;
declare
*
ERROR at line 1:
ORA-20100: Your entered Department number is not exists
ORA-06512: at "SYSTEM.GETNAME", line 9
ORA-06512: at line 6
Week 10

10. Develop programs using features parameters in a CURSOR, FOR UPDATE


CURSOR, WHERE CURRENT of clause and CURSOR variables.

Aim: To develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, and
WHERE CURRENT of clause and CURSOR variables.

Description:

Cursors:
 A cursor is a pointer to this context area.
 PL/SQL controls the context area through a cursor.
 A cursor holds the rows (one or more) returned by a SQL statement.
 The set of rows the cursor holds is referred to as the active set.

Types of Cursors:
There are two types of cursors
1. Implicit Cursors
2. Explicit Cursors

1. Implicit Cursors:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there
is no explicit cursor for the statement.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes
such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.

The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed
for use with the FORALL statement.

2. Explicit Cursors:
Explicit cursors are programmer-defined cursors for gaining more control over the context Area. An explicit
cursor should be defined in the declaration section of the PL/SQL Block.

Syntax:
CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps


 Declaring the cursor for initializing the memory
 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
# Declaring the Cursor:

Declaring the cursor defines the cursor with a name and the associated SELECT statement.
Syntax:
CURSOR c_customers IS
SELECT id, name, address FROM customers;

# Opening the Cursor:

Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned
by the SQL statement into it.
Syntax:
OPEN c_customers;

# Fetching the Cursor:

Fetching the cursor involves accessing one row at a time.


Syntax:
FETCH c_customers INTO c_id, c_name, c_addr;

# Closing the Cursor:

Closing the cursor means releasing the allocated memory.


Syntax:
CLOSE c_customers;

SQL Queries:

SQL> create table customers(id number(3), name varchar2(10), age


number(3), address varchar2(10), salary number(10,2));
Table created.

SQL> insert into customers values(1,'Naresh',32,'Tirupati',2000);


1 row created.

SQL> insert into customers values(2,'Deepika',25,'Madanapalli',1500);


1 row created.

SQL> insert into customers values(3,'Dharani',23,'Raychoti',2000);


1 row created.

SQL> insert into customers values(4,'saikeerthi',25,'Kavali',6500);


1 row created.
SQL> select *from customers;

ID NAME AGE ADDRESS SALARY

1 Naresh 32 Tirupati 2000


2 Deepika 25 Madanapalli 1500
3 Dharani 23 Raychoti 2000
4 saikeerthi 25 kavali 6500

4 rows selected.

Pl/SQL Code:

SQL> ed pro10

DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.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;
/

SQL> @pro10
1 Naresh Tirupati
2 Deepika Madanapalli
3 Dharani Raychoti
4 saikeerthi Kavali

PL/SQL procedure successfully completed.


Week-11

Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers

DESCRITION

Triggers in PL/SQL:
Triggers in oracle are blocks of PL/SQL code which oracle engine can execute
automatically based on some action or event.
These events can be:
 DDL statements (CREATE, ALTER, DROP, TRUNCATE)
 DML statements (INSERT, SELECT, UPDATE, DELETE)
 Database operation like connecting or disconnecting to oracle (LOGON, LOGOFF,
SHUTDOWN)
Triggers are automatically and repeatedly called upon by oracle engine on satisfying certain
condition.
Triggers can be activated or deactivated depending on the requirements.
If triggers are activated then they are executed implicitly by oracle engine and if triggers are
deactivated then they are executed explicitly by oracle engine.

PL/SQL: Uses of Triggers:


Here we have mentioned a few use cases where using triggers proves very helpful:
 Maintaining complex constraints which is either impossible or very difficult via normal
constraint(like primary, foreign, unique etc) applying technique.
 Recording the changes made on the table.
 Automatically generating primary key values.
 Prevent invalid transactions to occur.
 Granting authorization and providing security to database.
 Enforcing referential integrity.

PL/SQL: Parts of a Trigger


Whenever a trigger is created, it contains the following three sequential parts:
 Triggering Event or Statement: The statements due to which a trigger occurs is called
triggering event or statement. Such statements can be DDL statements, DML statements or
any database operation, executing which gives rise to a trigger.
 Trigger Restriction: The condition or any limitation applied on the trigger is called trigger
restriction. Thus, if such a condition is TRUE then trigger occurs otherwise it does not
occur.
 Trigger Action: The body containing the executable statements that is to be executed
when trigger occurs that is with the execution of Triggering statement and upon evaluation
of Trigger restriction as True is called Trigger Action.
PL/SQL: Types of Triggers
The above diagram clearly indicated that Triggers can be classified into three categories:
 Level Triggers
 Event Triggers
 Timing Triggers

Level Triggers
There are 2 different types of level triggers, they are:
 ROW LEVEL TRIGGERS
It fires for every record that got affected with the execution of DML statements like
INSERT, UPDATE, DELETE etc.
It always use a FOR EACH ROW clause in a triggering statement.
 STATEMENT LEVEL TRIGGERS
It fires once for each statement that is executed.
Event Triggers
There are 3 different types of event triggers, they are:
 DDL EVENT TRIGGER
It fires with the execution of every DDL statement(CREATE, ALTER, DROP,
TRUNCATE).
 DML EVENT TRIGGER
It fires with the execution of every DML statement(INSERT, UPDATE, DELETE).
 DATABASE EVENT TRIGGER
It fires with the execution of every database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.
Timing Triggers
There are 2 different types of timing triggers, they are:
 BEFORE TRIGGER
It fires before executing DML statement.
Triggering statement may or may not executed depending upon the before condition block.
 AFTER TRIGGER
It fires after executing DML statement.

SQL Queries:

SQL> create table customers (id number(3), name varchar2(10),


age number(3), address varchar2(10), salary number(10,2));
Table created.

SQL> insert into customers values(1,'ramesh',32,'ahmedabad',2000);


1 row created.
SQL> insert into customers values(2,'khilan',25,'Delhi',1500);
1 row created.
SQL> insert into customers values(3,'kaushik',23,'Kota',2000);
1 row created.
SQL> insert into customers values(4,'chitali',25,'Mumbai',6500);
1 row created.
SQL> select *from customers;
ID NAME AGE ADDRESS SALARY
-
1 ramesh 32 ahmedabad 2000
2 khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 chitali 25 Mumbai 6500

PL/SQL Code for creation of trigger while insert / update records into a table.

SQL>ed pro11

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :
OLD.salary;
dbms_output.put_line('Old salary: ' ||:OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

SQL> @pro11
Trigger created.

SQL> insert into customers values(5,'Hardik',27,'Mumbai',5500);


Old salary:
New salary: 5500
Salary difference:
1 row created.

SQL> update customers set salary=salary+500 where id=2;


Old salary: 1500
New salary: 2000
Salary difference: 500
1 row updated.
Week-12

Create a table and perform the search operation on table using indexing and non-
indexing techniques.

SQL> Create Table Teacher(Staff_Id Varchar2(4) Primary Key, Staff_Name Varchar2(30), Qualification
Varchar2(10), Hiredate Date, Job Varchar2(30), Address Varchar2(15), Ph_Num Number(10), Salary
Number(7, 2), Department Varchar2(10));

Table created.

SQL> insert into teacher values('T101','SUNITHA','MCA','29-JUN-06','ASSOCIATE


PROFESSOR','VIJAYAWADA',9985061308,23000,'MCA');
1 row created.

SQL>insert into teacher values('T102','FRED SMITH','MTECH','07-MAR-03','ASSOCIATE


PROFESSOR','GUNTUR',9985063445,36000,'MBA');
1 row created.

SQL>insert into teacher values('T103','JACK BARNES','BTECH','27-


JUN07','PROFESSOR','TENALI',9985012345,27000,'MTECH');
1 row created.

SQL>insert into teacher values('T104','JANE DOE','MCA','04-JUL-06','ASSISTANT


PROFESSOR','VIJAYAWADA',9985045678,29000,'BTECH');
1 row created.

SQL>insert into teacher values('T105','JOE SHMOE','MBA','16-AUG-08','ASSOCIATE


PROFESSOR','ELURU',9987651308,36000,'MCA');
1 row created.

SQL>insert into teacher values('T106','JON BAKER','MSC(COM)','12-


JAN03','PROFESSOR','HYDERABAD',8876561308,46000,'MCA');
1 row created.

SQL>insert into teacher values('T107','JOHN DOE','MSC(PHY)','06-FEB-04','ASSISTANT


PROFESSOR','VIJAYAWADA',8345661308,31000,'MBA');
1 row created.

SQL>insert into teacher values('T108','KIM SMITH','MCA','10-MAR-08','ASSISTANT


PROFESSOR','VIZAG',8374561308,26000,'MTECH');
1 row created.

SQL>insert into teacher values('T109','MARY PARKER','MTECH','02-


APR09','PROFESSOR','NELLORE',7893427649,52000,'MBA');
1 row created.

SQL>insert into teacher values('T110','SAMUEL JOHN','BTECH','19-MAY-05','ASSISTANT


PROFESSOR','ELURU',9982222208,26000,'MBA');
1 row created.
SQL>insert into teacher values('T111','FRANKLIN WONG','MBA','20-AUG-06','ASSOCIATE
PROFESSOR','VIZAG',9985033333,20000,'MTECH');
1 row created.

SQL>insert into teacher values('T112','SLICIA ZELAYA','MCA','16-SEP-04','ASSISTANT


PROFESSOR','VIJAYAWADA',9985202020,33000,'BTECH');
1 row created.

SQL>insert into teacher values('T113','JENNIFER WALLACE','MSC(MATHS)','25-


OCT03','PROFESSOR','HYDERABAD',9902192033,54000,'MCA');
1 row created.

SQL>insert into teacher values('T114','RAMESH NARAYANA','MCA','24-NOV04','ASSOCIATE


PROFESSOR','NARASARAOPET',9988776655,34000,'MBA');
1 row created.

SQL>insert into teacher values('T115','JOYCE ENGLISH','MBA','22-DEC-06','ASSISTANT


PROFESSOR','VIJAYAWADA',9998765443,45000,'MBA');
1 row created.

To show the query execution timing use the following query


SQL> Set timing on;

Retrieve details of teacher before creation of index.


SQL> select *from teacher;
STAFF ID STAFF_NAME QUALIFICATION HIREDATE JOB ADDRESS PH_NUM SALARY DEPARTMENT
----------- ------------------- ----------------------- ----------------- ------------- -------------- -------------- - ------------- -----------------------
T101 SUNITHA MCA 29-06-06 ASSOCIATE PROFESSOR VIJAYAWADA 9985061308 23000 MCA
T102 FRED SMITH MTECH 07-MAR-03 ASSOCIATE PROFESSOR GUNTUR 9985063445 36000 MBA
T103 JACK BARNES BTECH 27-JUN-07 PROFESSOR TENALI 9985012345 27000 MTECH
T104 JANE DOE MCA 04-JUL-06 ASSISTANT PROFESSOR VIJAYAWADA 9985045678 29000 BTECH
T105 JOE SHMOE MBA 16-AUG-08 ASSOCIATE PROFESSOR ELURU 9987651308 36000 MCA
T106 JON BAKER MSC(COM) 12-JAN-03 PROFESSOR HYDERABAD 8876561308 46000 MCA
T107 JOHN DOE MSC(PHY) 06-FEB-04 ASSISTANT PROFESSOR VIJAYAWADA 8345661308 31000 MBA
T108 KIM SMITH MCA 10-MAR-08 ASSISTANT PROFESSOR VIZAG 8374561308 26000 MTECH
T109 MARY PARKER MTECH 02-APR-09 PROFESSOR NELLORE 7893427649 52000 MBA
T110 SAMUEL JOHN BTECH 19-MAY-05 ASSISTANT PROFESSOR ELURU 9982222208 26000 MBA
T111 FRANKLIN WONG MBA 20-AUG-06 ASSOCIATE PROFESSOR VIZAG 9985033333 20000 MTECH
T112 SLICIA ZELAYA MCA 16-SEP-04 ASSISTANT PROFESSOR VIJAYAWADA 9985202020 33000 BTECH
T113 JENNIFER WALLACE MSC(MATHS) 25-OCT-03 PROFESSOR HYDERABAD 9902192033 54000 MCA
T114 RAMESH NARAYANA MCA 24-NOV-04 ASSOCIATE PROFESSOR NARASARAOPET 9988776655 34000 MBA
T115 JOYCE ENGLISH MBA 22-DEC-06 ASSISTANT PROFESSOR VIJAYAWADA 9998765443 45000 MBA

15 rows selected. Elapsed: 00:00:00.24

You might also like