Dbms Lab Manual - 2013 - Regulation
Dbms Lab Manual - 2013 - Regulation
Dbms Lab Manual - 2013 - Regulation
1. Creation of a database and writing SQL queries to retrieve information from the database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of database triggers and functions
11. Mini project (Application Development using Oracle/ Mysql )
a) Inventory Control System.
b) Material Requirement Processing.
c) Hospital Management System.
d) Railway Reservation System.
e) Personal Information System.
f) Web Based User Identification System.
g) Timetable Management System.
h) Hotel Management System
LAB EQUIPMENTS
Oracle server could be loaded and can be connected from individual PCs.
2
www.studentsfocus.com
OBJECTIVES:
The student should be made to:
Learn to create and use a database
Be familiarized with a query language
Have hands on experience on DDL Commands
Have a good understanding of DML Commands and DCL
commands Familiarize advanced SQL queries.
Be Exposed to different applications
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement a database schema for a given problem-
domain Populate and query a database
Create and maintain tables using
PL/SQL. Prepare reports.
REFERENCE:
spoken-tutorial.org
DO’S
Students should come with observation, record note, class notes, and lab relevant book to the
laboratory. Students should maintain silence inside the laboratory.
After completing the laboratory exercise, make sure to shutdown the system properly.
DONT’S
www.studentsfocus.com
INTRODUCTION TO SQL
SQL:
Structured query language pronounced as (SEQUEL). This language is used to communicate to
oracle database.
A database along with the software which helps to manage. The database is called
database management system (DBMS).
A DBMS which is based on relational theory is called as relational database management system.
Examples of RDBMS:
1. ORACLE
2. SQL SERVER
3. DB2
4. MYSQL
5. SYBASE
6. TERA DATA
7. MS ACCESS
SQL Commands
www.studentsfocus.com
Data Definition Language (DDL):
Data Definition Language (DDL) or Schema Definition Language, statements are used to define the database
structure or schema.
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed COMMENT - add comments to the data dictionary
RENAME - rename an object
Data Manipulation Language (DML) statements are used for managing data within schema objects.
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records
remain MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It
allows statements to be grouped together into logical transactions.
COMMIT - save work done
www.studentsfocus.com
Fiq: SQL Architecture:
Rules:
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. Two different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is ‘null’.
8. It is a command based language.
9. It is not case sensitive.
10. Every command should end with ‘;’.
11. Every command starts with “verb”.
12. It is similar to English. This language is developed in the year 1972. Mr.CODD, by
IBM developed by “IBM”.
www.studentsfocus.com
WORDS TO REMEMBER
This appendix lists words that have a special meaning to Oracle. Each word plays a specific role in the context in which it appears.
For example, in an INSERT statement, the reserved word INTO introduces the tables to which rows will be added. But, in a FETCH or
SELECT statement, the reserved word INTO introduces the output host variables to which column values will be assigned.
The following words are reserved by Oracle. That is, they have a special meaning to Oracle and so cannot be redefined. For
this reason, you cannot use them to name database objects such as columns, tables, or indexes.
Oracle Keywords
The following words also have a special meaning to Oracle but are not reserved words and so can be redefined. However, some might
eventually become reserved words.
ADMIN COUNT FOREIGN MINEXTENTS PRECISION SQLERROR
AFTER CURSOR FORTRAN MINVALUE PRIMARY SQLSTATE
ALLOCATE CYCLE FOUND MODULE PRIVATE STATEMENT_ID
ANALYZE DATABASE FUNCTION MOUNT PROCEDURE STATISTICS
ARCHIVE DATAFILE GO NEXT PROFILE STOP
ARCHIVELOG DBA GOTO NEW QUOTA STORAGE
AUTHORIZATION DEC GROUPS NOARCHIVELOG READ SUM
7
www.studentsfocus.com
CLOSE EXPLAIN MAX OPEN SECTION UNTIL
COBOL EXECUTE MAXDATAFILES OPTIMAL SEGMENT USE
COMMIT EXTENT MAXINSTANCES OWN SEQUENCE USING
COMPILE EXTERNALLY MAXLOGFILES PACKAGE SHARED WHEN
CONSTRAINT FETCH MAXLOGHISTORY PARALLEL SNAPSHOT WRITE
CONSTRAINTS FLUSH MAXLOGMEMBERS PCTINCREASE SOME WORK
CONTENTS FREELIST MAXTRANS PCTUSED SORT
CONTINUE FREELISTS MAXVALUE PLAN SQL
CONTROLFILE FORCE MIN PLI SQLCODE
O OCI functions
8
www.studentsfocus.com
SQL Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform
operation(s), such as comparisons and arithmetic operations.Operators are used to specify conditions in an SQL
statement and to serve as conjunctions for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate condition.
Arithmetic operators
Assume variable a holds 10 and variable b holds 20, then:
Operator Description Example
Comparison operators
Logical operators
Operator Description
www.studentsfocus.com
ALL The ALL operator is used to compare a value to all values in another value set.
AND The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
ANY The ANY operator is used to compare a value to any applicable value in the list according to the condition.
BETWEEN The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have been specified.
LIKE The LIKE operator is used to compare a value to similar values using wildcard operators.
NOT The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, et
OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
www.studentsfocus.com
SQL Functions
SQL aggregate functions return a single value, calculated from values in a column.
SQL scalar functions return a single value, based on the input value.
10
www.studentsfocus.com
SQL String Functions
SQL string functions are used primarily for string manipulation. The following table details the important
string functions:
Name Description
ASCII() Returns numeric value of left-most character
BIN() Returns a string representation of the argument
BIT_LENGTH() Returns length of argument in bits
CHAR_LENGTH() Returns number of characters in argument
CHAR() Returns the character for each integer passed
CHARACTER_LENGTH() A synonym for CHAR_LENGTH()
CONCAT_WS() Returns concatenate with separator
CONCAT() Returns concatenated string
CONV() Converts numbers between different number bases
ELT() Returns string at index number
EXPORT_SET() Returns a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string
FIELD() Returns the index (position) of the first argument in the subsequent arguments
FIND_IN_SET() Returns the index position of the first argument within the second argument
FORMAT() Returns a number formatted to specified number of decimal places
HEX() Returns a string representation of a hex value
INSERT() Inserts a substring at the specified position up to the specified number of characters
INSTR() Returns the index of the first occurrence of substring
LCASE() Synonym for LOWER()
LEFT() Returns the leftmost number of characters as specified
LENGTH() Returns the length of a string in bytes
LOAD_FILE() Loads the named file
LOCATE() Returns the position of the first occurrence of substring
LOWER() Returns the argument in lowercase
LPAD() Returns the string argument, left-padded with the specified string
LTRIM() Removes leading spaces
MAKE_SET() Returns a set of comma-separated strings that have the corresponding bit in bits set
MID() Returns a substring starting from the specified position
OCT() Returns a string representation of the octal argument
OCTET_LENGTH() A synonym for LENGTH()
ORD() If the leftmost character of the argument is a multi-byte character, returns the code for that character
POSITION() A synonym for LOCATE()
QUOTE() Escapes the argument for use in an SQL statement
REGEXP Pattern matching using regular expressions
REPEAT() Repeats a string the specified number of times
REPLACE() Replaces occurrences of a specified string
REVERSE() Reverses the characters in a string
RIGHT() Returns the specified rightmost number of characters
RPAD() Appends string the specified number of times
RTRIM() Removes trailing spaces
SOUNDEX() Returns a soundex string
SOUNDS LIKE Compares sounds
SPACE() Returns a string of the specified number of spaces
STRCMP() Compares two strings
SUBSTRING_INDEX() Returns a substring from a string before the specified number of occurrences of the delimiter
SUBSTRING(), SUBSTR() Returns the substring as specified
TRIM() Removes leading and trailing spaces
UCASE() Synonym for UPPER()
UNHEX() Converts each pair of hexadecimal digits to a character
UPPER() Converts to uppercase
11
www.studentsfocus.com
SQL Numeric Functions
SQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations. The
following table details the numeric functions:
Name Description
ABS() Returns the absolute value of numeric expression.
ACOS() Returns the arccosine of numeric expression. Returns NULL if the value is not in the range -1 to 1.
ASIN() Returns the arcsine of numeric expression. Returns NULL if value is not in the range -1 to 1
ATAN() Returns the arctangent of numeric expression.
ATAN2() Returns the arctangent of the two variables passed to it.
BIT_AND() Returns the bitwise AND all the bits in expression.
BIT_COUNT() Returns the string representation of the binary value passed to it.
BIT_OR() Returns the bitwise OR of all the bits in the passed expression.
CEIL() Returns the smallest integer value that is not less than passed numeric expression
CEILING() Returns the smallest integer value that is not less than passed numeric expression
CONV() Convert numeric expression from one base to another.
COS() Returns the cosine of passed numeric expression. The numeric expression should be expressed in radians.
COT() Returns the cotangent of passed numeric expression.
DEGREES() Returns numeric expression converted from radians to degrees.
EXP() Returns the base of the natural logarithm (e) raised to the power of passed numeric expression.
FLOOR() Returns the largest integer value that is not greater than passed numeric expression.
FORMAT() Returns a numeric expression rounded to a number of decimal places.
GREATEST() Returns the largest value of the input expressions.
Takes multiple expressions exp1, exp2 and exp3 so on.. and returns 0 if exp1 is less than exp2, returns 1 if
INTERVAL()
exp1 is less than exp3 and so on.
LEAST() Returns the minimum-valued input when given two or more.
LOG() Returns the natural logarithm of the passed numeric expression.
LOG10() Returns the base-10 logarithm of the passed numeric expression.
MOD() Returns the remainder of one expression by diving by another expression.
Returns the string representation of the octal value of the passed numeric expression. Returns NULL if passed
OCT()
value is NULL.
PI() Returns the value of pi
POW() Returns the value of one expression raised to the power of another expression
POWER() Returns the value of one expression raised to the power of another expression
RADIANS() Returns the value of passed expression converted from degrees to radians.
Returns numeric expression rounded to an integer. Can be used to round an expression to a number of
ROUND()
decimal points
SIN() Returns the sine of numeric expression given in radians.
SQRT() Returns the non-negative square root of numeric expression.
STD() Returns the standard deviation of the numeric expression.
STDDEV() Returns the standard deviation of the numeric expression.
TAN() Returns the tangent of numeric expression expressed in radians.
Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result will have no decimal
TRUNCATE()
point.
12
www.studentsfocus.com
LIST OF EXPERIMENTS
1. Creation of a database and writing SQL queries to retrieve information from the database.
a. CREATE d. TRUNCATE
b. ALTER e. RENAME
c. DROP f. COMMENT
a. INSERT
b. UPDATE
c. DELETE
d. SELECT
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based
on conditions.
13
www.studentsfocus.com
5. Creating relationship between the databases.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
9. Creation of Procedures.
14
www.studentsfocus.com
Creation of a database and writing SQL queries to retrieve information from the database.
AIM:
OBJECTIVE:
After completing the exercise the students can able to Understand how to create a table with list of
fields, Modify a row using where clause, Drop a table, Delete the unwanted rows in a table.
ALGORITHM:
DDL COMMAND:
CREATE
ALTER
DROP
TRUNCATE
COMMENT
RENAME
15
www.studentsfocus.com
CREATE TABLE
Constraints are condition for the data item to be stored into a database. There are two types
of Constraints viz., Column Constraints and Table Constraints.
Tables
In relational database systems (DBS) data are represented using tables (relations). A query
issued against the DBS also results in a table. A table has the following structure:
Tuple or record 1
Tuple or record 2
.
.
.
Tuple or record n
Column 1 Column 2 Columnn
A table is uniquely identified by its name and consists of rows that contain the stored information,
each row containing exactly one tuple (or record). A table can have one or more columns. A column is
made up of a column name and a data type, and it describes an attribute of the tuples. The structure of a
table, also called relation schema, thus is defined by its attributes. The type of information to be stored in a
table is defined by the data types of the attributes at table creation time. Oracle offers the following basic
data types:
Sl.No Data Type Description
1 Char(n) Character String . n is the size of variable. Maximum size is 255 characters. The default size is 1
16
www.studentsfocus.com
SQL uses the terms table, row, and column for relation, tuple, and attribute, respectively. A table can have
up to 254 columns which may have different or same data types and sets of values (domains), respectively.
Possible domains are alphanumeric data (strings), numbers and date formats.
Sample Databases used for illustration of SQL Commands is given below with ER Diagram and corresponding
Relational Model with suitable data entered in the tables.
17
www.studentsfocus.com
QUERY: 01
Q1: Write a query to create a table employee with empno, ename, designation, and salary.
Command:
Table created.
Constraints are condition for the data item to be stored into a database. There are two types
of Constraints viz., Column Constraints and Table Constraints.
Syntax:
[CONSTRAINT constraint name]
REFERENCES table
TABLE DESCRIPTION
It is used to view the table structure to confirm whether the table was created correctly.
QUERY: 02
Q2: Write a query to display the column name and data type of the table employee.
Command:
www.studentsfocus.com
QUERY: 03
Q3: Write a query for create a from an existing table with all the fields
Syntax: syntax for create a table from an existing table with all fields.
SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT * FROM<SOURCE TABLE NAME>;
Command:
Table created.
Command:
QUERY: 04
Q4: Write a query for create a from an existing table with selected fields
Syntax: Syntax for create a from an existing table with selected fields.
SQL> CREATE TABLE <TRAGET TABLE NAME> AS SELECT EMPNO, ENAMEFROM <SOURCE
TABLE NAME>;
Command:
Table created.
Command:
19
www.studentsfocus.com
QUERY: 05
Q5: Write a query for create a new table from an existing table without any record:
Syntax: The syntax for create a new table from an existing table without any record.
SQL> CREATE TABLE <TRAGET TABLE NAME> AS SELECT * FROM<SOURCE TABLE NAME>
Command:
Table created.
Command:
20
www.studentsfocus.com
ALTER & MODIFICATION ON TABLE
To modify structure of an already existing table to add one more columns and also modify
the existing columns.
QUERY: 06
Q6: Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER (6).
Command:
Table altered.
Command:
Q7. Write a Query to Alter the table employee with multiple columns (EMPNO,ENAME.)
www.studentsfocus.com
Command:
QUERY: 08
Q8. Write a query to add a new column in to employee
Command:
SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
Table altered.
QUERY: 09
www.studentsfocus.com
REMOVE / DROP
It will delete the table structure provided the table should be empty.
QUERY: 10
Q10. Write a query to drop a column from an existing table employee
Command:
SQL> ALTER TABLE EMP DROP COLUMN DOJ;
Table altered.
QUERY: 11
Q10. Write a query to drop multiple columns from employee
Command:
SQL> ALTER TABLE EMP DROP (DOB, QUALIFICATION);
Table altered.
23
www.studentsfocus.com
RENAME
QUERY: 12
Q10. Write a query to rename table emp to employee
Syntax:The Syntax for add a new column.
SQL> ALTER TABLE RENAME <OLD NAME> TO <NEW NAME>
Command:
SQL> ALTER TABLE RENAME EMP TO EMPLOYEE;
SQL> DESC EMPLOYEE;
Name Null? Type
------------------- --------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained then the records
alone can be deleted.
Syntax:
TRUNCATE TABLE <TABLE NAME>;
Example:
Truncate table EMP;
DROP:
To remove a table along with its structure and data.
Syntax:The Syntax for add a new column.
SQL> Drop table<table name>;
Command:
SQL> drop table employee;
RESULT:
Thus the SQL commands for DDL commands in RDBMS has been verified and executed successfully.
24
www.studentsfocus.com
DATA MANIPULATION LANGUAGE (DML) COMMANDS IN RDBMS
Ex: No: 1.2
__ : __ : __
AIM:
To execute and verify the DML commands are the most frequently used SQL commands and is
used to query and manipulate the existing database objects.
DML (DATA MANIPULATION LANGUAGE)
SELECT
INSERT
DELETE
UPDATE
ALGORITHM:
25
www.studentsfocus.com
INSERT
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
QUERY: 01
Command:
1 row created.
QUERY: 03
Q3. Write a query to insert the records in to employee using substitution method.
SQL :> INSERT INTO <TABLE NAME> VALUES< ‘&column name’, ‘&column name 2’, …..);
Command:
www.studentsfocus.com
SQL> /
Enter value for empno: 104
Enter value for ename: CHINNI
SELECT
SELECT Statement is used to fetch the data from a database table which returns data in the form
of result table. These result tables are called result-sets.
QUERY: 02
Command:
27
www.studentsfocus.com
UPDATE
The SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE
clause with UPDATE query to update selected rows, otherwise all the rows would be affected.
QUERY: 04
Command:
1 row updated.
QUERY: 05
Command:
1 row updated.
www.studentsfocus.com
DELETE
The SQL DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.
QUERY: 06
Command:
1 row deleted.
RESULT:
Thus the SQL commands for DML has been verified and executed successfully.
29
www.studentsfocus.com
Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions.
Ex: No: 02
__ : __ : __
AIM:
To performing insertion, deletion, modifying, altering, updating and viewing records based
on conditions.
ALGORITHM:
STEP 4: Insert the record into table based on some condition using WHERE CLAUSE
STEP 5: Update the existing records into the table based on some condition
30
www.studentsfocus.com
DRL-DATA RETRIEVAL IMPLEMENTING ON SELECT COMMANDS
Command:
SQL> CREATE TABLE EMP(
EMPNO NUMBER (4),
ENAME VARCHAR2 (10),
JOB VARCHAR2(20),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(8,2),
DEPTNO NUMBER(3)
);
Table created.
31
www.studentsfocus.com
SQL> SELECT * FROM EMP;
EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO
------------ ------------------------------- ----------- ----------------- -------------- --------------------
7369 SMITH CLERK 5001 17-DEC-80 8000 200
7499 ALLEN SALESMAN 5002 20-FEB-80 3000 300
7521 WARD SALESMAN 5003 22-FEB-80 5000 500
7566 JONES MANAGER 5002 02-APR-85 75000 200
7566 RAJA OWNER 5000 30-APR-75 100
7566 KUMAR COE 5002 12-JAN-87 55000 300
7499 RAM KUMAR SR.SALESMAN 5003 22-JAN-87 12000.55 200
7521 SAM KUMAR SR.SALESMAN 5003 22-JAN-75 22000 300
8 rows selected.
BY USING SELECTED COLUNMS
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP;
EMPNO ENAME JOB SAL
----------- ----------- ----------- --------------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7566 JONES MANAGER 75000
7566 RAJA OWNER
7566 KUMAR COE 55000
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMARSR.SALESMAN 22000
8 rows selected.
BETWEEN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL BETWEEN 10000 AND 30000;
EMPNO ENAME JOB SAL
---------- ------------------- ------------- -------------
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMAR SR.SALESMAN 22000
32
www.studentsfocus.com
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL NOT BETWEEN 10000 AND 30000;
EMPNO ENAME JOB SAL
----------- ---------------- ------------ ------------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7566 JONES MANAGER 75000
7566 KUMAR COE 55000
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
33
www.studentsfocus.com
LIKE Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
34
www.studentsfocus.com
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE ENAME LIKE '%U%A%';
no rows selected
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE ENAME NOT LIKE 'R_J_';
7 rows selected.
35
www.studentsfocus.com
RELATIONAL OPERATOR
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL=55000;
EMPNO ENAME JOB SAL
---------- ---------- -------------------- ----------
7566 KUMAR COE 55000
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL!=55000;
EMPNO ENAME JOB SAL
---------- ---------- -------------------- ----------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7566 JONES MANAGER 75000
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMAR SR.SALESMAN 22000
6 rows selected.
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL<>55000;
EMPNO ENAMEJOB SAL
---------- ---------- -------------------- ----------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7566 JONES MANAGER 75000
7499 RAM KUMARSR.SALESMAN12000.55
7521 SAM KUMARSR.SALESMAN 22000
6 rows selected.
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL>55000;
EMPNO ENAME JOB SAL
---------- ---------- ------------------- ----------
7566 JONES MANAGER 75000
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL<55000;
EMPNO ENAME JOB SAL
----------- ---------- -------------------- ----------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMARSR.SALESMAN 22000
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL<=55000;
EMPNO ENAME JOB SAL
---------- ------------ -------------------- ----------
7369 SMITH CLERK 8000
7499 ALLEN SALESMAN 3000
7521 WARD SALESMAN 5000
7566 KUMAR COE 55000
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMARSR.SALESMAN 22000
6 rows selected.
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE SAL>=55000;
EMPNO ENAME JOB SAL
------------ ---------- ----------------- ---------
7566 JONES MANAGER 75000
7566 KUMAR COE 55000
36
www.studentsfocus.com
AND / OR
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE JOB='SR.SALESMAN' AND SAL=22000;
EMPNO ENAME JOB SAL
----------- ------------ ------------------ ----------
7521 SAM KUMARSR.SALESMAN 22000
ORDER BY
Syntax:
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
8 rows selected.
37
www.studentsfocus.com
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP ORDER BY ENAME ASC;
EMPNO ENAME JOB SAL
----------- ------------ -------------------- ----------
7499 ALLEN SALESMAN 3000
7566 JONES MANAGER 75000
7566 KUMAR COE 55000
7566 RAJA OWNER
7499 RAM KUMAR SR.SALESMAN 12000.55
7521 SAM KUMARSR.SALESMAN 22000
7369 SMITH CLERK 8000
7521 WARD SALESMAN 5000
8 rows selected.
TOP
Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SQL> SELECT EMPNO,ENAME,JOB,SAL FROM EMP WHERE ROWNUM <4 ORDER BY ENAME;
EMPNO ENAME JOB SAL
----------- ---------- ------------------ ----------
7499 ALLEN SALESMAN 3000
7369 SMITH CLERK 8000
7521 WARD SALESMAN 5000
DISTINCT
Syntax:
SELECT DISTINCT column_name,column_name
FROM table_name;
Ex:
SQL> SELECT DISTINCT JOB FROM EMP;
JOB
--------------------
CLERK
SALESMAN
SR.SALESMAN
MANAGER
COE
OWNER
6 rows selected.
38
www.studentsfocus.com
USING ALTER
This can be used to add or remove columns and to modify the precision of the datatype.
a) ADDING COLUMN
Syntax:
alter table <table_name> add <col datatype>;
Ex:
SQL> DESC EMP;
Name Null? Type
------------------------- ----------- ---------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(20)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(8,2)
DEPTNO NUMBER(3)
SQL> alter table EMP add TAX number;
Table altered.
b) REMOVING COLUMN
Syntax:
alter table <table_name> drop <col datatype>;
Ex:
39
www.studentsfocus.com
c) INCREASING OR DECREASING PRECISION OF A COLUMN
Syntax:
Ex:
Syntax:
alter table <table_name> set unused column <col>;
Ex:
SQL> alter table EMP set unused column DEPTNO;
Table altered.
40
www.studentsfocus.com
d) DROPPING UNUSED
COLUMNS Syntax:
alter table <table_name> drop unused columns;
Ex:
SQL> alter table EMP drop unused columns;
Table altered.
e) RENAMING
COLUMN Syntax:
alter table <table_name> rename column <old_col_name> to <new_col_name>;
Ex:
SQL> alter table EMP rename column SAL to SALARY;
Table altered.
INSERT
Method 1
Method 2
Method 3
Method 4
41
www.studentsfocus.com
SQL> select * from emp;
Method 5
Ex:
www.studentsfocus.com
SQL> SELECT * FROM EMPLOYEE;
EMP_NO EMP_NAME EMP_JOB HR HIREDATE SALARY
---------- ---------------- -------------------- ------------------------ ----------
7369 SMITH CLERK 5001 17-DEC-80 8000
7499 ALLEN SALESMAN 5002 20-FEB-80 3000
7521 WARD SALESMAN 5003 22-FEB-80 5000
7566 JONES MANAGER 5002 02-APR-85 75000
7566 RAJA OWNER 5000 30-APR-75
7566 KUMAR COE 5002 12-JAN-87 55000
7499 RAM KUMAR SR.SALESMAN 5003 22-JAN-87 12000.55
7521 SAM KUMARSR.SALESMAN 5003 22-JAN-75 22000
7521 SAM KUMARSR.SALESMAN 5003 22-JAN-75 22000
1111 RAMU SALESMAN 5063 12-JAN-87 5643.55
1111 RAMU SALESMAN 5063 12-JAN-87 5643.55
1111 RAMU SALESMAN
1111 RAMU SALESMAN 35000
13 rows selected.
Method 6
MULTIBLE INSERTS
We have table called DEPT with the following columns and data
SQL> select * from DEPT;
DEPTNO DNAME LOC
----------- ---------- -------
10 accounting new york
20 research dallas
30 sales Chicago
40 operations boston
43
www.studentsfocus.com
c) MULTI INSERT WITH SPECIFIED FIELDS
-- This inserts 9 rows because in the select statement retrieves 3 records (3 inserts for each row
retrieved) SQL> Select * from student;
NO NAME MARKS
------ ---- -- ---------
1 a 100
2 b 200
3 c 300
4 d
e 400
3 c 300
1 a 100
1 a 100
1 a 100
2 b 200
2 b 200
2 b 200
3 c 300
3 c 300
3 c 300
15 rows selected.
44
www.studentsfocus.com
e) MULTI INSERT WITH CONDITIONS BASED
45
www.studentsfocus.com
SQL> select * from yourtbl1;
NAME NO
-------------------- ----------
ramu 1111
ramu 1111
-- This inserts 4 rows because the first condition satisfied 3 times, second condition
satisfied once and the last none.
46
www.studentsfocus.com
f) MULTI INSERT WITH CONDITIONS BASED AND ELSE
www.studentsfocus.com
g) MULTI INSERT WITH CONDITIONS BASED AND FIRST
48
www.studentsfocus.com
h) MULTI INSERT WITH CONDITIONS BASED, FIRST AND ELSE
www.studentsfocus.com
i) MULTI INSERT WITH MULTIBLE TABLES
SQL> create table mytbl1(name varchar2(20),no number(10));
Table created.
www.studentsfocus.com
GROUP BY
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.
Ex:
www.studentsfocus.com
USING DELETE
52
www.studentsfocus.com
SQL> SELECT * FROM myTBL;
NAME MARK
--------- ----------
RAM 101
SAM 102
RAMU
SAMU 103
TAM
RAJA 555
KAJA 123
8 rows selected.
Using UPDATE
SQL> UPDATE EMP SET SAL = 55555,JOB = 'SR.MANAGER' WHERE ENAME LIKE
'R__'; 1 row updated.
RESULT:
Thus the SQL commands for Performing Insertion, Deletion, Modifying, Altering, Updating and
Viewing records based on conditions has been verified and executed successfully.
53
www.studentsfocus.com
Creation of Views, Synonyms, Sequence, Indexes, Save point.
AIM:
To create the view, execute and verify the various operations on views.
OBJECTIVE:
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 kind 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 such that a user can see and (sometimes) modify exactly what they
need and no more.
ALGORITHM:
54
www.studentsfocus.com
COMMANDS EXECUTION
CREATION OF TABLE:
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.
TABLE DESCRIPTION:
CREATE VIEW
SUNTAX FOR CREATION OF VIEW
CREATION OF VIEW
DESCRIPTION OF VIEW
55
www.studentsfocus.com
DISPLAY VIEW:
COMMAND:
56
www.studentsfocus.com
DELETION OF VIEW:
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Command:
SQL> DELETE FROM EMPVIEW WHERE
EMPLOYEE_NAME='SRI'; 1 row deleted.
SQL> SELECT * FROM EMPVIEW;
EMPLOYEE_N EMPLOYEE_NO DEPT_NAMEDEPT_NO
--------------------- ----------------------- ------------------ ----------------
RAVI 124 ECE 89
VIJAY 345 CSE 21
RAJ 98 IT 22
GIRI 100 CSE 67
UPDATE STATEMENT:
A view can be updated under certain conditions:
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY
clause. The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or
HAVING. Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in
order for the INSERT query to function.
SYNTAX:
Command:
57
www.studentsfocus.com
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
SQL>DROP VIEW
EMPVIEW; view droped
CREATE A VIEW WITH SELECTED FIELDS:
SYNTAX:
EXAMPLE-2:
EXAMPLE-3:
Note:
Replace is the keyboard to avoid the error “ora_0095:name is already used by an existing abject”.
TYPE-1:
58
www.studentsfocus.com
SQL> SELECT * FROM EMP_TOTSAL;
EMPNO ENAME SALARY MGRNO DEPTNO
------------ ------------ ------------- ------------- -------------
7578 TOM 1500 7298 10
7548 TURNER 1500 7298 10
View created.
TYPE-2:
TYPE-3:
View created.
59
www.studentsfocus.com
EID EMPNAME DNO D_NAME D_LOC
---------- ---------------- ---------- ----------------- ----------------------
7578 TOM 10 ACCOUNT NEW YORK
7548 TURNER 10 ACCOUNT NEW YORK
7369 SMITH 20 SALES CHICAGO
7678 JOHN 20 SALES CHICAGO
7499 MARK 30 RESEARCHZURICH
7565 WILL 30 RESEARCH ZURICH
JOIN VIEW:
EXAMPLE-5:
SQL> CREATE OR REPLACE VIEW DEPT_EMP_VIEW AS SELECT A.EMPNO,
A.ENAME,
A.DEPTNO,
B.DNAME,
B.LOC
FROM EMPL A, DEPMT B
WHERE A.DEPTNO=B.DEPTNO;
SQL> SELECT * FROM DEPT_EMP_VIEW;
View created.
www.studentsfocus.com
EMPNO ENAME DEPTNO DNAME LOC
----------- ------------ ------------- ------------- -------
7578 TOM 10 ACCOUNT NEW YORK
7548 TURNER 10 ACCOUNT NEW YORK
7369 SMITH 20 SALES CHICAGO
7678 JOHN 20 SALES CHICAGO
7499 MARK 30 RESEARCH ZURICH
7565 WILL 30 RESEARCH ZURICH
6 rows selected.
FORCE VIEW:
EXAMPLE-6:
61
www.studentsfocus.com
COMPILING A VIEW:
SYNTAX:
ALTER VIEW <VIEW_NAME> COMPILE;
EXAMPLE:
SQL> ALTER VIEW MYVIEW COMPILE;
RESULT:
Thus the SQL commands for View has been verified and executed successfully.
62
www.studentsfocus.com
Synonyms
Ex: No: 03 (3.2)
__ : __ : __
AIM:
OBJECTIVE:
A synonym is an alias for any table, view, materialized view, sequence, procedure, function,
package, type, Java class schema object, user-defined object type, or another synonym. Because a
synonym is simply an alias, it requires no storage other than its definition in the data dictionary.
Synonyms are often used for security and convenience. For example, they can do the following:
You can create both public and private synonyms. A public synonym is owned by the special user group
named PUBLIC and every user in a database can access it. A private synonym is in the schema of a
specific user who has control over its availability to others.
ALGORITHM:
63
www.studentsfocus.com
Example:
Syntax:
COMMANDS:
CREATE THE TABLE
64
www.studentsfocus.com
CREATE THE SYNONYM FROM TABLE
65
www.studentsfocus.com
YOU CAN UPDATE THE TABLE BY USING SYNONYM
TO DROP SYSNONYM
RESULT:
Thus the SQL commands for creation and various operation on Synonyms has been verified and
executed successfully.
66
www.studentsfocus.com
Sequence
Ex: No: 03 (3.3)
__ : __ : __
AIM:
To create the Sequence and verify the various operations on Sequence to get the
incremented number.
OBJECTIVE:
The sequence generator provides a sequential series of numbers. The sequence generator is
especially useful in multiuser environments for generating unique sequential numbers without the
overhead of disk I/O or transaction locking
Sequence numbers are integers of up to 38 digits defined in the database. A sequence definition
indicates general information, such as the following:
The name of the sequence
Whether the sequence ascends or
descends The interval between numbers
Whether Oracle Database should cache sets of generated sequence numbers in memory
ALGORITHM:
Step 4: Display the data presented on the sequence by using pseudo column.
67
www.studentsfocus.com
Creating a Sequence
You create a sequence using the CREATE SEQUENCE statement, which has the following.
SYNTAX:
Where
sequence_name is the name of the sequence.
start_num is the integer to start the sequence. The default start number is 1.
increment_num is the integer to increment the sequence by. The default increment number is 1. The
absolute value of increment_num must be less than the difference between maximum_num and
minimum_num.
maximum_num is the maximum integer of the sequence; maximum_num must be greater than or
equal to start_num, and maximum_num must be greater than minimum_num.
NOMAXVALUE specifies the maximum is 1027 for an ascending sequence or –1 for a descending
sequence. NOMAXVALUE is the default.
minimum_num is the minimum integer of the sequence; minimum_num must be less than or equal
to start_num, and minimum_num must be less than maximum_num.
NOMINVALUE specifies the minimum is 1 for an ascending sequence or –1026 for a descending
sequence. NOMINVALUE is the default.
CYCLE means the sequence generates integers even after reaching its maximum or minimum value.
When an ascending sequence reaches its maximum value, the next value generated is the minimum.
When a descending sequence reaches its minimum value, the next value generated is the maximum.
NOCYCLE means the sequence cannot generate any more integers after reaching its maximum or
minimum value. NOCYCLE is the default.
68
www.studentsfocus.com
cache_num is the number of integers to keep in memory. The default number of integers to cache is
20. The minimum number of integers that may be cached is 2. The maximum integers that may be
cached is determined by the formula CEIL(maximum_num - minimum_num)/ABS(increment_num).
NOCACHE means no caching. This stops the database from pre-allocating values for the sequence,
which prevents numeric gaps in the sequence but reduces performance. Gaps occur because cached
values are lost when the database is shut down. If you omit CACHE and NOCACHE, the database
caches 20 sequence numbers by default.
ORDER guarantees the integers are generated in the order of the request. You typically use ORDER
when using Real Application Clusters, which are set up and managed by database administrators.
NOORDER doesn’t guarantee the integers are generated in the order of the request.
NOORDER is the default.
Example: 1
Command:
SQL> CREATE SEQUENCE seq1
INCREMENT BY 1
START with 1
MAXVALUE 5
MINVALUE 0;
Sequence created.
www.studentsfocus.com
The following is the list of available pseudo columns in Oracle.
ROWNUM - Returns the number indicating in which order Oracle selects rows. First row
selected will be ROWNUM of 1 and second row ROWNUM of 2 and so on.
alter SEQUENCE
seq1 maxvalue 25
INCREMENT BY
2 cycle
cache 2
drop SEQUENCE seq1;
EXAMPLE: 2
70
www.studentsfocus.com
EXAMPLE: 3
EXAMPLE: 4
EXAMPLE: 5
EXAMPLE: 6
TO DROP SEQUENCES
RESULT:
Thus the SQL commands for creation and various operations on Sequence has been verified
and executed successfully.
71
www.studentsfocus.com
Indexes
Ex: No: 03 (3.4)
__ : __ : __
AIM:
To create the Index for the table data and verify the various operations on Index.
ALGORITHM:
STEP 5: Create the Index from the above created table or any data object.
72
www.studentsfocus.com
Index
The indexes are special objects which built on top of tables. The indexes can do operation like
SELECT , DELETE and UPDATE statement faster to manipulate a large amount of data. An INDEX can
also be called a table and it has a data structure. An INDEX is created on columns of a table. One table may
contain one or more INDEX tables
Types of Indexes:
1. Simple Index
2. Composite Index
Command
SAMPLE TABLE:
SQL> SELECT * FROM STUDENT_TBL;
SL_NO REG_NONAME SEX DOB TOTAL_PERCENTAGE MOBILE_NO ADDRESS BLOOD
--------- ------------ -------------------- ------ ----------- ------------------------------- ----------------- ------------- ---------
1 10001 RAM M 11-DEC-85 75 9756435789 PLOT.No:30/6 ABC B+
2 10002 RAJA M 16-JAN-7487.5 9456435458 ABC Nager O+
3 10003 NIRMALA F 22-FEB-87 95.5 9461135411 SAKTHI Nager A+
4 10004 Anitha F 05-MAR-8764.3 9461135555 ANNA Nager AB+
73
www.studentsfocus.com
Simple Index:
Syntax:
Ex:
*notes
Index should be created on columns which we regularly use in the where clause.
When a index is created a separate structure is created with first column is ROWID and
second column as indexed column.
The Rows in the index will be arranged in the ascending order of indexed column.
Composite Index:
Ex:
The above index myCompIndex is used only when both the columns are used in the where clause.
Disadvantages of index:
1. Unique index
2. Non-unique index
74
www.studentsfocus.com
Unique Index:
A unique index is automatically created. When we create a table with primary key constraint
or unique constraint.
Cmd
Non-unique index:
If an index column contains duplicated values they are called as non-unique index.
INDEX_NAME
-----------------------
MYCOMPINDEX
MYINDEX
SYS_C0011164
INDEX_NAME TABLE_NAME
------------------------------ ------------------------------
SYS_C0011164 TBL_PKEY
MYCOMPINDEX STUDENT_TBL
MYINDEX STUDENT_TBL
Query to see list of all the indexes along with column name.
75
www.studentsfocus.com
SQL> Desc user_indexes;
Ex:
Index created.
To drop on index:
Ex:
RESULT:
Thus the SQL commands for creation and various operations on Indexes has been verified
and executed successfully.
76
www.studentsfocus.com
SAVE POINT
Ex: No: 03 (3.5)
__ : __ : __
AIM:
To create the SAVE POINT for the transaction and verify the various operations of TCL commands.
OBJECTIVE:
The SAVEPOINT statement names and marks the current point in the processing of a transaction.
With the ROLLBACK TO statement, savepoints undo parts of a transaction instead of the whole
transaction.
ALGORITHM:
STEP 4: Insert record values into the table or perform any kind of DML operation.
STEP 5: Create the SAVE POINTs for some set of statement on the transaction of database object.
STEP 6: Use the COMMIT command to save the effect of the previous command operation except
DDL command
STEP 7: Use the ROLLBACK TO SP_LABLE / ROLLBACK command for restore the database
status up to the save point
77
www.studentsfocus.com
Syntax:
SAVEPOINT<SAVEPOINT_NAME>;
Ex:
SQL> create table ORDER_PROCESSING(
Order_ID number(3),
Product_ID varchar2(10),
Quantity number(3,2),
Price number(4,2)
);
Table created.
SQL> insert into ORDER_PROCESSING values(101,'RICE-22','6.5','30.50');
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SAVEPOINT A;
Savepoint created.
www.studentsfocus.com
SQL> insert into ORDER_PROCESSING values(106,'SHAMPOO','1','75.50');
1 row created.
SQL> SAVEPOINT B;
Savepoint created.
SQL> SAVEPOINT C;
Savepoint created.
SQL> ROLLBACK TO B;
Rollback complete.
79
www.studentsfocus.com
SQL> SELECT * FROM ORDER_PROCESSING;
ORDER_ID PRODUCT_ID QUANTITY PRICE
---------------- ------------------- -------------- -------------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
103 BAGS 2 95
104 WATER BOTS 2 20
105 EGG 8 40.5
106 SHAMPOO 1 75.5
6 rows selected.
SQL> ROLLBACK TO A;
Rollback complete.
SQL> ROLLBACK;
Rollback complete.
SQL> ROLLBACK;
Rollback complete.
80
www.studentsfocus.com
SQL> SELECT * FROM ORDER_PROCESSING;
ORDER_IDPRODUCT_ID QUANTITY PRICE
---------------- ------------------- ---------------- -----------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
RESULT:
Thus the SQL commands for creation and various operations on transaction (TCL
COMMAND) save point has been verified and executed successfully
81
www.studentsfocus.com
Creating an Employee database to set various constraints in RDBMS
Ex: No: 04
__ : __ : __
AIM:
ALGORITHM:
STEP 4: Insert record values into the table and then check the constraint.
STEP 5: disable the constraints and insert the values into the table.
STEP 6: if you want to re-enable the constraint then enable you can do.
82
www.studentsfocus.com
CONSTRAINTS
Constraints are part of the table definition that limits and restriction on the value entered into
its columns.
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. It
has enforcing the rules for the columns in a table.
a) Domain Integrity
b) Entity Integrity
c) Referential Integrity
TYPES OF CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default
OPERATION ON CONSTRAINT:
i) ENABLE
ii) DISABLE
iii) DROP
83
www.studentsfocus.com
PRIMARY KEY CONSTRAINTS
A primary key avoids duplication of rows and does not allow null values. It can be defined on one or more
columns in a table and is used to uniquely identify each row in a table. These values should never be changed and
should never be null. A table should have only one primary key. If a primary key constraint is assigned to more than
one column or combination of column is said to be composite primary key, which can contain 16 columns.
QUERY: 13
Q13. Write a query to create primary constraints with column
level Syntax: Column level constraints using primary key.
SQL> CREATE<OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE)<TYPE OF
CONSTRAINTS>, COLUMN NAME.1 <DATATYPE> (SIZE) ……………………………);
Command:
SQL> CREATE TABLE TBL_PKEY(
RegNo NUMBER(5) PRIMARY
KEY, Name VARCHAR2(20),
ANY_SUB_MARK NUMBER(3)
);
Table created.
SQL> insert into result values(10001,'raju',75);
1 row created.
SQL> insert into result values(10002,'KAMAL;',100);
1 row created.
SQL> insert into result values(0,'RAVI;',75);
1 row created.
SQL> insert into result values(NULL,'KAVI',65);
1 row created.
SQL> insert into TBL_PKEY values(10001,'raju',75);
1 row created.
SQL> insert into TBL_PKEY values(10002,'raj',85);
1 row created.
SQL> insert into TBL_PKEY values(0,'Kaj',22);
1 row created.
SQL> insert into TBL_PKEY values(NULL,'Kaj',22);
insert into TBL_PKEY values(NULL,'Kaj',22)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SENTHIL"."TBL_PKEY"."REGNO")
SQL> insert into TBL_PKEY values(10002,'RAJAN',95);
insert into TBL_PKEY values(10002,'RAJAN',95)
*
ERROR at line 1:
ORA-00001: unique constraint (SENTHIL.SYS_C0011650) violated
SQL> insert into TBL_PKEY values(10003,'RAJA',85);
1 row created.
SQL> select * FROM TBL_PKEY;
REGNO NAME ANY_SUB_MARK
----------- ------------- -----------------------------
10001 raju 75
10002 raj 85
0 Kaj 22
10003 RAJA 85
84
www.studentsfocus.com
Column level constraints using primary key with naming convention:
QUERY: 14
Q14. Write a query to create primary constraints with column level with naming convention
Syntax: syntax for column level constraints using primary key.
SQL >CREATE <OBJ.TYPE><OBJ.NAME> (
COL NAME.1 <DATATYPE> (SIZE)CONSTRAINTS <NAME OF CONSTRAINTS><TYPE OF
CONSTRAINTS>, COL NAME.2 <DATATYPE> (SIZE)…………………………….…………);
Command:
SQL>CREATE TABLE EMPLOYEE (
EMPNO NUMBER (4) CONSTRAINT EMP_EMPNO_PK PRIMARY KEY,
ENAMEVARCHAR2 (10),JOB VARCHAR2 (6),SAL NUMBER (5),DEPTNO NUMBER (7));
Table level primary key constraints:
QUERY: 15
Q15. Write a query to create primary constraints with table level with naming convention
Syntax: The syntax for table level constraints using primary key
SQL: >CREATE <OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE>
(SIZE), COLUMN NAME.1 <DATATYPE> (SIZE),
CONSTRAINTS <NAME OF THE CONSTRAINTS><TYPE OF THE CONSTRAINTS>);
Command:
SQL>CREATE TABLE EMPLOYEE (EMPNO NUMBER(6),ENAME VARCHAR2(20),JOB
VARCHAR2(6), SAL NUMBER(7), DEPTNO NUMBER(5),
CONSTRAINT EMP_EMPNO_PK PRIMARY KEY(EMPNO));
85
www.studentsfocus.com
REFERENCE /FOREIGN KEY CONSTRAINT
It enforces relationship between tables. To establish parent-child relationship between 2 tables having a
common column definition, we make use of this constraint. To implement this, we should define the column in the
parent table as primary key and same column in the child table as foreign key referring to the corresponding parent
entry.
Foreign key
A column or combination of column included in the definition of referential integrity, which would refer to a
referenced key.
Referenced key
It is a unique or primary key upon which is defined on a column belonging to the parent table.
Column level foreign key constraint
QUERY: 17
Q.17. Write a query to create foreign key constraints with column level
Parent Table:
Syntax: Syntax for Column level constraints Using Primary key
SQL:>CREATE <OBJ.TYPE><OBJ.NAME> (
COLUMN NAME.1 <DATATYPE>(SIZE)<TYPE OF CONSTRAINTS> ,
COLUMN NAME.1 <DATATYPE> (SIZE)………………………);
Command:
SQL> CREATE TABLE DEPT(
DEPTNO NUMBER(3) PRIMARY KEY,
DNAME VARCHAR2(20),LOCATION VARCHAR2(15));
Table created.
SQL> desc DEPT;
Name Null? Type
----------------- ---------------- --------------------
DEPTNO NOT NULL NUMBER(3)
DNAME VARCHAR2(20)
LOCATION VARCHAR2(15)
SQL> select * from DEPT;
DEPTNO DNAME LOCATION
------------ ---------------- ---------------
101 kamal chennai
102 rajini madurai
103 Ajith kovai
Child Table:
Syntax: The syntax for column level constraints using foreign key.
SQL:>CREATE <OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE>(SIZE),
COLUMN NAME2 <DATATYPE> (SIZE) REFERENCES <TABLE NAME>(COLUMN NAME> ….);
Command:
SQL> CREATE TABLE EMPL(EMPNO NUMBER(4),
DEPTNO NUMBER(3) REFERENCES DEPT(DEPTNO),
DESIGN VARCHAR2(10));
Table created.
86
www.studentsfocus.com
SQL> desc EMPL;
Name Null? Type
-------------------------- ------------- ----------------------------
EMPNO NUMBER(4)
DEPTNO NUMBER(3)
DESIGN VARCHAR2(10)
QUERY: 18
Q.18. Write a query to create foreign key constraints with column level
Parent Table:
Syntax: The syntax for column level constraints using primary key.
SQL :> CREATE<OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE>(SIZE)<TYPE OF
CONSTRAINTS>,COLUMN NAME.1 <DATATYPE> (SIZE)…);
Child Table:
Syntax: syntax for column level constraints using foreign key.
SQL :> CREATE<OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE>(SIZE) ,
COLUMN NAME2 <DATATYPE> (SIZE) CONSTRAINT <CONST.NAME>REFERENCES <TABLE NAME>
(COLUMN NAME>…);
Command:
SQL>CREATE TABLE DEPT (DEPTNO NUMBER (2) PRIMARYKEY,
DNAME VARCHAR2 (20), LOCATION VARCHAR2 (15));
SQL>CREATE TABLE EMP4A (EMPNO NUMBER (3),
DEPTNO NUMBER (2) CONSTRAINT EMP4A_DEPTNO_FK REFERENCES DEPT (DEPTNO),
DESIGN VARCHAR2 (10));
87
www.studentsfocus.com
Table level foreign key constraints:
QUERY: 19
Q.19. Write a query to create foreign key constraints with Table level.
Parent Table:
Syntax:
SQL :> CREATE<OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE>(SIZE) <TYPE OF
CONSTRAINTS>, COLUMN NAME.1 <DATATYPE> (SIZE)…);
Child Table:
Syntax: The syntax for table level constraints using foreign key.
SQL :> CREATE<OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1
<DATATYPE>(SIZE), COLUMN NAME2 <DATATYPE> (SIZE),
CONSTRAINT <CONST.NAME>REFERENCES <TABLE NAME> (COLUMN NAME>);
Command:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY,
DNAME VARCHAR2(20),LOCATION VARCHAR2(15));
Command:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY, DNAME VARCHAR2(20),
LOCATION VARCHAR2 (15));
SQL>CREATE TABLE EMP5 (EMPNO NUMBER(3), DEPTNO NUMBER (2), DESIGN VARCHAR2 (10));
www.studentsfocus.com
CHECK CONSTRAINT
Check constraint can be defined to allow only a particular range of values .when the manipulation violates
this constraint, the record will be rejected. Check condition cannot contain sub queries.
QUERY: 21
Command:
DEPTNO NUMBER(2));
QUERY: 22
Command:
QUERY:23
Q.23. Write a query to create Check constraints with table level using alter command.
Command:
www.studentsfocus.com
UNIQUE CONSTRAINT
It is used to ensure that information in the column for each record is unique, as with telephone or drivers
license numbers. It prevents the duplication of value with rows of a specified column in a set of column. A column
defined with the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination of column cannot be specified.
Maximum combination of columns that a composite unique key can contain is 16.
QUERY:26
Q.26. Write a query to create unique constraints with table level
Syntax: syntax for table level constraints with check using alter.
Command:
SQL>CREATE TABLE EMP12(EMPNO NUMBER(3),ENAME VARCHAR2(20),DESIGN
VARCHAR2(15), SAL NUMBER(5));
SQL>ALTER TABLE EMP12 ADD CONSTRAINT EMP12_DESIGN_UKUNIQUE(DESING);
90
www.studentsfocus.com
NOT NULL CONSTRAINTS
While creating tables, by default the rows can have null value .the enforcement of not null constraint in a
table ensure that the table contains values.
QUERY: 27
Q.27. Write a query to create Not Null constraints with column level
Syntax: syntax for column level constraints with not null
Command:
NULL CONSTRAINTS
Setting null value is appropriate when the actual value is unknown, or when a value would not be meaningful.
Not null Integrity constraint cannot be defined using the alter table command when the table contain rows.
QUERY:28
Command:
91
www.studentsfocus.com
DEFAULT CONSTRAINTS
Default constraints assign the default values if the values is not passed at the time of inserting the values to the table
QUERY:28
Command:
REGNO NUMBER(5),
NAME VARCHAR2(20),
);
Table created.
1 row created.
1 row created.
1 row created.
92
www.studentsfocus.com
DISABLING AND DROPPING CONSTRAINTS
USING DISABLE/ENABLE
Whenever a constraint is created for a column(s), every time an entry is made to the column , it must be
evaluated to determine whether the value is allowed in that column(it checks doesn‘t Violate the constraint). If a
large block of data is being added to a table the validation process can severely slow down the oracle server‘s
processing speed. You are certain that the data being added to a table adheres to the constraints then disable the
constraints while adding that particular block of data of data to the table.
To DISABLE a constraint, issue an ALTER TABLE command and change the status of the constraint to
DISABLE. At a later time can reissue the ALTER TABLE command and change the status of the constraint back to
ENABLE Sometimes, temporarily disable or drop a constraint.
Constraint Disable
QUERY:29
RESULT:
Thus the SQL commands for Creating an Employee database to set various constraints has been
verified and executed successfully.
93
www.studentsfocus.com
CREATING RELATIONSHIP BETWEEN THE DATABASES IN RDBMS
AIM:
To Execute and verify The SQL Commands For Set Operators Implementation In Relational Model
.
OBJECTIVE:
Set operators are used to retrieve the data from two or multiple tables.
They are different types.
Union
Union all
Intersect
Minus
ALGORITHM:
STEP 1: Start
STEP 2: Create two different tables with its essential attributes.
STEP 3: Insert attribute values into the tables.
STEP 4: Create the result for the various set operation.
STEP 5: Execute Command and extract information from the tables.
STEP 6: Stop
SAMPLE TABLES
94
www.studentsfocus.com
UNION
This will combine the records of multiple tables having the same structure.
Ex:
SQL> select * from student_IT union select * from student_ECE;
REG_NO NAME BRANC SUBJECT
----------- -------- ----------- ------------------
10001 ram IT DATA STRUCTURE
10002 Sam IT DATABASE SYSTEM
10003 Tam IT WEB TECHNOLOGY
10004 RAJ IT DSP
10005 TAJ IT DIP
10006 khan IT WEB TECHNOLOGY
30001 RAMUECE DIP
30002 SAMU ECE DSP
30003 TAMU ECE CIRCUIT DESIGN
30004 RAJU ECE ELECTRO MECHANICS
30005 RAJA ECE CIRCUIT DESIGN
11 rows selected.
UNION ALL
This will combine the records of multiple tables having the same structure but including duplicates.
Ex:
SQL> select * from student_IT union all select * from student_ECE;
REG_NO NAME BRANC SUBJECT
------------- ----------- ----------- --------------------
10001 ram IT DATA STRUCTURE
10002 Sam IT DATABASE SYSTEM
10003 Tam IT WEB TECHNOLOGY
10004 RAJ IT DSP
10005 TAJ IT DIP
10006 khan IT WEB TECHNOLOGY
30005 RAJA ECE CIRCUIT DESIGN
30001 RAMU ECE DIP
30002 SAMU ECE DSP
30003 TAMU ECE CIRCUIT DESIGN
30004 RAJU ECE ELECTRO MECHANICS
30005 RAJA ECE CIRCUIT DESIGN
30005 RAJA ECE CIRCUIT DESIGN
13 rows selected.
INTERSECT
This will give the common records of multiple tables having the same structure.
Ex:
www.studentsfocus.com
MINUS
This will give the records of a table whose records are not in other tables having the same structure.
Ex:
RESULT:
Thus the SQL commands for SET operators has been verified and executed successfully.
96
www.studentsfocus.com
CREATING RELATIONSHIP BETWEEN THE DATABASES IN RDBMS
AIM:
Nested Query can have more than one level of nesting in one single query. A SQL nested query is
a SELECT query that is nested inside a SELECT, UPDATE, INSERT, or DELETE SQL query.
ALGORITHM:
STEP 4: Create the Nested query from the above created table.
97
www.studentsfocus.com
Table -1
TABLE- 2
98
www.studentsfocus.com
Syntax:
GENERAL SYNTAX FOR NESTED QUERY:
SQL> SELECT "COLUMN_NAME1"
FROM "TABLE_NAME1"
WHERE "COLUMN_NAME2"
[COMPARISON OPERATOR] (SELECT "COLUMN_NAME3" FROM "TABLE_NAME2"
WHERE [CONDITION])
Syntax: syntax nested query statement.
RESULT:
Thus the SQL commands for to implementation of nested queries has been verified and
executed successfully.
99
www.studentsfocus.com
CREATING RELATIONSHIP BETWEEN THE DATABASES IN RDBMS
__ : __ : __
AIM:
To execute and verify the SQL commands for various join operation.
ALGORITHM:
JOINS:
Types of Joins:
1. EQUI_JOIN
2. NON EQUI_JOIN
3. SELF JOIN
4. OUTER JOIN
100
www.studentsfocus.com
1. EQUI_JOIN:
Ex:
select empno, ename, dname from emp, dept where emp.deptno = dept.deptno;
Note:
Ex:
Note:
we need to mention table name dot column(emp.deptno) name for the common column to resolve
the any table.
101
www.studentsfocus.com
Ex:
To improve the performance of the join we need mention table name dot column name for all the columns.
Ex:
Table alias:
By using a table alias length of the table reduces and at the same time performance is maintains.
Table alias are create in same clause can be used in select clause as well as where clause.
Table alias is temporary once the query is executed the table alias are losed.
Ex:
City State
Newyork AP
Dallas Mh
Ex:
www.studentsfocus.com
NON EQUI JOIN:
When we do not use NON EQUI JOIN to operator in the join condition is NON EQUI JOIN.
Ex:
SELF JOIN:
When a table is joining to it self it is called self join. In self joins we need to create two table
aliases for the same table.
103
www.studentsfocus.com
CARTESIAN PRODUCT:
When tables are joined without any join condition it is called Cartesian product. In the result we
get all possible combination.
ANSI JOINS:
INNER JOINS:
Ex:
Ex:
SQL>Select empno, ename, sal, deptno, dname,loc from NATURAL JOIN dept;
Ex:
DEFAULT:
Ex:
Sname varchar2(10),
104
www.studentsfocus.com
SQL>Insert into stu1(sno, sname) values(101,’malli’);
SUPER KEY:
Combination of columns which can be used unique key identify every row is called as super
key. Table object
Column Attributes
Row Tuple/Record
OUTER JOINS:
SQL Syntax:
ANSI SYSTAX:
105
www.studentsfocus.com
LEFT OUTER JOIN:
SQL Syntax:
ANSI SYNTAX:
ANSI SYNTAX:
RESULT:
Thus the SQL commands to implementation the join operations has been verified and
executed successfully.
106
www.studentsfocus.com
Study of PL/SQL block.
Ex: No: 06
__ : __ : __
AIM:
To write a PL/SQL block using different control (if, if else, for loop, while loop,…) statements.
OBJECTIVE:
PL/SQL Control Structure provides conditional tests, loops, flow control and branches that let
to produce well-structured programs
PL/SQL
PL/SQL is Oracle’s procedural language extension to SQL. PL/SQL allows you to mix SQL
statements with procedural statements like IF statement, Looping structures etc.
3. We can have user defined error massages by using concept of exception handling.
PL/SQL Block:
A PL/SQL programs called as PL/SQL block.
107
www.studentsfocus.com
PL/SQL Block:
DECLARE
Declaration of variable
Declaration of cursor---------- (OPTIONAL)
Declaration of exception
BEGIN
EXCEPTION
END;
Declare:
This section is used to declare local variables, cursors, Exceptions and etc. This section is optional.
Executable Section:
This section contains lines of code which is used to complete table. It is mandatory.
Exception Section:
This section contains lines of code which will be executed only when exception is raised.
This section is optional.
This will be used to display the output of the PL/SQL programs. By default this will be off.
Syntax:
Ex:
108
www.studentsfocus.com
BLOCK TYPES
Anonymous blocks
Named blocks
Labeled blocks
Subprograms
Triggers
ANONYMOUS BLOCKS
Anonymous blocks implies basic block structure.
Ex:
Q : program to display the string “”
BEGIN
DBMS_OUTPUT.PUT_LINE(‘My first program’):
END;
/
LABELED BLOCKS
Labeled blocks are anonymous blocks with a label which gives a name to the block.
Ex:
<<my_bloock>>
BEGIN
Dbms_output.put_line(‘My first program’):
END;
SUBPROGRAMS
Subprograms are procedures and functions. They can be stored in the database as stand-alone
objects, as part of package or as methods of an object type.
TRIGGERS
Triggers consist of a PL/SQL block that is associated with an event that occurs in the database.
NESTED BLOCKS
A block can be nested within the executable or exception section of an outer block.
IDENTIFIERS
Identifiers are used to name PL/SQL objects, such as variables, cursors, types and subprograms.
109
www.studentsfocus.com
QUOTED IDENTIFIERS
If you want to make an identifier case sensitive, include characters such as spaces or use a
reserved word, you can enclose the identifier in double quotation marks.
Ex:
DECLARE
"a" number := 5;
"A" number := 6;
BEGIN
END;
Output:
a=6
A=6
110
www.studentsfocus.com
COMMENTS
Comments improve readability and make your program more understandable. They are ignored
by the PL/SQL compiler.
Multiline comments
A single-line comment can start any point on a line with two dashes and continues until the end
of the line.
Ex:
BEGIN
END;
MULTILINE COMMENTS
Multiline comments start with the /* delimiter and ends with */ delimiter.
Ex:
BEGIN
END;
VARIABLE DECLERATIONS
Ex:
DECLARE
a number;
b number := 5;
c number default 6;
111
www.studentsfocus.com
CONSTANT DECLERATIONS
To declare a constant, you include the CONSTANT keyword, and you must supply a default value.
Ex:
DECLARE
b constant number := 5;
You can also specify that the variable must be not null.
Ex:
DECLARE
ANCHORED DECLERATIONS
Scalar anchoring
Record anchoring
SCALAR ANCHORING
Use the %TYPE attribute to define your variable based on table’s column of some other
PL/SQL scalar variable.
Ex:
DECLARE
dno dept.deptno%type;
a t_number;
V_sno t_sno;
112
www.studentsfocus.com
RECORD ANCHORING
Use the %ROWTYPE attribute to define your record structure based on a table.
Ex:
DECLARE
V_dept dept%rowtype;
PROGRAMMER-DEFINED TYPES
With the SUBTYPE statement, PL/SQL allows you to define your own subtypes or aliases
of predefined datatypes, sometimes referred to as abstract datatypes.
Constrained
Unconstrained
CONSTRAINED SUBTYPE
A subtype that restricts or constrains the values normally allowd by the datatype itself.
Ex:
In the above declaration a variable that is declared as positive can store only ingeger
greater than zero even though binary_integer ranges from -2147483647..+2147483647.
UNCONSTRAINED SUBTYPE
A subtype that does not restrict the values of the original datatype in variables declared with the
subtype.
Ex:
113
www.studentsfocus.com
DATATYPE CONVERSIONS
PL/SQL can handle conversions between different families among the datatypes.
Explicit conversion
Implicit conversion
EXPLICIT CONVERSION
IMPLICIT CONVERSION
Ex:
DECLARE
a varchar(10);
BEGIN
END;
In the above variable a is char type and deptno is number type even though, oracle will
automatically converts the numeric data into char type assigns to the variable.
114
www.studentsfocus.com
VARIABLE SCOPE AND VISIBILITY
The scope of a variable is the portion of the program in which the variable can be accessed. For
PL/SQL variables, this is from the variable declaration until the end of the block. When a variable goes
out of scope, the PL/SQL engine will free the memory used to store the variable.
The visibility of a variable is the portion of the program where the variable can be accessed
without having to qualify the reference. The visibility is always within the scope. If it is out of scope, it is
not visible.
Ex1:
DECLARE
a number; -- scope of a
BEGIN
--------
DECLARE
b number; -- scope of b
BEGIN
-----
END;
------
END;
Ex2:
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
END;
-----
END;
Ex3:
<<my_block>>
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
-- number type b is available using <<my_block>>.b
END;
------
END;
115
www.studentsfocus.com
PL/SQL CONTROL STRUCTURES
PL/SQL has a variety of control structures that allow you to control the behaviour of the block
as it runs. These structures include conditional statements and loops.
If-then-
else Case
o Case with no else
o Labeled case
o Searched
case Simple loop
While loop
For loop
Goto and Labels
IF-THEN-ELSE
Syntax:
If <condition1> then
Sequence of statements;
Elseif <condition1> then
Sequence of statements;
……
Else
Sequence of statements;
End if;
Ex:
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'); elseif dno = 20 then
dbms_output.put_line('Location is
DALLAS'); elseif dno = 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end if;
END;
Output:
Location is NEW YORK
116
www.studentsfocus.com
CASE
Syntax:
Case test-variable
.
.
When valuen then sequence of statements;
End case;
Ex:
DECLARE
dno number(2);
BEGIN
when 10 then
dbms_output.put_line('Location is NEW
YORK'); 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;
Output:
117
www.studentsfocus.com
CASE WITHOUT ELSE
Syntax:
Case test-variable
……
End case;
Ex:
DECLARE
dno number(2);
BEGIN
when 10 then
dbms_output.put_line('Location is NEW
YORK'); 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;
Output:
118
www.studentsfocus.com
LABELED CASE
Syntax:
<<label>>
Case test-variable
When value1 then sequence of statements;
When value2 then sequence of statements;
……
When valuen then sequence of statements;
End case;
Ex:
DECLARE
dno number(2);
BEGIN
dbms_output.put_line('Location is NEW
YORK'); 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
my_case;
END;
Output:
119
www.studentsfocus.com
SEARCHED CASE
Syntax:
Case
……
End case;
Ex:
DECLARE
dno number(2);
BEGIN
case dno
dbms_output.put_line('Location is NEW
YORK'); when dno = 20 then
dbms_output.put_line('Location is
DALLAS'); when dno = 30 then
dbms_output.put_line('Location is
CHICAGO'); when dno = 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
120
www.studentsfocus.com
SIMPLE LOOP
Syntax:
Loop
Sequence of statements;
End loop;
If <condition> then
Exit;
End if;
Ex:
DECLARE
i number := 1;
BEGIN
loop
dbms_output.put_line('i = ' ||
i); i := i + 1;
end loop;
END;
Output:
i=1
i=2
i=3
i=4
i=5
121
www.studentsfocus.com
WHILE LOOP
Syntax:
Sequence of statements;
End loop;
Ex:
DECLARE
i number := 1;
BEGIN
i := i + 1;
end loop;
END;
Output:
i=1
i=2
i=3
i=4
i=5
122
www.studentsfocus.com
FOR LOOP
Syntax:
Sequence of statements;
End loop;
Ex1:
BEGIN
end loop;
END;
Output:
i=1
i=2
i=3
i=4
i=5
Ex2:
BEGIN
end loop;
END;
Output:
i=5
i=4
i=3
i=2
i=1
123
www.studentsfocus.com
GOTO AND LABELS
Syntax:
Goto label;
Where label is a label defined in the PL/SQL block. Labels are enclosed in double angle brackets.
When a goto statement is evaluated, control immediately passes to the statement identified by
the label.
Ex:
BEGIN
if i = 4 then
goto exit_loop;
end if;
end loop;
<<exit_loop>>
Null;
END;
Output:
i=1
i=2
i=3
i=4
Restrictions on GOTO
124
www.studentsfocus.com
RESULT:
Thus the Study of PL/SQL block has been implemented by various control structure are verified and
executed successfully.
125
www.studentsfocus.com
Write a PL/SQL block to satisfy some conditions by accepting input from the user.
Ex: No: 07
__ : __ : __
AIM:
To implement the PL/SQL block to satisfy some conditions by accepting input from the user.
ALGORITHM:
STEP 7: if you want to access the table use the SQL statement.
STEP 8: if you want to solve any exception, write the exception name with WHEN stetment
STEP 10: Give the input values or validate the information from the tables.
126
www.studentsfocus.com
Q1: Write PL/SQL block which will calculate some of two numbers and display the output?
DECLARE
A number(2);
B number(2);
C number(3);
BEGIN
A := 10;
B := 20;
C := A + B;
DBMS_OUTPUT.PUT_LINE(C);
DBMS_OUTPUT.PUT_LINE( ‘sum of two numbers’ || C);
END;
/
Output:
30
sum of two numbers 30
PL/SQL procedure successfully completed.
Q2: Write a PL/SQL block which accepts employee number and increment is salary by 1000?
DECLARE
A number(4);
A := &Empno;
Update emp set sal = sal + 1000 where Empno = A;
END;
/
Q3: Write a PL/SQL block which empno and delete that row from the emp table?
DECLARE
A number(4);
BEGIN
A := &Empno;
Delete from emp where Empno = A;
END;
/
127
www.studentsfocus.com
Q4: PL/SQL for reversing the given string
Algorithm:
1. Get the input string.
2. Find the length of the string.
3. Extract the characters one by one from the end of the string.
4. Concatenate the extracted characters.
5. Display the concatenated reversed string.
6. Stop the program.
Program:
declare
b varchar2(10) := '&b';
c varchar2(10);
l number(2);
i number(2);
g number(2);
d varchar2(10);
begin
l:=length(b);
g:=l;
for i in 1..l
loop
c:=substr(b,g,1);
g := g - 1;
d := d ||
c; end loop;
dbms_output.put_line('revised string
is'); dbms_output.put_line(d);
end;
OUTPUT:
128
www.studentsfocus.com
Q5: PL/SQL for Fibonacci Series.
Algorithm:
Program:
declare
a number(3);b number(3);c number(3);n
number(3):=&n; negative exception;
begin
if n < 2 then
raise negative;
end if;
a := 0;b := 1;
dbms_output.put_line('fibonacci series
is'); dbms_output.put_line(a);
dbms_output.put_line(b);
for i in 3 ..
n loop
c := a + b;
dbms_output.put_line(c);
a := b;
b :=
c; end loop;
exception
when negative then
dbms_output.put_line('n should be greater than 1');
end;
SQL> /
Enter value for n:10
old 5: n number(3):=&n;
new 5:n number(3):=10;
Fibonacci
0
1
1
129
www.studentsfocus.com
2
3
5
8
13
21
34
PL/SQL procedure successfully completed
Algorithm:
Declare
N number;
S number;
D number;
Begin
N:=&n;
S:=0;
While(n!=0)
Loop
D=n%10;
S:=s+(D*D*D);
N:=floor(n/10);
End loop;
If (DUP=S) then
DBMS_output.put_line(‘number is armstrong’);
Else
DBMS_output.put_line(‘number is not armstrong’);
End if;
End;
130
www.studentsfocus.com
Q7: Write a program to generate all prime numbers below 100.
Declare
I number;
J number;
C number;
Begin
While(i<=100)
Loop
C:=0;
J:=1;
While(j<=i)
Loop
If(floor(i%j)=0) then
C:= C+1;
End if;
J:=j+1;
End loop;
If(c=2) then
Dbms_output.put_line(i);
End if;
Endloop;
End;
OUTPUT:
11
99
131
www.studentsfocus.com
Q8: Write a program to demonstrate %type and %rowtype attributes
Declare
My_Empno emp.empno%type;
My_Ename emp.ename%type;
My_Emprow emp%rowtype; No
number;
Begin
No:=&no;
Select empno,ename into my_empno,my_ename from emp where
empno=no; If(SQl%rowcount=1) then
Dbms_output.put_line(‘empno is’ || my_empno || ‘ename is ‘ || my_ename);
Else
Dbms_output.put_line( ‘error’);
End if;
Select * into my_emprow from emp where
empno=no; If(SQl%rowcount=1) then
Dbms_output.put_line(‘empno is’ || my_emprow.empno || ‘ename is ‘ ||
my_emprow.ename); Else
Dbms_output.put_line( ‘error’);
End if;
End;
7788
OUTPUT
RESULT:
Thus the PL/SQL block to satisfy some conditions by accepting input from the user has been verified and
executed successfully.
132
www.studentsfocus.com
Write a PL/SQL block that handles all types of exceptions.
Ex: No: 08
__ : __ : __
AIM:
ALGORITHM:
STEP3: write the PL/SQL program that to handle the exception on exception block
STEP4: Execute the PL/SQL program and give the input values or make the error on the table data.
EXCEPTIONS:
In PL/SQL, errors and warnings are called as exceptions. Whenever a predefined error occurs in the
program, PL/SQL raises an exception. For example, if you try to divide a number by zero then PL/SQL
raises an exception called ZERO_DIVIDE and if SELECT can not find a record then PL/SQL raises
exception NO_DATA_FOUND.
PL/SQL has a collection of predefined exceptions. Each exception has a name. These exceptions are
automatically raised by PL/SQL whenever the corresponding error occurs.
In addition to PL/SQL predefined exceptions, user can also create his own exceptions to deal with
errors in the applications.
They are three types of Exceptions.
1. ORACLE Predefined Exception
133
www.studentsfocus.com
SYNTAX OF EXCEPTION HANDLING
WHEN exception-1 [or exception -2] ...
THEN statements;
[WHEN exception-3 [or exception-4] ... THEN
statements; ] ...
[WHEN OTHERS THEN
statements; ]
select
… exception
when no_data_found
then statements;
end;
Output:
Q: The following exception handling part takes the same action when either NO_DATA_FOUND or
TOO_MANY_ROWS exceptions occur.
declare
...
begin
select ...
exception
when no_data_found or too_many_rows
then statements;
end;
Output:
134
www.studentsfocus.com
Q: The following snippet handles these two exceptions in different ways.
declare
...
begin
select ...
exception
when no_data_found
then statements;
when too_many_rows
then statements;
end;
Output:
WHEN OTHERS is used to execute statements when an exception other than what are mentioned in
exception handler has occurred.
declare
newccode varchar2(5) := null;
begin
update courses set ccode = newccode where ccode =
'c'; exception
when dup_val_on_index then
dbms_output.put_line('Duplicate course code');
when others then dbms_output.put_line(
sqlerrm);
end;
Output:
135
www.studentsfocus.com
Predefined exceptions
PL/SQL has defined certain common errors and given names to these errors, which are called as
predefined exceptions.
Each exception has a corresponding Oracle error code. The following is the list of predefined
exceptions and the corresponding Oracle error code.
NO_DATA_FOUND:
This Exception is Raised if a SELECT INTO statement returns no rows or if you reference an
un-initialized row in a PL/SQL table.
Ex:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select sal INTO L_sal from emp where empno =
&empno; DBMS_OUTPUT.PUT_LINE(L_sal);
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when NO_DATA_FOUND then
DBMS_OUTPUT.PUT_LINE( ‘INVALID EMPNO’);
END;
/
136
www.studentsfocus.com
TOO_MANY_ROWS:
This Exception is Raised if a SELECT INTO statement returns more than one row.
Ex:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select sal INTO L_sal from emp where deptno =
30; DBMS_OUTPUT.PUT_LINE(L_sal);
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when TOO_MANY_ROWS then
DBMS_OUTPUT.PUT_LINE( ‘MORE THEN ONE ROW RETURNED’);
END;
/
ZERO_DIVIDE:
Declare
A Number;
Begin
A :=
5/0; Exception
when ZERO_DIVIDE then
DBMS_OUTPUT.PUT_LINE( ‘DO NOT DIVIDE BY 0’ );
END;
/
Note:
This Exception is raised when we try to divided by zero.
137
www.studentsfocus.com
VALUE_ERROR:
This Exception is raised when there is miss match with the value and data type of local variable
or size of local variables.
Ex 1:
Declare
L_sal emp.sal%type;
Begin
DBMS_OUTPUT.PUT_LINE( ‘WELCOME’ );
Select ename INTO L_sal from emp where empno =
7521; DBMS_OUTPUT.PUT_LINE(L_sal);
DBMS_OUTPUT.PUT_LINE( ‘THANK YOU’ );
EXCEPTION
when VALUE_ERROR then
DBMS_OUTPUT.PUT_LINE( ‘please check the local variables’);
END;
/
Ex 2:
Declare
A number(3);
Begin
A :=
1234; Exception
when VALUE_ERROR then
DBMS_OUTPUT.PUT_LINE( ‘PLEASE CHECK THE LOCAL VARIABLES’ );
END;
/
This Exception is raised when we try to insert a duplicate value in primary key constraint.
Ex:
Begin
DBMS_OUTPUT.PUT_LINE( ‘welcome’ );
Insert into student values(104, ‘ARUN’,60);
DBMS_OUTPUT.PUT_LINE( ‘Thank you’ );
Exception
when DUP_VAL_ON_INDEX then
DBMS_OUTPUT.PUT_LINE(‘ Do not insert duplicates’ );
END;
/
The above program works on an assumption the table student for if having a primary key SNO column with
value 104.
138
www.studentsfocus.com
WHEN OTHERS:
When others are a universal Exception angular this can catch all the Exceptions.
Declare
L_sal number(4);
A number;
Begin
DBMS_OUTPUT.PUT_LINE( ‘Welcome’ );
Select sal INTO L_SAL from emp where deptno = &deptno;
DBMS_OUTPUT.PUT_LINE(‘The sal is ….’||L_sal);
A :=10/0;
DBMS_OUTPUT.PUT_LINE( ‘Thank you’ );
Exception
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( ‘please check the code’ );
END;
/
ERROR REPORTING FUNCTIONS:
They are two Error Reporting functions.
1. SQLCODE
2. SQLERRM
These error reporting functions are used in when others clause to identified the exception which is raised.
1. SQLCODE: It returns ERRORCODE
www.studentsfocus.com
NESTED BLOCK:
Declare
A number := 10;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO1’);
Declare
B number := 20;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO2’);
DBMS_OUTPUT.PUT_LINE(B);
DBMS_OUTPUT.PUT_LINE(A);
END;
DBMS_OUTPUT.PUT_LINE(‘HELLO3’);
DBMS_OUTPUT.PUT_LINE(B); --ERROR
END;
/
Note:
outer block variables can be accessed in nested block nested block variables can not be accessed
in outer block.
EXCEPTION PROPAGATION:
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO1’);
L_SAL EMP.SAL%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘HELLO2’);
Select sal INTO L_SAL from emp where empno = 1111;
DBMS_OUTPUT.PUT_LINE(‘HELLO3’);
END;
DBMS_OUTPUT.PUT_LINE(‘HELLO4’);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘HELLO5’);
END;
/
140
www.studentsfocus.com
ORALE NON PREDEFINED EXCEPTIONS:
These Exceptions will have only Exception number. But does not have Exception
name. Steps to handle non predefined exceptions.
Syntax:
Step1: Declare the Exception
<EXCEPTION_NAME> EXCEPTION;
Step2: Associate the Exception
PRAGMA EXCEPTION_INIT(<EXCEPTION_NAME>,<EXCEPTION NO>);
Step3: Catch the Exception
WHEN <EXCEPTION_NAME> THEN
------------------
------------------
------------------
END;
/
ORA -2292 is an example of non predefined exception.
This exception is raised when we delete row from a parent table. If the corresponding value
existing the child table.
Declare
MY_EX1 Exception; --step1
PRAGMA EXCEPTION_INIT(MY_EX1, -2292); --step2
Begin
DBMS_OUTPUT.PUT_LINE(‘Welcome’);
Select from student where eno = 102;
EXCEPTION
WHEN MY_EX1 THEN --step3
DBMS_OUTPUT.PUT_LINE(‘do not delete pargma table’);
END;
/
Pragma Exception_init is a compiler directive which is used to associated an Exception name to the
predefined number.
141
www.studentsfocus.com
USER DEFINED EXCEPTION:
These Exceptions are defined and controlled by the user. These Exceptions neither have
predefined name nor have predefined number. Steps to handle user defined Exceptions.
Declare
MY_EX1 EXCEPTION; --Step1
L_SAL EMP.SAL%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘welcome’);
Select SAL INTO L_SAL from emp where empno =
&empno; IF L_SAL > 2000 THEN
RAISE MY_EX1; --Step2
ENDIF;
DBMS_OUTPUT.PUT_LINE(‘The sal is … ‘||L_sal);
DBMS_OUTPUT.PUT_LINE(‘Thank you’);
EXCEPTION
WHEN MY_EX1 THEN --Step3
DBMS_OUTPUT.PUT_LINE(‘Sal is two high’);
END;
/
Note: When others should be the last handler of the exception section other wise we get a compiler ERROR.
142
www.studentsfocus.com
RAISE_APPLICATION_ERROR:
Declare
L_sal emp.sal%TYPE;
Begin
DBMS_OUTPUT.PUT_LINE(‘Welcome’);
Insert INTO dept values (08,’arun’,70);
RESULT:
Thus the PL/SQL block that handles all types of exceptions has been verified and
executed successfully.
143
www.studentsfocus.com
Creation of Procedures.
Ex: No: 09
__ : __ : __
AIM:
To write a PL/SQL block to display the student name, marks whose average mark is above 60%.
ALGORITHM:
STEP3: Insert the values into the table and Calculate total and average of each student
STEP4: Execute the procedure function the student who get above 60%.
144
www.studentsfocus.com
SYNTAX
{IS|AS}
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
END [name];
EXECUTION:
SQL> SET SERVEROUTPUT ON
I) PROGRAM:
PROCEDURE USING POSITIONAL PARAMETERS:
SETTING SERVEROUTPUT ON:
Procedure created.
www.studentsfocus.com
II) PROGRAM:
IS
BEGIN
TOT := N1 + N2;
END;
Output:
Procedure created.
SQL> PRINT T
----------
99
146
www.studentsfocus.com
PROCEDURE FOR GCD NUMBERS
III) PROGRAM:
SQL> create or replace procedure
pro is
a number(3);
b number(3);
c number(3);
d number(3);
begin
a:=&a;
b:=&b;
if(a>b) then
c:=mod(a,b);
if(c=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(b);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(c);
end if;
else
d:=mod(b,a);
if(d=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(a);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(d);
end if;
end if;
end;
/
147
www.studentsfocus.com
Out put:
Enter value for a:
8 old 8: a:=&a;
new 8: a:=8;
Procedure created.
RESULT:
Thus the implementation of PL/SQL procedure has been verified and executed successfully.
148
www.studentsfocus.com
CREATION OF DATABASE TRIGGERS AND FUNCTIONS
Ex: No: 10
__ : __ : __
AIM:
To the Implementation of Triggers for the purpose of monitor the database object(table..etc) for any
ALGORITHM:
6. Specify DML statement that invokes the trigger - UPDATE, DELETE, or INSERT
11. Display the trigger message for the particular kind of modification
149
www.studentsfocus.com
DATABASE TRIGGERS
Triggers are similar to procedures or functions in that they are named PL/SQL blocks with
declarative, executable, and exception handling sections. A trigger is executed implicitly whenever the
triggering event happens. The act of executing a trigger is known as firing the trigger.
USE OF TRIGGERS
Maintaining complex integrity constraints not possible through declarative constraints enable at
table creation.
Auditing information in a table by recording the changes made and who made them.
Automatically signaling other programs that action needs to take place when chages are made to
a table.
RESTRICTIONS ON TRIGGERES
Like packages, triggers must be stored as stand-alone objects in the database and cannot be local to
a block or package.
TYPES OF TRIGGERS
DML Triggers
Instead of Triggers
DDL Triggers
System Triggers
Suspend Triggers
CATEGORIES
Row level trigger fires once for each row affected by the triggering statement. Row level trigger
is identified by the FOR EACH ROW clause.
Statement level trigger fires once either before or after the statement.
150
www.studentsfocus.com
TRIGGER SYNTAX
PL/SQL block
DML TRIGGERS
A DML trigger is fired on an INSERT, UPDATE, or DELETE operation on a database table. It can
be fired either before or after the statement executes, and can be fired once per affected row, or
once per statement.
The combination of these factors determines the types of the triggers. These are a total of 12
possible types (3 statements * 2 timing * 2 levels).
Ex:
Suppose we have a follwing table.
SQL> select * from student;
NO NAME MARKS
----- ---------- ------------
1 a 100
2 b 200
3 c 300
4 d 400
Also we have triggering_firing_order table with firing_order as the field.
151
www.studentsfocus.com
Ex:
CREATE OR REPLACE TRIGGER
TRIGGER1 before insert on student
BEGIN
insert into trigger_firing_order values('Before Statement Level');
END TRIGGER1;
Ex:
CREATE OR REPLACE TRIGGER
TRIGGER2 before insert on student
for each row
BEGIN
insert into trigger_firing_order values('Before Row Level');
END TRIGGER2;
Ex:
CREATE OR REPLACE TRIGGER
TRIGGER3 after insert on student
BEGIN
insert into trigger_firing_order values('After Statement Level');
END TRIGGER3;
Ex:
CREATE OR REPLACE TRIGGER
TRIGGER4 after insert on student
for each row
BEGIN
insert into trigger_firing_order values('After Row Level');
END TRIGGER4;
Output:
152
www.studentsfocus.com
SQL> select * from trigger_firing_order;
FIRING_ORDER
--------------------------------------------------
Before Statement
Level Before Row
Level After Row Level
After Statement Level SQL>
NO NAME MARKS
----- ------------ --------------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
Ex:
Suppose we have a table called marks with fields no, old_marks, new_marks.
Output:
SQL> select * from student;
NO NAME MARKS
----- ------- - ---------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
www.studentsfocus.com
SQL> select * from student;
NO NAME MARKS
----- ----------- --------------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
6 f 600
www.studentsfocus.com
REFERENCING CLAUSE
If desired, you can use the REFERENCING clause to specify a different name for :old ane
:new. This clause is found after the triggering event, before the WHEN clause.
Syntax:
REFERENCING [old as old_name] [new as new_name]
Ex:
CREATE OR REPLACE TRIGGER REFERENCE_TRIGGER
before insert or update or delete on student
WHEN CLAUSE
WHEN clause is valid for row-level triggers only. If present, the trigger body will be
executed only for those rows that meet the condition specified by the WHEN clause.
Syntax:
WHEN trigger_condition;
Where trigger_condition is a Boolean expression. It will be evaluated for each row. The :new and
:old records can be referenced inside trigger_condition as well, but like REFERENCING, the
colon is not used there. The colon is only valid in the trigger body.
Ex:
CREATE OR REPLACE TRIGGER WHEN_TRIGGER
before insert or update or delete on student
155
www.studentsfocus.com
TRIGGER PREDICATES
There are three Boolean functions that you can use to determine what the operation
is. The predicates are
INSERTING
UPDATING
DELETING
Ex:
CREATE OR REPLACE TRIGGER PREDICATE_TRIGGER
before insert or update or delete on student
BEGIN
if inserting then
insert into predicates
values('I'); elsif updating then
insert into predicates
values('U'); elsif deleting then
insert into predicates values('D');
end if;
END PREDICATE_TRIGGER;
Output:
SQL> delete student where
no=1; 1 row deleted.
www.studentsfocus.com
SQL> update student set marks = 777 where
no=7; 1 row updated.
INSTEAD-OF TRIGGERS
Instead-of triggers fire instead of a DML operation. Also, instead-of triggers can be defined only
on views. Instead-of triggers are used in two cases:
RESULT:
Thus the Implementation of Triggers and its applications to monitor the modification in database
has been verified and executed successfully.
157
www.studentsfocus.com
10.2 IMPLEMENTATION OF FUNCTIONS AND ITS APPLICATION
AIM:
To write the PL/SQL block for the implementation of functions and its application.
ALGORITHM:
STEP 4: Create the function with necessary arguments and return data types.
158
www.studentsfocus.com
STORED FUNCTION
A function is similar to procedure, except that it returns a value. The calling program should
CREATE FUNCTION
SYNTAX:
CREATE [OR REPLACE] FUNCTION name
[(parameter[,parameter, ...])]
RETURN datatype
{IS | AS}
[local declarations]
BEGIN
executable statements
RETURN value;
[EXCEPTION
exception handlers]
END [name];
Note:
OR REPLACE is used to create a function even though a function with the same name already
exists
RETURN statement in the executable part returns the value. The value must be of the same type as
User-defined PL/SQL functions can be used in SQL in the same manner as the standard functions
159
www.studentsfocus.com
Q 1: To write a PL/SQL block to implementation of factorial using function
I) PROGRAM:
SQL>create function fnfact(n
number) return number is
b number;
begin
b:=1;
for i in 1..n
loop
b:=b*i;
end loop;
return b;
end;
/
SQL>Declare
n number:=&n;
y number;
begin
dbms_output.put_line(y);
end;
/
Output:
Function created.
Enter value for n: 5
old 2: n
number:=&n; new 2:
n number:=5; 120
Q2:create a function which count total no.of employees having salary less than 6000.
160
www.studentsfocus.com
/*function body*/
Create or replace function count_emp(esal number)return number as
Cursor vin_cur as Select empno,sal from emp;
Xno emp.empno%type;
Xsal emp.sal%type;
C number;
Begin
Open vin_cur;
C:=0;
loop
fetch vin_cur into xno,xsal;
if(xsal<esal) then
c:=c+1;
end if;
exit when
vin_cur%notfound; end loop;
close vin_cur;
return c;
end;
/
Function created.
/*function specification*/
Declare
Ne number;
Xsal number;
Begin
Ne:=count_emp(xsal);
Dbms_output.put_line(xsal);
Dbma_output.put_line(‘there are ‘||ne||;employees’);
End;
/
OUTPUT
There are 8 employees.
Q2: To write a PL/SQL function to search an address from the given database
161
www.studentsfocus.com
II) PROGRAM
SQL> create table phonebook (phone_no number (6) primary
key, username varchar2(30),
doorno varchar2(10),
street varchar2(30),
place varchar2(30),
pincode char(6));
table created.
Function created.
162
www.studentsfocus.com
declare
address varchar2(100);
begin
address:=findaddress(20312);
dbms_output.put_line(address);
end;
/
OUTPUT 1:
Vijay,120/5D,bharathi street,NGO colony,629002
PL/SQL procedure successfully completed.
declare
address
varchar2(100); begin
address:=findaddress(23556);
dbms_output.put_line(address);
end;
/
OUTPUT2:
Address not found
PL/SQL procedure successfully completed.
Result:
Thus the implementation of functions and its applications has been executed successfully.
163
www.studentsfocus.com
SUPPLEMENT - A
1. What is database?
A database is a logically coherent collection of data with some inherent meaning, representing some
aspect of real world and which is designed, built and populated with data for a specific purpose.
2. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other words it is
general-purpose software that provides the users with the processes of defining, constructing and
manipulating the database for various applications.
1. Redundancy is controlled.
3. Data isolation.
4. Data integrity.
6. Security Problems.
164
www.studentsfocus.com
6. Describe the three levels of data abstraction?
1. Physical level: The lowest level of abstraction describes how data are stored.
2. Logical level: The next higher level of abstraction, describes what data are stored in database and
what relationship among those data.
3. View level: The highest level of abstraction describes only part of entire database.
1. Entity Integrity: States that "Primary key cannot have NULL value"
2. Referential Integrity: States that "Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
1. Extension: It is the number of tuples present in a table at any instance. This is time dependent.
2. Intension: It is a constant value that gives the name, structure of table and the constraints laid on it.
System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It
is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be
used in a real life environment to solve real life problems, with performance at least comparable to that of
existing system.
1. Research Storage
165
www.studentsfocus.com
10. How is the data structure of System R different from the relational
Data independence means that "the application is independent of the storage structure and access
strategy of data". In other words, The ability to modify the schema definition in one level should not affect
the schema definition in the next higher level.
1. Physical Data Independence: Modification in physical level should not affect the logical level.
2. Logical Data Independence: Modification in logical level should affect the view
A view may be thought of as a virtual table, that is, a table that does not really exist in its own right
but is instead derived from one or more underlying base table. In other words, there is no stored file that
direct represents the view instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users
from the effects of restructuring and growth in the database. Hence accounts for logical data independence.
A collection of conceptual tools for describing data, data relationships data semantics and
constraints.
166
www.studentsfocus.com
14. What is E-R model?
This data model is based on real world that consists of basic objects called entities and of
relationship
This model is based on collection of objects. An object contains values stored in instance variables
with in the object. An object also contains bodies of code that operate on the object. These bodies of code
are called methods. Objects that contain same types of values and the same methods are grouped together
into classes.
The collections of entities of a particular entity type are grouped together into an entity set.
An entity set may not have sufficient attributes to form a primary key, and its primary key
compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set.
167
www.studentsfocus.com
22. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, ..., An) is made up of the relation name R and the list of
attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set
tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn).
Relationship type defines a set of associations or a relationship set among a given set of entity types.
A data base schema is specifies by a set of definitions expressed by a special language called DDL.
This language is to specify the internal schema. This language may specify the mapping between
two schemas.
168
www.studentsfocus.com
31. What is Data Storage - Definition Language?
The storage structures and access methods used by database system are specified by a set of
definition in a special type of DDL called data storage-definition language.
This language that enable user to access or manipulate data as organised by appropriate data model.
1. Procedural DML or Low level: DML requires a user to specify what data are needed and how to
get those data.
2. Non-Procedural DML or High level: DML requires a user to specify what data are needed without
specifying how to get those data.
It translates DML statements in a query language into low-level instruction that the query evaluation
The Low level or Procedural DML can specify and retrieve each record from a set of records. This
retrieve of a record is said to be Record-at-a-time.
The High level or Non-procedural DML can specify and retrieve many records in a single DML
statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.
169
www.studentsfocus.com
38. What is Relational Algebra?
It is procedural query language. It consists of a set of operations that take one or two relations as
input and produce a new relation.
It is an applied predicate calculus specifically tailored for relational databases proposed by E.F.
Codd.
40. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus?
1. The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are
tuples of that relation. E.g. QUEL
2. The domain-oriented calculus has domain variables i.e., variables that range over the underlying
domains instead of over relation. E.g. ILL, DEDUCE.
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs)
and primary key to achieve the properties
(1).Minimizing redundancy,
A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets
of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any
two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component
of a tuple uniquely determines the value of component Y.
It guarantees that the spurious tuple generation does not occur with respect to relation schemas after
decomposition.
170
www.studentsfocus.com
44. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values.
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true
1. X is a Super-key of R.
2. A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every
FD X A, X must be a candidate key.
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R,
one of following is true.
171
www.studentsfocus.com
50. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R,
one the following is true
2.) The join dependency is implied by the set of FD, over R in which the left side is key of R.
A relation is said to be in DKNF if all constraints and dependencies that should hold on the the
constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation.
52. What are partial, alternate,, artificial, compound and natural key?
1. Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner
entity. It is sometime called as Discriminator.
2. Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
3. Artificial Key:
If no obvious key, either stand alone or compound is available, then the last resort is to simply create
a key, by assigning a unique number to each record or occurrence. Then this is known as developing an
artificial key.
4. Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining multiple
elements to create a unique identifier for the construct is known as creating a compound key.
5. Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it is
called the natural key.
172
www.studentsfocus.com
53. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
2. B-Tree indexing
5. Table indexing
54. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every relation
and index that it contains. This information is stored in a collection of relations maintained by the system
called metadata. It is also called data dictionary.
The phase that identifies an efficient execution plan for evaluating a query that has the least
estimated cost is referred to as query optimization.
Once the DBMS informs the user that a transaction has successfully completed, its effects should
persist even if the system crashes before all its changes are reflected on disk. This property is called
durability.
1. Atomicity:
Either all actions are carried out or none are. Users should not have to worry about the effect of
incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions.
173
www.studentsfocus.com
2. Aggregation:
A concept which is used to model a relationship between a collection of entities and relationships. It
is used when we need to express a relationship among relationships.
In distributed deadlock detection, the delay in propagating local information might cause the
deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called
phantom deadlocks and they lead to unnecessary aborts.
A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce
the amount of work to be done during restart in the event of subsequent crashes.
It is a database in which there are no programs or user access languages. It has no cross-file
capabilities but is user-friendly and provides user-interface management.
A query with respect to DBMS relates to user commands that are used to interact with a data base.
The query language can be classified into data definition language and data manipulation language.
174
www.studentsfocus.com
64. What do you mean by Correlated subquery?
Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query.
Depending on how the subquery is written, it can be executed once for the parent query or it can be
executed once for each row returned by the parent query. If the subquery is executed for each row of the
parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent subquery columns
in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query.
The following example demonstrates a non-correlated subquery.
Example:
65. What are the primitive operations common to all record management
66. Name the buffer in which all the commands that are typed in are stored?
'Edit' Buffer.
68. Are the resulting relations of PRODUCT and JOIN operation the
same? No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
Two important pieces of RDBMS architecture are the kernel, which is the software, and the data
dictionary, which consists of the system-level data structures used by the kernel to manage the database You
175
www.studentsfocus.com
might think of an RDBMS as an operating system (or set of subsystems), designed specifically for
controlling data access; its primary functions are storing, retrieving, and securing data.
An RDBMS maintains its own list of authorized users and their associated privileges; manages
memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules
user requests; and manages space usage within its table-space structures.
Language Processing,
Process Control,
Storage Management,
Distribution Control,
Transaction Control,
Memory Management,
Lock Management.
71. Which part of the RDBMS takes care of the data dictionary? How?
Data dictionary is a set of tables and database objects that is stored in a special area of the database
and maintained exclusively by the kernel.
The information in the data dictionary validates the existence of the objects, provides access to them,
and maps the actual physical storage location.
www.studentsfocus.com
74. Define SQL and state the differences between SQL and other conventional programming Languages.
SQL is a nonprocedural language that is designed specifically for data access operations on
normalized
relational database structures. The primary difference between SQL and other conventional programming
languages is that SQL statements specify what data operations should be performed rather than how to
perform them.
75. Name the three major set of files on disk that compose a database in Oracle.
There are three major sets of files on disk that compose a database. All the files are binary. These are
The most important of these are the database files where the actual data resides. The control files and
the redo logs support the functioning of the architecture itself. All three sets of files must be present, open,
and available to Oracle for any data on the database to be useable. Without these files, you cannot access the
database, and the database administrator might have to recover some or all of the database using a backup, if
there is one.
A database trigger is a PL/SQL block that can defined to automatically execute for insert, update,
and delete statements against a table. The trigger can e defined to execute once for the entire statement or
once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which
you can define database triggers. A database trigger can call database procedures that are also written in
PL/SQL.
77. What are stored-procedures? And what are the advantages of using them?
Stored procedures are database objects that perform a user defined operation. A stored procedure can
have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the
result to the client. Stored procedures are used to reduce network traffic.
177
www.studentsfocus.com
78. What is Storage Manager?
It is a program module that provides the interface between the low-level data stored in database,
application programs and queries submitted to the system.
It is a program module, which is responsible for fetching data from disk storage into main memory
and deciding what data to be cache in memory.
It is a program module, which ensures that database, remains in a consistent state despite system
failures and concurrent transaction execution proceeds without conflicting.
It is a program module, which manages the allocation of space on disk storage and data structure
used to represent information stored on a disk.
It is the program module, which tests for the satisfaction of integrity constraint and checks the
authority of user to access data.
Procedures that are not part of a package are known as stand-alone because they independently
defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These
types of procedures are not available for reference from other Oracle tools. Another limitation of stand-
alone procedures is that they are compiled at run time, which slows execution.
PL/SQL uses cursors for all database information accesses statements. The language supports the use
two types of cursors
1.) Implicit
2.) Explicit
178
www.studentsfocus.com
85. What is cold backup and hot backup (in case of Oracle)?
1. Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the
instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut
down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in
the event of data file loss is restoring all the files from the latest backup. All work performed on the
database since the last backup is lost.
2. Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database
while making a backup copy of the files. The cold backup is not an available option.
1. Proactive Update: The updates that are applied to database before it becomes effective in real world.
2. Retroactive Update: The updates that are applied to database after it becomes effective in real world.
3. Simulatneous Update: The updates that are applied to database at the same time when it becomes
effective in real world.
179
www.studentsfocus.com
SUPPLEMENT - B
DATABASE APPLICATION
Apart from giving you an idea about how to create tables with constraints, it also enables you to understand
how to create queries, pl/sql programs, stored procedures and functions and database triggers.
However, note, this sample collection of tables is only for learning purpose and they are hypothetical.
Required Tables
Structure of Tables
Creating Tables
Loading data into
tables Queries
Required Tables
The following are the set of tables to be created to store the required information.
Structure of Tables
The following is the structure of each of the required table.
180
www.studentsfocus.com
DEPT Table
Stores information about all the departments of the company.
Constraints
EMPLOYEE table
Contains information about all the employees of the company.
Constraints
181
www.studentsfocus.com
LEAVES Table
Contains information about the types of leaves available in the company.
NOLEAVES number(2) Number of leaves allotted to each employee for a leave type
Contraints
EMP_LEAVES Table
Contains information about the leaves taken by employees.
EMPNO number(5) Employee number of the employee who has taken leave
Contraints
182
www.studentsfocus.com
Creating Tables
The following scirpt is used to create sample tables. Click here to download the script and run
the script at SQL> promt using START command of SQL*PLUS>
183
www.studentsfocus.com
The following script inserts a few rows into sample tables. Click here to download the script to
create sample data or copy the script given below into notepad, save it with .SQL extension
and run it at SQL> using START command.
REM ****** script to insert sample data into EMPLOYEES application ******
REM ****** AUTHOR : P.SRIKANTH ******
REM ****** DATE: 23-AUG-2001 ******
REM ************************************************************************
COMMIT;
184
www.studentsfocus.com
Queries Related To Employees Management Application
NOTE:
TRUNC FUNCTION IS REQUIRED IN ORDER TO IGNORE TIME DIFFERENCE BETWEEN TWO DATES.
FROM EMPLOYEE
SELECT EMPNAME
185
www.studentsfocus.com
Q: SELECT EMPLOYEES WHERE SECOND CHARACTER IN NAME IS 'S'
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO HAVE JOINED IN THE LAST 20 DAYS
FROM EMPLOYEE;
Q: DISPLAY DETAILS OF EMPLOYEES WHO ARE DRAWING MORE THAN 10000 AND THE DESIGNATION IS CONTAINING
MORE THAN 3 LETTERS
Q: DISPLAY DETAILS OF EMPLOYEES WHOSE NAME IS CONTAINING MORE THAN ONE SPACE
Q: DISPLAY DETAILS OF LEAVES WHERE THE LEAVE STARTED IN THE PREVIOUS MONTH AND THE LEAVE IS NOT YET
COMPLETED
LAST_DAY( ADD_MONTHS(STDATE,-1)) + 1
Q: DISPLAY DETAILS OF EMPLOYEES WHERE BASIC SALARY IS MORE THAN 10000 OR DESIGNATION IS PL AND
EXPERIENCE IS MORE THAN 3 YEARS
WHERE SAL > 10000 OR DESG = 'PL' AND MONTHS_BETWEEN(SYSDATE,DJ) > 36;
186
www.studentsfocus.com
Q: DISPLAY EMPNO,NAME AND FIRST NAME OF THE EMPLOYEE AND WHEN EMPLOYEE HAS TAKEN HIS FIRST
FROM EMPLOYEE;
Q: FIND THE AVERAGE SALARY OF THE EMPLOYEE WHO JOINED IN THE CURRENT YEAR
SELECT AVG(SAL)
FROM EMPLOYEE
Q: FIND THE AVERAGE SALARY OF EACH DEPARTMENT BY TAKING EMPLOYEES WHO EARN MORE THAN 10000
FROM EMPLOYEE
GROUP BY DEPTNO;
Q: DISPLAY DETAILS OF EMPLOYEES ALONG WITH BONUS WHICH WILL BE 100% ON SALARY FOR EMPLOYEES OF
DEPARTMENT 1 AND 75% FOR OTHERS
FROM EMPLOYEE;
Q: DISPLAY DETAILS OF LEAVES TAKEN BY EMPLOYEES WHERE TYPE OF LEAVE IS 'S' AND LEAVE STARTED ON
MONDAY
FROM EMP_LEAVES
GROUP BY EMPNO;
SELECT DESG,SUM(SAL)
FROM EMPLOYEE
GROUP BY DESG;
FROM EMPLOYEE
187
www.studentsfocus.com
Q: FIND THE AVERAGE SALARY OF EACH DEPARTMENT AND SELECT ONLY THOSE EMPLOYEES HAVING SALARY
MORE THAN 10000
FROM EMPLOYEE
GROUP BY DEPTNO;
FROM EMP_LEAVES
Q: DISPLAY DEPTNO,MIN SALARY,MAX SALARY ,DIFFERENCE BETWEEN MAX AND MIN SALARY FOR THE
DEPARTMENTS
THAT HAVE MORE THAN 2 EMPLOYEES
FROM EMPLOYEE
GROUP BY DEPTNO
Q: DISPLAY LEAVETYPE AND HOW MANY TIMES EACH EMPLOYEE HAS TAKEN LEAVE
FROM EMP_LEAVES
GROUP BY LEAVETYPE,EMPNO;
Q: DISPLAY EMPNO OF THE EMPLOYEE WHO HAS TAKEN MORE THAN 2 LEAVES IN THE CURRENT MONTH
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
Q: DISPLAY DESIGNATION THAT CONTAIN EITHER MORE THAN 5 EMPLOYEES OR AVERAGE SALARY MORE THAN 12000
SELECT DESG
FROM EMPLOYEE
GROUP BY DESG
SELECT LEAVETYPE
FROM EMP_LEAVES
GROUP BY LEAVETYPE
Q: DISPLAY THE DETAILS OF LEAVES TAKEN BY EMPLOYEES WHO ARE HAVING 'DUKE' AS THE HEAD OF THE
DEPARTMENT.
SELECT EL.*
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO HAVE JOINED AFTER EMPLOYEE 'WILLY' HAS
www.studentsfocus.com
Q: SELECT THE EMPLOYEES WHO HAVE TAKEN LEAVE IN THE PRESENT MONTH
WHERE EMPNO IN
WHERE TO_CHAR(SYSDATE,'MMYYYY') =
TO_CHAR(STDATE,'MMYYYY') );
WHERE DEPTNO IN
( SELECT DEPTNO
FROM EMPLOYEE
GROUP BY DEPTNO
Q: DISLAY THE DETAILS OF EMPLOYEES WHO HAVE TAKEN MORE THAN 10 LEAVES
WHERE EMPNO IN
( SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
10 );
Q: DISPLAY THE DETAILS OF DEPARTMENTS WHICH HAVE MORE THAN 3 EMPLOYEES JOINED IN THE CURRENT YEAR
WHERE DEPTNO IN
( SELECT DEPTNO
FROM EMPLOYEE
GROUP BY DEPTNO
);
190
www.studentsfocus.com
Q: DISPLAY THE NAME OF THE EMPLOYEE DRAWING THE MAX SALARY
WHERE SAL =
( SELECT MAX(SAL)
FROM EMPLOYEE
);
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO HAS TAKEN MORE THAN 10 SICKLEAVES OR MORE THAN 15 LEAVES
WHERE EMPNO IN
( SELECT EMPNO
FROM EMP_LEAVES
WHERE LEAVETYPE='S'
GROUP BY EMPNO
OR EMPNO IN
( SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
);
Q: DISPLAY EMPNO,EMPNAME,DESIGNATION AND DEPTNAME OF EMPLOYEES WHO HAVE NOT TAKEN ANY LEAVES IN
THE CURRENT YEAR
SELECT EMPNO,EMPNAME,DESG,DEPTNAME
( SELECT EMPNO
FROM EMP_LEAVES
);
191
www.studentsfocus.com
Q: DISPLAY THE DETAILS OF HOD'S
WHERE EMPNAME IN
( SELECT HOD
FROM DEPT
);
WHERE DEPTNO IN
SELECT DEPTNO
GROUP BY DEPTNO
HAVING SUM(ENDDATE-STDATE) =
SELECT MAX(SUM(ENDDATE-STDATE))
GROUP BY DEPTNO
);
FROM EMP_LEAVES
WHERE EMPNO IN
WHERE DEPTNO IN
SELECT DEPTNO
FROM DEPT
192
www.studentsfocus.com
WHERE HOD = 'STEVE'
GROUP BY EMPNO;
FROM EMPLOYEE
Q: DISPLAY DETAILS OF DEPARTMENT IN WHICH ATLEAST ONE EMPLOYEE HAS TAKEN MORE NO. OF LEAVES THAN
AVERAGE LEAVES OF ALL THE EMPLOYEES WHO JOINED IN THE CURRENT YEAR
WHERE DEPTNO IN
( SELECT DEPTNO
FROM EMPLOYEE
WHERE EMPNO IN
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
FROM EMP_LEAVES
);
193
www.studentsfocus.com
Q: HOW MANY EMPLOYEES ARE EARNING MORE THAN THE AVERAGE SALARY OF
FROM EMPLOYEE
FROM EMPLOYEE
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO BELONG TO DEPARTMENT 1 OR 3 AND DRAW MORE THAN 5000 SALARY
Q: DISPLAY THE DETAILS OF LEAVES WHERE THE EMPNO IS IN THE RANGE 103 TO 110
Q: DISPLAY DETAILS OF DEPARTMENT WHERE HEAD OF DEPARTMENT IS 'STEVE' AND THE DEPTNAME CONTAINS 'P' AS
THE LAST CHARACTER.
FROM EMPLOYEE;
Q: DISPLAY EMPNO,LEAVETYPE,STDATE,NO OF DAYS BETWEEN SYSDATE & STDATE FOR LEAVES THAT ARE NOT
COMPLETED.
FROM EMP_LEAVES
194
www.studentsfocus.com
Q: DISPLAY EMPNO,EMPNAME,DATE ON WHICH EMPLOYEE TOOK FIRST SALARY (ASSUMING ON 1ST OF EACH MONTH
SALARY IS PAID).
FROM EMPLOYEE;
Q: DISPLAY THE DETIALS OF EMPLOYEES WHO HAVE THE PATTERN 'TE' IN NAME AND NAME HAS MORE THAN 5
LETTERS.
Q: DISPLAY THE DETAILS OF LEAVES ALONG WITH THE DATE OF COMING SATURDAY AFTER STDATE AND NO. OF DAYS
OF LEAVES FOR LEAVES THAT ARE COMPLETED.
FROM EMP_LEAVES
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO HAVE JOINED IN THE CURRENT YEAR
Q: DISPLAY THE DETAILS OF EMPLOYEES WHOSE NAME CONTAINS 'APP' IN 4TH,5TH,6TH POSITIONS.
INSTR(EMPNAME,'APP') = 4;
OR
FROM EMPLOYEE;
Q: DISPLAY THE EMPNO,LEAVETYPE,STDATE IN 'DD-MM' FORMAT AND ENDING DATE FOR ALL THE LEAVES THAT ARE
TAKEN BY EMPLOYES WITH NUMBERS IN THE RANGE 103-107 AND IN THE CURRENT YEAR.
FROM EMP_LEAVES
195
www.studentsfocus.com
Q: TRUNCATE TIME PORTION IN STARTING DATE OF THE LEAVE.
UPDATE EMP_LEAVES
FROM EMPLOYEE
GROUP BY DEPTNOL;
Q: DISPLAY THE AVERAGE SALARY OF EACH DEPT BY TAKING EMPLOYEES WHO HAVE JOINED IN THE CURRENT YEAR.
FROM EMPLOYEE
GROUP BY DEPTNO;
FROM EMP_LEAVES
GROUP BY EMPNO;
FROM EMP_LEAVES
GROUP BY LEAVETYPE;
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
FROM EMPLOYEE
GROUP BY TO_CHAR(DJ,'YYYY')
196
www.studentsfocus.com
Q: DISPLAY EMPNO FOR EMPLOYEES WHO HAVE TAKEN MORE THAN 20 LEAVES IN THE CURRENT YEAR.
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
Q: DISPLAY THE LEAVETYPE THAT HAS BEEN TAKEN FOR MORE THAN 10 TIMES
SELECT LEAVETYPE
FROM EMP_LEAVES
GROUP BY LEAVETYPE
Q: DISPLAY DEPT,DESIGNATION,YEAR & NO. OF EMPLOYEES JOINED IN THAT YEAR IN THAT DEPARTMENT AND
DESIGNATION.
FROM EMPLOYEE
Q: DISPLAY DEPT IN WHICH THE AVGERAGE SAL OF ANY SINGLE DESIGNATION IS MORE THAN 10000.
FROM EMPLOYE
FROM EMPLOYEE
GROUP BY DEPTNO;
Q: DISPLAY LEAVETYPE FOR WHICH MORE THAN 10 LEAVES ARE TAKEN IN THE CURRENT MONTH OR 20 LEAVES TAKEN
SO FAR.
SELECT LEAVETYPE
FROM EMP_LEAVES
WHERE TO_CHAR(STDATE,'MMYYYY') = TO_CHAR(SYSDATE,'MMYYYY')
GROUP BY LEAVETYPE
HAVING SUM(ENDDATE - STDATE) > 10
UNION
SELECT LEAVETYPE
FROM EMP_LEAVES
GROUP BY LEAVETYPE
HAVING SUM(ENDDATE - STDATE) > 20
197
www.studentsfocus.com
Q: DISPLAY TOTAL NO.OF LEAVES OF ALL EMPLOYES (CONSIDERING SYSDATE AS ENDING DATE IF ENDING DATE IS NOT
AVAILABLE).
FROM EMP_LEAVES;
Q: DISPLAY EMPNO,LEAVETYPE ,STDATE,NO. OF LEAVES & MAX NO. OF LEAVES FOR THAT CATEGORY.
Q: DISPLAY EMPNO,NAME,DEPTNAME,HOD FOR THE EMPLOYEES WHO HAVE NOT TAKEN ANY LEAVE SO FAR.
Q: DISPLAY EMPNO,NAME,DEPTNAME,LEAVENAME,STDATE,ENDDATE
Q: DISPLAY DETAILS OF DEPT IN WHICH AT LEAST ONE EMPLOYEE HAS JOINED IN THE CURRENT MONTH.
WHERE DEPTNO IN
Q: DISPLAY LEAVETYPE,LEAVENAME,EMPNO AND STDATE FOR ALL THE LEAVES INCLUDING LEAVETYPES THAT HAVE
NOT BEEN USED BY ANY EMPLOYEE.
www.studentsfocus.com
Q: DISPLAY THE DETAILS OF LEAVES WHERE THE NO.OF DAYS OF LEAVES IS MORE THAN THE NOOFDAYS OF
LEAVE TAKEN BY 101 IN LEAVE THAT STARTED ON 5-MARCH-00.
SELECT E1.*
WHERE DEPTNO IN
( SELECT DEPTNO
FROM EMPLOYEE
GROUP BY DEPTNO
Q: DISPLAY DETAILS OF DEPT WHERE THE DEPT HAS MORE THAN 3 EMPLOYEES DRAWING MORE THAN 5000
WHERE DEPTNO IN
( SELECT DEPTNO
FROM EMPLOYEE
GROUP BY DEPTNO
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO HAS NOT TAKEN SICK LEAVE IN CURRENT MONTH.
( SELECT EMPNO
FROM EMP_LEAVES
);
199
www.studentsfocus.com
Q: DISPLAY DETAILS OF EMPLOYEES DRAWING THE MAXSAL.
MAX(SAL)
FROM EMPLOYEE);
Q: DISPLAY DETAILS OF EMPLOYEES DRAWING MORE SALARY THAN THE AVERAGE SAL OF EMPLOYEES JOINED IN THE
CURRENT YEAR.
( SELECT AVG(SAL)
FROM EMPLOYEE
);
);
Q: DELETE DETAILS OF LEAVES TAKEN BY EMPLOYEE WHOSE EMPNO IS THE HIGHEST EMPNO
Q: DISPLAY THE DETAILS OF EMPLOYEES WHO ARE BELONGING TO PRODUCTION DEPT AND HAVE TAKEN MORE
THAN 20 LEAVES SO FAR.
SELECT E.*
AND EMPNO IN
( SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
www.studentsfocus.com
);
Q: DISPLAY DETAILS OF LEAVES WHERE THE EMPLOYEE SAL IS MORE THAN 10000 AND JOINED IN THE LAST 6 MONTHS.
WHERE EMPNO IN
( SELECT EMPNO
FROM EMPLOYEE
);
the number of employees whose salary is greater than the salary of the
current employee in main query. If that count is less than 5 that means
where 5 >
from employee
Q: UPDATE THE SALARY OF EMPLOYEE 102 WITH THE AVERAGE SALARY OF HIS DEPARTMENT.
UPDATE EMPLOYEE E SET SAL= ( SELECT AVG(SAL) FROM EMPLOYEE WHERE DEPTNO = E.DEPTNO)
Q: DISPLAY DETAILS OF DEPARTMENT IN WHICH THERE ARE HIGHEST NUMBER OF LEAVES TAKEN
201
www.studentsfocus.com
Q: RENAME COLUMN DJ TO JOINDATE OF EMPLOYEE TABLE.
1. CREATE A NEW TABLE FROM EMPLOYEE TABLE. GIVE ALIAS JOINDATE TO DJ COLUMN IN QUERY.
4. FROM EMPLOYEE;
DECLARE
SAL_103 EMPLOYEE.SAL%TYPE;
BEGIN
FROM EMPLOYEE
UPDATE EMPLOYEE
UPDATE EMPLOYEE
COMMIT;
END;
202
www.studentsfocus.com
Q: CREATE A PROCEDURE TO TAKE EMPNO AND LEAVETYPE AND INSERT A ROW INTO EMP_LEAVES TABLE WITH THE
FOLLOWING CONDITIONS.
CHECK WHETHER EMPLOYEE HAS ALREADY USED ALL LEAVES IN THAT TYPE
IS
CNT NUMBER(3);
TNL NUMBER(2);
NL NUMBER(2);
BEGIN
FROM EMPLOYEE
-- IN THAT LEAVETYPE
STATUS := 1;
FROM LEAVES
FROM EMP_LEAVES
203
www.studentsfocus.com
IF CNT <> 0 THEN -- EMPLOYEE IS ALREADY ON LEAVE
END IF;
END IF;
COMMIT;
EXCEPTION
IF STATUS = 0 THEN
END IF;
RAISE_APPLICATION_ERROR(SQLCODE,SQLERRM);
END;
204
www.studentsfocus.com
Q: CREATE A FUNCTION TO RETURN NAMES OF THE EMPLOYEES DRAWING HIGEST SALARY. IF THERE IS MORE THAN
ONE EMPLOYEE, EMPLOYEE NAMES ARE TO BE SEPARATED BY COMMA.
IS
CURSOR HSEMP_CURSOR IS
SELECT EMPNAME FROM EMPLOYEE WHERE SAL = (SELECT MAX(SAL) FROM EMPLOYEE);
ENAME VARCHAR2(20);
ALLNAMES VARCHAR2(200);
BEGIN
ALLNAMES := '';
LOOP
IF LENGTH(ALLNAMES) != 0 THEN
END IF;
END LOOP;
RETURN ALLNAMES;
END;
Q: GET THE DETAILS OF DEPT. WHICH IS HEADED BY PERSON WITH THE NAME THAT CONTAINS LETTER 'C' AND 'A'.
Q: DISPLAY THE DETAILS OF DEPT'S WHERE THE DEPTNO IS >10 AND DEPTNAME ENDS WITH 'A'.
205
www.studentsfocus.com
Q: DISPLAY DETAILS OF EMPLOYEES WHO HAVE MORE THAN 10000 SALARY OR DESG. 'SA'.
Q: DISPLAY EMPNO,EMPNAME,SALARY ROUNDED TO 100'S.DOJ AND NO.OF MONTHS BETWEEN TODAY AND DATE OF
JOINING.
FROM EMPLOYEE;
Q: DISPLAY DETAILS OF LEAVES IN WHICH THE NO.OF DAYS OF LEAVES IS MORE THAN 5.
FROM EMP_LEAVES
Q: DISPLAY EMPLOYEE WHERE EMPNAME CONTAINS LETTERS 'M' AND 'J' IN ANY ORDER.
Q: DISPLAY THE ROWS OF EMPLOYEE TABLE WHERE EMPLOYEE JOINED IN THE LAST 6 MONTHS AND SAL>5000 AND
DESG. IS NOT PROGRAMMER.
WHERE SAL > 5000 AND MONTHS_BETWEEN(SYSDATE,DJ) <= 6 AND DESG <> 'PRO';
FROM EMPLOYEE;
206
www.studentsfocus.com
Q: DISPLAY THE DETAILS OF EMPLOYEE WHO JOINED IN THE MONTHS OF JULY IRRESPECTIVE OF THE YEAR.
WHERE TO_CHAR(DJ,'MM') = 7;
Q: DISPLAY DETAILS OF EMPLOYEE WHO HAVE MORE THAN 10 CHARS IN THE NAME OR HAVING LETTER 'G' AND 'C' IN
THE NAME.
Q: CHANGE THE NAME OF EMPLOYEE 105 TO UPPERCASE AND REMOVE ALL LEADING AND TRAILING SPACES.
Q: DISPLAY EMPNO,LEAVETYPE,THE MONTH IN WHICH LEAVE STARTED AND THE MONTH IN WHICH LEAVE ENDED FOR
LEAVES WHERE THESE TWO MONTHS ARE NOT SAME.
FROM EMP_LEAVES
Q: DELETE DETAILS OF LEAVES WHERE THE LEAVE STARTED IN THE FIRST WEEK OF THE PREVIOUS MONTH.
LAST_DAY(ADD_MONTHS(SYSDATE,-2)) + 7;
Q: DISPLAY EMPNAME IN UPPERCASE,DAY OF JOINING AND DATE OF FIRST SALARY AND WEEK DAY OF FIRST
FROM EMPLOYEE;
FROM EMPLOYEE
SELECT AVG(SAL)
FROM EMPLOYEE;
207
www.studentsfocus.com
Q: DISPLAY LEAVETYPE,NO.OF TIMES EMPLOYEES HAVE TAKEN THAT LEAVE.
FROM EMP_LEAVES
GROUP BY LEAVETYPE;
FROM EMPLOYEE
GROUP BY DEPTNO;
FROM EMP_LEAVES
GROUP BY TO_CHAR(STDATE,'MONTH');
Q: DISPLAY THE EMPLOYEE WHO HAVE TAKEN MORE THAN 10 LEAVES SO FAR.
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
Q: DISPLAY THE EMPLOYEE WHO HAS TAKEN MORE THAN 5 SICK LEAVES IN THE CURRENT YEAR.
SELECT EMPNO
FROM EMP_LEAVES
GROUP BY EMPNO
FROM EMPLOYEE
208
www.studentsfocus.com
Q: DISPLAY YEAR,NO.OF EMPLOYEES JOINED WITH DESG
FROM EMPLOYEE
GROUP BY TO_CHAR(DJ,'YYYY');
Q: DISPLAY EMPNO,EMPNAME,DEPTNAME FOR EMPLOYEES WHO HAVE JOINED IN THE CURRENT MONTH.
GROUP BY EMPNAME;
Q: DISPLAY EMPNO,EMPNAME,LEAVETYPE,STDATE.INCLUDE EMPLOYEES WHO HAVE NOT TAKEN ANY LEAVE AND
DISPLAY THE DATE IN THE ASCENDING ORDER OF EMPNO.
Q: DISPLAY THE LEAVES THAT WERE TAKEN AFTER EMPNO 106 TOOK SICK LEAVE(ASSUMMING 106 HAS TAKEN
Q: DISPLAY DETAILS OF DEPT. IN WHICH WE HAVE AN EMPLOYEE WITH THE NAME CONTAINING 'KEVIN'.
209
www.studentsfocus.com
FROM EMPLOYEE WHERE EMPNAME LIKE '%KEVIN%');
SELECT MAX(SUM(ENDDATE-STDATE))
FROM EMP_LEAVES
GROUP BY EMPNO;
SELECT MAX(ENDDATE-STDATE)
FROM EMP_LEAVES;
FROM EMPLOYEE
Q: DISPLAY DEPTNO AND NO.OF EMPLOYEE WHO HAVE TAKEN LEAVE IN THE CURRENT
FROM EMPLOYEE
GROUP BY DEPTNO;
Q: DISPALY DETAILS OF EMPLOYEES WHO HAVE NOT TAKEN ANY LEAVE SO FAR.
210
www.studentsfocus.com
Q: DISPLAY DETAILS OF EMPLOYEES WHO HAVE TAKEN A LEAVE IN THE PREVIOUS MONTH AND HAS
FROM EMP_LEAVES
( SELECT EMPNO
FROM EMP_LEAVES
WHERE TO_CHAR(STDATE,'MMYY') =
TO_CHAR(SYSDATE,'MMYY') );
Q: DISPLAY DETAILS OF DEPT. IN WHICH ATLEAST 2 EMPLOYEE HAVE TAKEN MORE THAN 5 SICK LEAVES.
FROM EMPLOYEE
);
WHERE DEPTNO IN
WHERE EMPNO IN
( SELECT EMPNO
FROM EMP_LEAVES
211
www.studentsfocus.com
Q: DISPLAY DETAILS OF EMPLOYEES WHO ARE HEADED BY BILL OR WHO HAVE TAKEN A LEAVE ON
PREVIOUS 'THURSDAY'
FROM EMP_LEAVES
Q: DISPLAY THE DETAILS OF LEAVETYPES WHERE THE LEAVE HAS BEEN TAKEN FOR MORE THAN 50 TIMES.
FROM EMP_LEAVES
GROUP BY LEAVETYPE
UPDATE EMPLOYEE SET DEPTNO = ( SELECT DEPTNO FROM DEPT WHERE DEPTNAME ='INTERNET')
212
www.studentsfocus.com
OTHER IMPORTANT QUERIES
SQL> Select *from emp where rowid = (select max(rowid) from emp where rownum <= 4);
Or
SQL> Select *from emp where rownum <= 4 minus select *from emp where rownum <= 3;
SQL> Select *from emp where rowid in (select max(rowid) from emp group by empno,ename, mgr, job, hiredate,
comm, deptno, sal);
Or
SQL> Delete emp where rowid in (select max(rowid) from emp group by empno,ename,mgr,job, hiredate, sal,
comm, deptno);
SQL> Select ename, count(*) from emp group by ename having count(*) >= 1;
SQL> select *from emp where (rowid,0) in (select rowid,mod(rownum,2) from emp);
SQL> select *from emp where (deptno,sal) in ( select deptno,max(sal) from emp group by deptno);
7) How to get number of employees in each department , in which department is having more than
2500 employees?
SQL> Select deptno,count(*) from emp group by deptno having count(*) >2500;
SQL> Select *from emp where sal in (select max(sal) from (select *from emp order by sal) where rownum <= 5);
213
www.studentsfocus.com
FUNCTIONS
Functions can be categorized as follows.
Single row functions
Group functions
SINGLE ROW FUNCTIONS
Single row functions can be categorized into five. These will be applied for each row
and produces individual output for each row.
Numeric functions
String functions
Date functions
Miscellaneous functions
Conversion functions
NUMERIC FUNCTIONS
Abs Ceil
Sign Floor
Sqrt Round
Mod Trunk
Nvl Bitand
Power Greatest
Exp Least
Ln Coalesce
Log
a) ABS
Absolute value is the measure of the magnitude of
value. Absolute value is always a positive number.
Syntax: abs (value)
Ex:
SQL> select abs(5), abs(-5), abs(0), abs(null) from dual;
ABS(5) ABS(-5) ABS(0) ABS(NULL)
---------- ---------- ---------- -------------
5 -5 0
b) SIGN
c) SQRT
This will give the square root of the given value.
Syntax: sqrt (value) -- here value must be positive.
214
www.studentsfocus.com
Ex:
SQL> select sqrt(4), sqrt(0), sqrt(null), sqrt(1) from dual;
SQRT(4) SQRT(0) SQRT(NULL) SQRT(1)
---------- ------------- ----------------- ---------------
2 0 1
d) MOD
This will give the remainder.
Syntax: mod (value, divisor)
Ex:
SQL> select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4) from dual;
MOD(7,4) MOD(1,5) MOD(NULL,NULL) MOD(0,0) MOD(-7,4)
------------ ---------- --------------------- ----------- -- -----------
3 1 0 -3
e) NVL
This will substitutes the specified value in the place of null values.
Syntax: nvl (null_col, replacement_value)
Ex:
SQL> select * from student; -- here for 3rd row marks value is null
NO NAME MARKS
--- ------- ---------
1 a 100
2 b 200
3 c
0 1 4
215
www.studentsfocus.com
f) POWER
Power is the ability to raise a value to a given exponent.
Syntax: power (value, exponent)
Ex:
SQL> select power(2,5), power(0,0), power(1,1), power(null,null), power(2,-5) from dual;
POWER(2,5)POWER(0,0) POWER(1,1) POWER(NULL,NULL) POWER(2,-5)
---------------------------- ----- --------- --------------- -------- ---------------
32 11 .03125
g) EXP
This will raise e value to the give power.
Syntax: exp (value)
Ex:
SQL> select exp(1), exp(2), exp(0), exp(null), exp(-2) from dual;
EXP(1) EXP(2) EXP(0) EXP(NULL) EXP(-2)
-------- --------- - ------- ------------- - ---------
2.71828183 7.3890561 1 .135335283
h) LN
This is based on natural or base e logarithm.
Syntax: ln (value) -- here value must be greater than zero which is positive only.
Ex:
SQL> select ln(1), ln(2), ln(null) from dual;
LN(1) LN(2) LN(NULL)
------- ------- ------------
0 .693147181
Ln and Exp are reciprocal to each other.
EXP (3) = 20.0855369
LN (20.0855369) = 3
i) LOG
This is based on 10 based logarithm.
Syntax: log (10, value)-- here value must be greater than zero which is positive only.
Ex:
SQL> select log(10,100), log(10,2), log(10,1), log(10,null) from dual;
LOG(10,100) LOG(10,2) LOG(10,1) LOG(10,NULL)
--------------- ----------- ------------ -----------------
2 .301029996 0
LN (value) = LOG (EXP(1), value)
216
www.studentsfocus.com
SQL> select ln(3), log(exp(1),3) from dual;
LN(3) LOG(EXP(1),3)
------- -----------------
1.09861229 1.09861229
j) CEIL
This will produce a whole number that is greater than or equal to the specified value.
k) FLOOR
This will produce a whole number that is less than or equal to the specified value.
Syntax: floor (value)
Ex:
SQL> select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual;
FLOOR(5) FLOOR(5.1) FLOOR(-5) FLOOR(-5.1) FLOOR(0) FLOOR(NULL)
----------- ------------- ------------ -------------- ----------- ----------------
5 5 -5 -6 0
l) ROUND
This will rounds numbers to a given number of digits of precision.
Syntax: round (value, precision)
Ex:
SQL> select round(123.2345), round(123.2345,2), round(123.2354,2) from dual;
ROUND(123.2345) ROUND(123.2345,0) ROUND(123.2345,2) ROUND(123.2354,2)
--------------------- ------------------------ ----------------------- -----------------------
123 123 123.23 123.24
www.studentsfocus.com
SQL> select round(-123,0), round(-123,1), round(-123,2) from
dual; ROUND(-123,0) ROUND(-123,1) ROUND(-123,2)
------------------ ----------------- -------------------
-123 -123 -123
m) TRUNC
www.studentsfocus.com
SQL> select trunc(123,-1), trunc(123,-2), trunc(123,-3), trunc(-123,-1), trunc(-
123,2), trunc(-123,-3) from dual;
TRUNC(123,-1) TRUNC(123,-2) TRUNC(123,-3) TRUNC(-123,-1) TRUNC(-123,2)
TRUNC(-123,-3)
n) BITAND
Ex:
SQL> select bitand(2,3), bitand(0,0), bitand(1,1), bitand(null,null), bitand(-2,-3) from
dual;
2 0 1 -4
o) GREATEST
Ex:
GREATEST(1,2,3) GREATEST(-1,-2,-3)
-------------------- -----------------------
3 -1
www.studentsfocus.com
p) LEAST
Ex:
LEAST(1,2,3) LEAST(-1,-2,-3)
-------------------- -----------------------
1 -3
220
www.studentsfocus.com
STRING FUNCTIONS
Initcap Soundex
Upper Concat ( ‘ || ‘ Concatenation operator)
Lower Ascii
Length Chr
Rpad Substr
Lpad Instr
Ltrim Decode
Rtrim Greatest
Trim Least
Translate Coalesce
Replace
a) INITCAP
This will capitalize the initial letter of the
string. Syntax: initcap (string)
Ex:
SQL> select initcap('computer') from dual;
INITCAP
-----------
Computer
b) UPPER
This will convert the string into uppercase.
Ex:
SQL> select upper('computer') from dual;
UPPER
-----------
COMPUTER
c) LOWER
This will convert the string into lowercase.
Syntax: lower (string)
Ex:
SQL> select lower('COMPUTER') from dual;
LOWER
-----------
computer
221
www.studentsfocus.com
d) LENGTH
This will give length of the string.
Syntax: length (string)
Ex:
SQL> select length('computer') from dual;
LENGTH
-----------
8
e) RPAD
This will allows you to pad the right side of a column with any set of characters.
Syntax: rpad (string, length [, padding_char])
Ex:
SQL> select rpad('computer',15,'*'), rpad('computer',15,'*#') from dual;
RPAD('COMPUTER' RPAD('COMPUTER'
---------------------- ----------------------
computer******* computer*#*#*#*
-- Default padding character was blank space.
f) LPAD
This will allows you to pad the left side of a column with any set of characters.
Syntax: lpad (string, length [, padding_char])
Ex:
SQL> select lpad('computer',15,'*'), lpad('computer',15,'*#') from dual;
LPAD('COMPUTER' LPAD('COMPUTER'
--------------------- ---------------------
*******computer *#*#*#*computer
Default padding character was blank space.
g) LTRIM
This will trim off unwanted characters from the left end of string.
Syntax: ltrim (string [,unwanted_chars])
Ex:
SQL> select ltrim('computer','co'), ltrim('computer','com') from dual;
LTRIM( LTRIM
-------- ---------
mputer puter
222
www.studentsfocus.com
SQL> select ltrim('computer','puter'), ltrim('computer','omputer') from dual;
LTRIM('C LTRIM('C
---------- ----------
computer computer
If you haven’t specify any unwanted characters it will display entire string.
h) RTRIM
This will trim off unwanted characters from the right end of string.
Syntax: rtrim (string [, unwanted_chars])
Ex:
SQL> select rtrim('computer','er'), rtrim('computer','ter') from dual;
RTRIM( RTRIM
-------- ---------
comput compu
SQL> select trim( trailing'i' from 'indiani') from dual; -- this will work as RTRIM
TRIM(T
------
Indian
223
www.studentsfocus.com
j) TRANSLATE
This will replace the set of characters, character by character.
Syntax: translate (string, old_chars, new_chars)
Ex:
SQL> select translate('india','in','xy') from dual;
TRANS
--------
xydxa
k) REPLACE
This will replace the set of characters, string by string.
Syntax: replace (string, old_chars [, new_chars])
Ex:
SQL> select replace('india','in','xy'), replace(‘india’,’in’) from dual;
REPLACE REPLACE
----------- -----------
Xydia dia
l) SOUNDEX
This will be used to find words that sound like other words, exclusively used in where clause.
Syntax: soundex (string)
Ex:
SQL> select * from emp where soundex(ename) = soundex('SMIT');
EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO
-------- -------- ----- ----- ------------ --------- ----------
7369 SMITH CLERK 7902 17-DEC-80 500
20 m) CONCAT
This will be used to combine two strings only.
Syntax: concat (string1, string2)
Ex:
224
www.studentsfocus.com
n) ASCII
This will return the decimal representation in the database character set of the first character of the string.
Syntax: ascii (string)
Ex:
SQL> select ascii('a'), ascii('apple') from dual;
ASCII('A') ASCII('APPLE')
------------ ------------------
97 97
o) CHR
This will return the character having the binary equivalent to the string in either the database character set
or the national character set.
Syntax: chr (number)
Ex:
SQL> select chr(97) from dual;
CHR
-----
a
p) SUBSTR
This will be used to extract substrings.
Syntax: substr (string, start_chr_count [, no_of_chars])
Ex:
SQL> select substr('computer',2), substr('computer',2,5), substr('computer',3,7)
from dual;
SUBSTR( SUBST SUBSTR
---------- ------- --------
omputer omput mputer
If no_of_chars parameter is negative then it will display nothing.
If both parameters except string are null or zeros then it will display nothing.
If no_of_chars parameter is greater than the length of the string then it ignores and calculates based on
the orginal string length.
If start_chr_count is negative then it will extract the substring from right end.
12345678
C O M P U T E R -8
-7 -6 -5 -4 -3 -2 -1
225
www.studentsfocus.com
q) INSTR
This will allows you for searching through a string for set of characters.
Syntax: instr (string, search_str [, start_chr_count [, occurrence] ])
Ex:
SQL> select instr('information','o',4,1), instr('information','o',4,2) from dual;
INSTR('INFORMATION','O',4,1) INSTR('INFORMATION','O',4,2)
------------------------------------ -------------------------------------
4 10
If you are not specifying start_chr_count and occurrence then it will start search from the beginning and
finds first occurrence only.
If both parameters start_chr_count and occurrence are null, it will display nothing.
r) DECODE
Decode will act as value by value substitution.
For every value of field, it will checks for a match in a series of if/then tests.
Syntax: decode (value, if1, then1, if2, then2, ……. else);
Ex:
SQL> select sal, decode(sal,500,'Low',5000,'High','Medium') from emp;
SAL DECODE
----- ---------
500 Low
2500 Medium
2000 Medium
3500 Medium
3000 Medium
5000 High
4000 Medium
5000 High
1800 Medium
1200 Medium
2000 Medium
2700 Medium
2200 Medium
3200 Medium
www.studentsfocus.com
If the number of parameters are even and different then decode will display last
value. If all the parameters are null then decode will display nothing.
If all the parameters are zeros then decode will display zero.
s) GREATEST
This will give the greatest string.
Syntax: greatest (strng1, string2, string3 … stringn)
Ex:
SQL> select greatest('a', 'b', 'c'), greatest('satish','srinu','saketh') from dual;
GREAT GREAT
------- -------
c srinu
If all the parameters are nulls then it will display nothing. If
any of the parameters is null it will display nothing.
t) LEAST
This will give the least string.
Syntax: greatest (strng1, string2, string3 … stringn)
Ex:
SQL> select least('a', 'b', 'c'), least('satish','srinu','saketh') from dual;
LEAST LEAST
------- -------
a saketh
If all the parameters are nulls then it will display nothing. If
any of the parameters is null it will display nothing.
u) COALESCE
This will gives the first non-null string.
Syntax: coalesce (strng1, string2, string3 … stringn)
Ex:
SQL> select coalesce('a','b','c'), coalesce(null,'a',null,'b') from dual;
COALESCE COALESCE
----------- -----------
aa
227
www.studentsfocus.com
DATE FUNCTIONS
a) SYSDATE
This will give the current date and time.
Ex:
SQL> select sysdate from dual;
SYSDATE
-----------
24-DEC-06
b) CURRENT_DATE
This will returns the current date in the session’s timezone.
Ex:
SQL> select current_date from dual;
CURRENT_DATE
------------------
24-DEC-06
c) CURRENT_TIMESTAMP
This will returns the current timestamp with the active time zone information.
Ex:
www.studentsfocus.com
d) SYSTIMESTAMP
This will returns the system date, including fractional seconds and time zone of the database.
Ex:
e) LOCALTIMESTAMP
This will returns local timestamp in the active time zone information, with no time zone information shown.
Ex:
f) DBTIMEZONE
This will returns the current database time zone in UTC format. (Coordinated Universal Time)
Ex:
g) SESSIONTIMEZONE
This will returns the value of the current session’s time zone.
Ex:
SQL> select sessiontimezone from dual;
SESSIONTIMEZONE
---------------------------------------------------------------------------
+05:30
h) TO_CHAR
This will be used to extract various date formats.
The available date formats as follows.
Syntax: to_char (date, format)
229
www.studentsfocus.com
DATE FORMATS
D -- No of days in week
DD -- No of days in month
DDD -- No of days in year
MM -- No of month
MON -- Three letter abbreviation of month
MONTH -- Fully spelled out month
RM -- Roman numeral month
DY -- Three letter abbreviated day
DAY -- Fully spelled out day
Y -- Last one digit of the year
YY -- Last two digits of the year
YYY -- Last three digits of the year
YYYY -- Full four digit year
SYYYY -- Signed year
I -- One digit year from ISO standard
IY -- Two digit year from ISO standard
IYY -- Three digit year from ISO standard
IYYY -- Four digit year from ISO standard
Y, YYY -- Year with comma
YEAR -- Fully spelled out year
CC -- Century
Q -- No of quarters
W -- No of weeks in month
WW -- No of weeks in year
IW -- No of weeks in year from ISO standard
HH -- Hours
MI -- Minutes
SS -- Seconds
FF -- Fractional seconds
AM or PM -- Displays AM or PM depending upon time of day
A.M or P.M -- Displays A.M or P.M depending upon time of day
AD or BC -- Displays AD or BC depending upon the date
A.D or B.C -- Displays AD or BC depending upon the date
FM -- Prefix to month or day, suppresses padding of month or day
TH -- Suffix to a number
SP -- suffix to a number to be spelled out
SPTH -- Suffix combination of TH and SP to be both spelled out
THSP -- same as SPTH
Ex:
SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual;
TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI
----------------------------------------------------
24 december 2006 02:03:23 pm sun
230
www.studentsfocus.com
SQL> select to_char(sysdate,'dd month year') from dual;
TO_CHAR(SYSDATE,'DDMONTHYEAR')
-------------------------------------------------------
24 december two thousand six
i) TO_DATE
This will be used to convert the string into data format.
Syntax: to_date (date)
Ex:
SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day') from
dual; TO_CHAR(TO_DATE('24/DEC/20
--------------------------
24 * december * Sunday
-- If you are not using to_char oracle will display output in default date format.
231
www.studentsfocus.com
j) ADD_MONTHS
This will add the specified months to the given date.
Syntax: add_months (date, no_of_months)
Ex:
SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from dual;
ADD_MONTHS
----------------
11-JUN-90
SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5) from dual;
ADD_MONTH
---------------
11-AUG-89
If no_of_months is zero then it will display the same date.
k) MONTHS_BETWEEN
This will give difference of months between two dates.
Syntax: months_between (date1, date2)
Ex:
SQL> select months_between(to_date('11-aug-1990','dd-mon-yyyy'), to_date('11-jan-
1990','dd-mon-yyyy')) from dual; MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-
MON-YYYY'),TO_DATE('11-JAN-1990','DD-MON-YYYY'))
-----------------------------------------------------------------------------------------------
7
-------------------------------------------------------------------------------------------------
-7
232
www.studentsfocus.com
l) NEXT_DAY
This will produce next day of the given day from the specified
date. Syntax: next_day (date, day)
Ex:
SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;
NEXT_DAY(
-------------
31-DEC-06
-- If the day parameter is null then it will display nothing.
m) LAST_DAY
This will produce last day of the given
date. Syntax: last_day (date)
Ex:
SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;
LAST_DAY(
-------------
31-DEC-06
n) EXTRACT
This is used to extract a portion of the date value.
Syntax: extract ((year | month | day | hour | minute | second), date)
Ex:
SQL> select extract(year from sysdate) from dual;
EXTRACT(YEARFROMSYSDATE)
------------------------------------
2006
time. o) GREATEST
233
www.studentsfocus.com
p) LEAST
This will give the least date.
Syntax: least (date1, date2, date3 … daten)
Ex:
SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-monyy'), to_date('11-apr-
90','dd-mon-yy')) from dual;
LEAST(
-------------
11-JAN-90
q) ROUND
Round will rounds the date to which it was equal to or greater than the given date.
Syntax: round (date, (day | month | year))
If the second parameter was year then round will checks the month of the given date in the following
ranges. JAN -- JUN
JUL -- DEC
If the month falls between JAN and JUN then it returns the first day of the current year. If
the month falls between JUL and DEC then it returns the first day of the next year.
If the second parameter was month then round will checks the day of the given date in the following
ranges. 1 -- 15 16 -- 31
If the day falls between 1 and 15 then it returns the first day of the current month. If
the day falls between 16 and 31 then it returns the first day of the next month.
If the second parameter was day then round will checks the week day of the given date in the
following ranges.
SUN -- WED
THU -- SUN
If the week day falls between SUN and WED then it returns the previous sunday. If
the weekday falls between THU and SUN then it returns the next sunday.
If the second parameter was null then it returns nothing.
If the you are not specifying the second parameter then round will resets the time to the begining
of the current day in case of user specified date.
If the you are not specifying the second parameter then round will resets the time to the begining
of the next day in case of sysdate.
234
www.studentsfocus.com
Ex:
SQL> select round(to_date('24-dec-04','dd-mon-yy'),'year'), round(to_date('11-mar- 06','dd-mon-
yy'),'year') from dual;
ROUND(TO_ ROUND(TO_
------------ ---------------
01-JAN-05 01-JAN-06
r) TRUNC
Trunc will chops off the date to which it was equal to or less than the given date.
Syntax: trunc (date, (day | month | year))
If the second parameter was year then it always returns the first day of the current year.
If the second parameter was month then it always returns the first day of the current
month. If the second parameter was day then it always returns the previous sunday.
If the second parameter was null then it returns nothing.
If the you are not specifying the second parameter then trunk will resets the time to the begining
of the current day.
235
www.studentsfocus.com
Ex:
s) NEW_TIME
This will give the desired timezone’s date and time.
Syntax: new_time (date, current_timezone, desired_timezone)
Available timezones are as follows.
236
www.studentsfocus.com
TIMEZONES
AST/ADT -- Atlantic standard/day light time
BST/BDT -- Bering standard/day light time
CST/CDT -- Central standard/day light time
EST/EDT -- Eastern standard/day light time
GMT -- Greenwich mean time
HST/HDT -- Alaska-Hawaii standard/day light time
MST/MDT -- Mountain standard/day light time
NST -- Newfoundland standard time
PST/PDT -- Pacific standard/day light time
YST/YDT -- Yukon standard/day light time
Ex:
SQL> select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss am') from dual;
TO_CHAR(NEW_TIME(SYSDAT
-----------------------------------
24 dec 2006 02:51:20 pm
t) COALESCE
This will give the first non-null date.
Syntax: coalesce (date1, date2, date3 … daten)
Ex:
SQL> select coalesce('12-jan-90','13-jan-99'), coalesce(null,'12-jan-90','23-mar-98',null)
from dual;
COALESCE( COALESCE(
------------- ------------
12-jan-90 12-jan-90
237
www.studentsfocus.com
MISCELLANEOUS FUNCTIONS
Uid
User
Vsize
Rank
Dense_rank
a) UID
This will returns the integer value corresponding to the user currently logged in.
Ex:
SQL> select uid from dual;
UID
----------
319
b) USER
This will returns the login’s user name.
Ex:
SQL> select user from dual;
USER
----------------
SAKETH
c) VSIZE
This will returns the number of bytes in the expression.
Ex:
SQL> select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;
238
www.studentsfocus.com
d) RANK
This will give the non-sequential ranking.
Ex:
SQL> select rownum,sal from (select sal from emp order by sal desc);
ROWNUM SAL
---------- ----------
1 5000
2 3000
3 3000
4 2975
5 2850
6 2450
7 1600
8 1500
9 1300
10 1250
11 1250
12 1100
13 1000
14 950
15 800
RANK(2975)WITHINGROUP(ORDERBYSALDESC)
---------------------------------------------------------
4
d) DENSE_RANK
This will give the sequential ranking.
Ex:
SQL> select dense_rank(2975) within group(order by sal desc) from emp;
DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
-----------------------------------------------------------------
3
239
www.studentsfocus.com
CONVERSION FUNCTIONS
Bin_to_num
Chartorowid
Rowidtochar
To_number
To_char
To_date
a) BIN_TO_NUM
This will convert the binary value to its numerical equivalent.
Syntax: bin_to_num( binary_bits)
Ex:
SQL> select bin_to_num(1,1,0) from dual;
BIN_TO_NUM(1,1,0)
------------------------
6
If all the bits are zero then it produces zero.
If all the bits are null then it produces an error.
b) CHARTOROWID
This will convert a character string to act like an internal oracle row identifier or rowid.
c) ROWIDTOCHAR
This will convert an internal oracle row identifier or rowid to character string.
d) TO_NUMBER
This will convert a char or varchar to number.
e) TO_CHAR
This will convert a number or date to character string.
f) TO_DATE
This will convert a number, char or varchar to a date.
240
www.studentsfocus.com
GROUP FUNCTIONS
Sum
Avg
Max
Min
Count
Group functions will be applied on all the rows but produces single output.
a) SUM
This will give the sum of the values of the specified column.
b) AVG
This will give the average of the values of the specified column.
Syntax: avg (column)
Ex:
SQL> select avg(sal) from emp;
AVG(SAL)
---------------
2757.14286
c) MAX
This will give the maximum of the values of the specified column.
Syntax: max (column)
Ex:
SQL> select max(sal) from emp;
MAX(SAL)
----------
5000
241
www.studentsfocus.com
d) MIN
This will give the minimum of the values of the specified column.
Syntax: min (column)
Ex:
SQL> select min(sal) from emp;
MIN(SAL)
----------
500
e) COUNT
This will give the count of the values of the specified column.
Syntax: count (column)
Ex:
SQL> select count(sal),count(*) from emp;
COUNT(SAL) COUNT(*)
-------------- ------------
14 14
242
www.studentsfocus.com