0% found this document useful (0 votes)
22 views33 pages

DBMS Lab manual - Practical

The document is a laboratory manual for Database Management Systems, detailing various experiments related to SQL and Oracle concepts. It includes objectives, theoretical explanations, and exercises for creating, inserting, updating, and deleting records in tables, as well as modifying table structures. Each experiment is structured with specific tasks to enhance students' understanding of database operations and SQL commands.

Uploaded by

Abubakar Siddiq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views33 pages

DBMS Lab manual - Practical

The document is a laboratory manual for Database Management Systems, detailing various experiments related to SQL and Oracle concepts. It includes objectives, theoretical explanations, and exercises for creating, inserting, updating, and deleting records in tables, as well as modifying table structures. Each experiment is structured with specific tasks to enhance students' understanding of database operations and SQL commands.

Uploaded by

Abubakar Siddiq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Database Management Systems

Laboratory Manual
INDEX

Page No.
Sr.No. Experiment Date Marks Signature
From To
Introduction of Database
1. management systems, Oracle 3 5
concepts and Create a table.
How to insert data in a table using
2. insert and display the records in a 6 9
table.
Update or Delete records of a table
3. and modifying structure of a table 10 12
using Alter and Drop command.
Study of character functions for
4. 13 15
manipulation of data items.
Study of number and date functions
5. 16 18
for manipulation of data items.
To perform join operation between
6. 19 20
various tables.
Applying constraint using two
7. 21 24
tables.
How to retrieve data from different
8. tables using sub queries and 25 26
correlated queries.
Understanding of Database Objects:
9. 27 30
synonym, sequence, index and view.
To study the concepts of
10. 31 32
Normalization.
EXPERIMENT NO: 1 DATE: / /
TITLE: Introduction of Database Management Systems, SQL Concepts, Oracle
Concepts and Create a table.

OBJECTIVES: On completion of this experiment student will able to…


 Know the concept of database management system.
 Know the concept of Oracle.
 Create a table in database.

THEORY:

 Introduction of Database Management Systems:


 DBMS is a collection of interrelated data and a set of programs to access those
data.
 Primary goal of DBMS is to provide a way to store and retrieve database
information that is both convenient and efficient.
 Examples of DBMS are Banking System, Universities, Airlines, etc.

 Introduction of Oracle:
 The relational model, sponsored by IBM (in June 1970), then came too accepted as
the definitive model for RDBMS. The language developed by IBM to manipulate
the data stored within model (Dr. E.F.Codd model) was originally called
Structured English Query Language (SEQUEL) with the word English later
dropped in favor Structured Query Language (SQL).
 In 1979 a company called Relational Software, Inc. released the first commercially
available implementation of SQL. Relational Software later come to be known as
Oracle Corporation. Oracle Corporation is a company that produces the most
widely used, Server based, Multi user RDBMS named Oracle.

 Oracle Tools:
 The Oracle product is primarily divided into
 Oracle Server tools: Oracle Server Product is either called Oracle Workgroup
Server or Oracle Enterprise Server. Oracle Workgroup Server or Oracle
Enterprise Server is used for data storage.
 Oracle Client tools: The client roll most commonly used for Commercial
Application Development is called Oracle Developer 2000. Oracle Developer
2000, Oracle’s tool box which consists of Oracle Forms, Oracle Reports and
Oracle Graphics. This suite of tools is used to capture, validate and display
data according to user and system needs.
 SQL*Plus is a separate Oracle client-side tool. Oracle Workgroup or
Enterprise Server is bundled with this SQL*Plus. It is a product that works on
Microsoft Windows 95 and Windows NT both of which are standard Client
based GUI operating systems.
 Oracle Workgroup Server and Oracle Developer 2000 are separate products
and they must be purchased separately.

 SQL (Structured Query Language):


 SQL (Structured Query Language) is a database sublanguage for querying and
modifying relational databases. It was developed by IBM Research in the mid-
1970 and standardized by ANSI in 1986.

 Components of SQL:
1) DDL (Data Definition Language):
Is a language, which includes the commands, which are used dynamically to set
up, change and remove any data structure e.g. tables, views and indexes. The
examples are CREATE, ALTER & DROP.
2) DML (Data Manipulation Language):
Is a language, which includes the commands, which are used to enter new rows,
change existing rows and remove unwanted rows from the tables in database.
The examples are INSERT, UPDATE & DELETE.
3) DCL (Data Control Language):
Is a language, which includes the commands, which are used to give or remove
access rights to both the Oracle database and the structures within it. The
examples are GRANT & REVOKE.
4) DQL (Data Query Language):
It is the component of SQL statement that allows getting data from the database
and imposing ordering upon it. In includes the SELECT statement. It allows
getting the data out of the database perform operations with it.

 The CREATE TABLE command: The CREATE TABLE command defines


each column of the table uniquely. Each column has a minimum of three
attributes, a name, data type and size (i.e. column width).

 Rules for creating Tables:


1. A name can have maximum up to 30 characters.
2. Alphabets from A-Z, a-z and numbers from 0-9 are allowed.
3. A name should begin with an alphabet.
4. The use of the special character like _ is allowed and also recommended
(Special characters like $, # are allowed only in Oracle).
5. SQL reserved words not allowed. For example: create, select and so on.

Syntax: CREATE TABLE <tablename>


(<ColumnName1> <DataType>(<size>),
<ColumnName2> <DataType>(<size>), …… );

Example: Create table client_master


(c_no varchar2(5), name varchar2(10), address varchar2(20),
pincode number(6), bal_due number(10,2));

EXCERCISE:
1) Create a table “emp” with the following fields:
EMPNO ENAME JOB HIREDATE SAL COMM DEPTNO MGR

2) Create a table “dept” with the following fields:


DEPTNO DNAME LOCATION

3) Create a table “stud_master” with the following fields:


REG_NO S_NAME BRANCH

4) Create a table “stud_detail” with the following fields:


REG_NO COURSE_CODE COURSE_NAME MARKS SEM

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
EXPERIMENT NO: 2 DATE: / /

TITLE: How to insert data in a table using insert command and display the
records in a table.

OBJECTIVES: On completion of this experiment student will able to…


 Insert records into a table.
 Display records from a table.

THEORY:
 Inserting Data into Tables using INSERT INTO command:
 Once a table is created, most natural thing to do is load this table with data to be
manipulated later.

When inserting a single raw of data into the table, insert operation:
 Creates a new raw (empty) in the database table.
 Loads the values passed (by the SQL insert) into the columns specified.

Syntax: INSERT INTO <tablename> [(<ColumnName1>, <ColumnName2>, … )]


VALUES(<value1>,< value2>, ……);

Example: INSERT INTO client_master (c_no, name, address, pincode, bal_due)


VALUES (‘C001’, ‘Ajay’, ‘A-5, Bhandu’, 384120, 500 );

Note: Character value (expression) placed within the INSERT INTO statement
must be enclosed in single quotes (‘).

 Display / Viewing data in the Tables using SELECT command:


 Once data has been inserted into a table, the next most logical operation would
be to view what has been inserted. The SELECT SQL verb is used to achieve
this. The SELECT command is used to retrieve rows selected from one or
more tables.
 The SELECT statement can be used to Display some or all the columns from
a specified table.
 Display some or all of the rows from a specified table.
 Display calculated values from the table.
 Display statistical information from the tables, like averages or sums of
column values.
 Combine information from two or more tables.

In order to view global table data the syntax is:


SELECT <ColumnName 1> TO <ColumnName N> from TableName;

Note: Here, ColumnName 1 to ColumnName N represents table column names


and they separated by ‘,’.

All Rows and All Columns: When data from all rows and columns from the
table are to be viewed the syntax of the SELECT statement will be used. The syntax
is:

Syntax: SELECT * FROM <TableName>;

Example: SELECT * FROM client_master;

Oracle allows the use of the Meta character asterisk (*), this is expanded by Oracle
to mean all rows and all columns in the table.

Displaying Some Columns from a Table:

Syntax: SELECT <ColumnName 1>,<ColumnName 2>, …, <ColumnName N>


FROM <TableName>;

Example: SELECT c_no, name FROM client_master;

Displaying Some Specified Rows from the Table:


If you want conditional retrieval of rows i.e. only those rows which satisfy certain
condition. You can use WHERE clause in the SELECT statement.

Syntax: SELECT <ColumnName 1>,<ColumnName 2>, …, <ColumnName N>


FROM <TableName>
WHERE <Condition>;

Here, <Condtion> is always quantified as <ColumnName = Value>.

Example: SELECT c_no, name FROM client_master WHERE bal_due>500;


Elimination of duplicates from the select statement:
A table could hold duplicate rows. In such a case, to see only unique rows, you
have to use DISTINCT clause. The DISTINCT clause allows removing duplicates
from the result set. The DISTINCT clause can be only be used with SELECT
statements.

Syntax: SELECT DISTINCT <ColumnName 1>, …, <ColumnName N>


FROM <TableName>;

Example: SELECT DISTINCT job FROM emp;

The SELECT DISTINCT * SQL syntax scans through entire rows, and
eliminates rows that have exactly the same contents in each column.

Syntax: SELECT DISTINCT * FROM <TableName>;

Example: SELECT DISTINCT * FROM client_master;

Sorting data in a Table:


Oracle allows data from a table to be viewed in a sorted order. The rows
retrieved from the table will be sorted in either ascending or descending order
depending on the condition specified in the SELECT sentence.

Syntax: SELECT <ColumnName 1>, …, <ColumnName N> FROM


<TableName> ORDER BY <ColumnName 1>, …, <ColumnName N>
<[Sort Order]>;
Sort Order can be ascending (use word asc) or descending (use word desc). In
case there is no mention of the sort order, the Oracle engine sorts in ascending
order by default.

Example: a. SELECT * FROM client_master ORDER BY Name; (In ascending


order)
b. SELECT * FROM emp ORDER BY Job DESC; (In descending
order)
The format to display the records -

SELECT [DISTINCT] {*, column [alias],…}


FROM table
WHERE condition(s)
Group by column(s)
HAVING group of row condition(s)
ORDER BY {column. Expr} [ASC/DESC];

EXERCISES:

1) Insert records into emp table.


2) Insert records into dept table.
3) Insert records into stud_master table.
4) Insert records into stud_detail table.
5) Select all information from emp table.
6) List all the employees who have salary between 1000 and 2000.
7) List names and jobs of all clerks in department 20.
8) Display all the different job types.
9) List department numbers and names in department name order.
10) Select all information from stud_master table.
11) Display Registration number and name of students whose department is
“computer engineering”.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
EXPERIMENT NO: 3 DATE: / /
TITLE: Update or Delete records of a table and modifying structure of a table using
Alter and Drop command.

OBJECTIVES: On completion of this experiment student will able to…


 update or delete the data or records in the table.
 add or delete column in the table.
 change data type of given column and rename column.
 drop a table.

THEORY:

 Updating Rows: The UPDATE command is used to change or modify data values
in table.

Updating of All Rows:


Syntax: UPDATE <TableName> SET <ColumnName 1> = <Expression 1 or
Value 1>, <ColumnName N> = <Expression N or Value N>;

Example: Update the address details by changing its city name to Ahmedabad.
UPDATE ADDR_DTLS SET City = ‘Ahmedabad’;

Updating Records Conditionally:


Syntax: UPDATE <TableName> SET <ColumnName 1> = <Expression 1 or
Value 1>, <ColumnName N> = <Expression N or Value N> WHERE
<Condition>;

Example: Update the branch details by changing the AMP (HO) to Head Office.
UPDATE BRANCH_MSTR SET NAME = ‘Head Office’
WHERE NAME = ‘AMP (HO)’;

 Delete Operations:
 The DELETE command deletes rows from the table that satisfies the condition
provided by its WHERE clause, and returns the number of records deleted.

Removal of All Rows:


Syntax: DELETE FROM <TableName>;
Example: Empty the ACCT_DTLS table.
DELETE FROM ACCT_DTLS;
Removal of Specific Rows:
Syntax: DELETE FROM <TableName> WHERE <Condition>;

Example: Remove only the savings bank account details from the ACCT_DTLS
table.
DELETE FROM ACCT_DTLS WHERE ACCT_NO LIKE ‘SB%’;

 Inserting Data into a Table from another Table:


 To insert data one row at a time into a table, it is quite possible to populate a table
with data that already exists in another table.

Syntax: INSERT INTO <TableName> SELECT <ColumnName1>, … ,


<ColumnName N> FROM < TableName> [WHERE <Condition>];

 Here the WHERE clause is optional. If you are not specify the WHERE clause
then all the from source table to target table is copied.

Example: Insert only the savings bank accounts details in the target table
ACCT_DTLS from the source table ACCT_MSTR.

INSERT INTO ACCT_DTLS SELECT


ACCT_NO,BRANCH_NO,CURBAL FROM ACCT_MSTR
WHERE ACCT_NO LIKE ‘SB%’;

 Modifying the Structure of Tables:


 The structure of a table can be modified by using ALTER TABLE command.
ALTER TABLE allows changing the structure of an existing table. With ALTER
TABLE it is possible to add or delete columns, change the data type of existing
columns.

Adding New Columns:


Syntax: ALTER TABLE <TableName>
ADD (<NewColumnName> <DataType>(<Size>),
<NewColumnName> <DataType>(<Size>), …);

Example: Enter a new field called city in the table BRANCH_MSTR.


ALTER TABLE BRANCH_MSTR ADD(CITY VARCHAR2(25));

Dropping a Column from a Table:


Syntax: ALTER TABLE <TableName> DROP COLUMN <ColumnName>;
Example: Drop the column city from the table BRANCH_MSTR.
ALTER TABLE BRANCH_MSTR DROP COLUMN CITY;

Modifying Existing Columns:


Syntax: ALTER TABLE <TableName>
MODIFY(<ColumnName> <NewDataType>(<NewSize>));

Example: Alter table BRANCH_MSTR to allow the NAME field to hold


maximum of 30 characters.
ALTER TABLE BRANCH_MSTR MODIFY(NAME VARCHAR2(30));

 Destroying Tables:
 Sometimes tables within a particular database become obsolete and need to be
discarded. In such situation using DROP TABLE statement with the table name
can destroy a specific table. If a table is dropped all records held within it are lost
and cannot be recovered.
Syntax: DROP TABLE <TableName>;
Example: Remove the table BRANCH_MSTR along with the data held.
DROP TABLE BRANCH_MSTR;

EXCERCISES:
1) Add a column “SPOUSE” to the emp table that will hold the name of an
employee’s spouse.
2) Modify the job of employees to “programmer” whose job is “trainee”.
3) Delete record whose location is “Baroda” from dept table.
4) Drop a table “stud_master”.
5) Create a table “ManagerHist” from emp whose job is “Manager”.
6) Copy all the information of department 20 into the “ManagerHist” table.
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 4 DATE: / /
TITLE: Study of character functions for manipulation of data items.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of character function.

THEORY:

 Character functions:
 Character functions are described as follow:

Function Description Example


Returns the string s with the first character of
INITCAP('hello SIR') = 'Hello
INITCAP(s) each word in uppercase and all others in Sir'
lowercase.
Returns the number of characters in the string
LENGTH(s) LENGTH('Welcome Sir') = 11
s.
Returns the string s with all characters in LOWER('Welcome Sir') =
LOWER(s)
lowercase. 'welcome sir'

Returns s without any leading character that


LTRIM('welcome', 'slow') =
LTRIM(s, s1) appear in s1. If no s1 character are leading 'elcome'
characters in s, then s is returned unchanged.
Returns s without any trailing character that
RTRIM('Mississippi', 'pi') =
RTRIM(s, s1) appear in s1. If no s1 character are trailing 'Mississ'
characters in s, then s is returned unchanged.
Returns s with all occurrences of substring s1 REPLACE('www.yahoo.com',
REPLACE(s, s1[,
s2])
replaced with s2. By default s2 is NULL and 'yahoo', 'google') =
all occurrences of s1 are removed. 'www.google.com'

Returns the portion of the string s that is len


characters long, beginning at position pos. If SUBSTR('welcome', 4) = 'come'
pos is negative, the position is counted
SUBSTR(s, pos[,
len])
backwards from the end of the string. The SUBSTR('welcome',2,2) = 'el'
function returns NULL if len is less or equal to
SUBSTR('welcome',-3,2) = 'om'
zero. If len is skipped, it returns the remaining
of s.
Returns the string s with all occurrences of
TRANSLATE(s, s1, TRANSLATE('alfabet',
s2)
characters in s1 replaced with the positionally 'abscde', 'BCDE') = 'BlfBCt'
corresponding characters is s2.If s2 is shorter
than s1, the unmatched characters in s1 are
removed.
This function returns the string s with all s1
TRIM([LEADING|
(leading, trailing, or both (by default it's
TRAILING| TRIM(BOTH '.' FROM 'etc ...')
BOTH)) occurrences of characters in s
BOTH [s1 = 'etc '
FROM]] s) removed. The default value of s1 is a space
character.
Returns the string s with all characters in UPPER('Welcome Sir') =
UPPER(s)
uppercase. 'WELCOME SIR'

Returns the number of bytes in the internal


VSIZE(s) VSIZE('SCT on the net') = 14
representation of an s.
Returns s, left-padded to length n with the
LPAD('Page 1',10,’*’) = ****Page
LPAD(s,n[,s1]) sequence of characters specified in s1. if s1 is 1
not specified Oracle uses blanks by default.
Returns s, right-padded to length n with the
RPAD('Page 1',10,’*’) = Page
RPAD(s,n[,s1]) sequence of characters specified in s1. if s1 is 1****
not specified Oracle uses blanks by default.
Returns the location of a substring in a string.
String2 is the substring to search for in
string1. The default start position is 1.
INSTR(<string1, INSTR(‘SCT on the net’,’t’) = 8
If the start position is negative, the function
string2, [<start
position>],[nth
counts back start position number of INSTR(‘SCT on the net’,’t’,1,2)
appearance]) characters from the end of string1 and then = 14
searches towards the beginning of string1.
nth appearance is the nth appearance of
string2 and default is 1.
CONCAT CONCAT(‘Nirma’,
(<string1>, String2 is concated to string1. ’University’) = ‘Nirma
<string2>) University’

EXCERCISE:

1) Produce the following output


EMPLOYEE_AND_SALARY
AJAY 10000
JASHVANT 52000
PRAKASH 40850
SUDHA 65000
-------- -------
-------- -------
-------- -------

2) Produce the following output


EMPLOYEE
---------------------------------------------
AJAY (Assistant Professor)
JASHVANT (Manager)
RAHUL (Project Leader)
-------- -----------

3) Write the difference between REPLACE and TRANSLATE functions.


4) The LENGTH function returns the length of a word. (State True / False with
justification.)
5) The __________ function removes characters from the left of char with initial
characters removed upto the first character not in set.
6) LPAD returns the string passed as a parameter after justify padding it to a
specified length. (State True / False with justification.)

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 5 DATE: / /
TITLE: Study of number and date functions for manipulation of data items.

OBJECTIVES: On completion of this experiment student will able to…


 know the concept of number function
 know the concept of date function.
THEORY:

 Number functions:
 Number functions are described as follow:

Function Description Example


ABS(d) Returns the absolute value of the double d. ABS(-25.52) = 25.52
Returns the smallest integer that is greater CEIL(24.8) = 25
CEIL(d)
or equal to d. CEIL(-24.8)= -24
EXP(d) Returns ed EXP(5) = 148.413159
FLOOR(24.8) = 24,
FLOOR(d) Returns the largest integer less or equal to d.
FLOOR(-24.8)= -25
LN(d) Returns the natural logarithm of d. LN(10) = 2.30258509
LOG(b, d) Returns logbd. LOG(10,40) = 1.60205999
Returns i1 modulo i2, or the reminder of i1
MOD(i1, i2) MOD(15,7) = 1
divided i2.
POWER(d, p) Returns d to the pth power (dp). POWER(2,5)= 32
Returns d rounded to i digits of precision to
the right of the decimal point. If i is ROUND(2.6586,2) = 2.66
ROUND(d, i)
negative, d is rounded to the left of the ROUND(289.6586,-2)= 300
decimal point.
SIGN(-25) = -1
Returns -1 if d is negative, 1 if d is positive,
SIGN(d) SIGN(0) = 0
and 0 if d is zero.
SIGN(25) = 1
SQRT(d) Returns the square root of d. SQRT(81) = 9
Returns d truncated to i digits of precision
TRUNC(256.8888,2) =
to the right of the decimal point. If i is
TRUNC(d, i) 256.88
negative, d is truncated to the left of the
TRUNC(256.8888,-2) = 200
decimal point.
 Date functions:
 Implicit Date-to-String conversion is based on the value of the
NLS_DATE_FORMAT variable. To change its value use the ALTER SESSION
command:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS';
 Date functions are described as follow:

Function Description Example


Returns the date dt plus i months. If i
is a decimal number. Oracle will ADD_MONTHS(SYS
ADD_MONTHS(dt, i) automatically convert it to an integer DATE, 2) = 13-10-2008
by truncating the decimal portion (it 21:23:00
may also be negative).
MONTHS_BETWEEN(
Returns the number of months that '01-JAN-
dt1 is later than dt2. A whole number 2009',SYSDATE) = 4
MONTHS_BETWEEN(dt1,
dt2)
is returned if dt1 and dt2 are the same
day of the month or if both are th last MONTHS_BETWEEN(
day of the month. '01-JAN-
2007',SYSDATE) = -19
Returns the date that corresponds to
the next day of week specified by the
string s following the date dt. The
NEXT_DAY(SYSDATE
time portion of the date is the same as
NEXT_DAY(dt, s) , 'Mon') = 18-08-2008
the time portion of dt. The string s
21:26:32
should be a text string containing the
full or abbreviated day of the week in
the session's language.
Returns the date dt rounded to the
ROUND(SYSDATE,
granularity specified in the date-
ROUND(dt[, fmt]) 'HH24') = 13-08-2008
format string fmt. See date format
21:00:00
codes.
Returns the current date/time, takes SYSDATE = 13-08-
SYSDATE
no arguments. 2008 21:28:13
 Conversion functions:
 Conversion functions are described as follow:

Function Description
Takes up to three arguments, where x is either a date or a number, fmt is
a format string specifying the format that x will appear in, and nls
TO_CHAR(x[,
fmt[, nls]])
specifies language or location formatting string.
If x is a date, fmt is a date format code.
If x is a number, fmt is a numeric format code.
Converts string s to DATE datatype accordingly the format string fmt.
TO_DATE(s[,
fmt[, nls]])
The fmt string uses the same date format code. The default is the value
stored in the NLS_DATE_FORMAT session variable.
TO_NUMBER(s[, Returns the numeric value represented by the string s. The format string
fmt[, nls]]) fmt specifies the format the that s appears in.

EXCERCISE:

1) Write down the query that “Display each employee name with hire date, and salary
review date. Assume review date is after one year after hire date. Order the output in
ascending review date order”.
2) Differentiate: ROUND and TRUNC functions.
3) The __________ function returns number of months between two dates.
4) The TO_DATE() function also disallows part insertion of a DATE value into a column.
(State True / False with justification.)
5) The __________ function converts a value of a DATE datatype to CHAR value. (State
True / False with justification.)

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 6 DATE: / /
TITLE: To perform join operation between various tables.

OBJECTIVES: On completion of this experiment student will able to…


 fetch the data from more then one table on database.
 know different types of join.
THEORY:

 Join: A join is used when a SQL query requires data from more than one table on
database.
 There are two main types of join conditions: -
 Equi-join
 Non-equi join

 Equi-join: The relationship between two tables is equi join when any one column
corresponds to the same column in oyher table e.g. deptno in EMP table as well as in
DEPT table. Here relationship is obtained using “=” operator.

 Non Equi-join: The relationship between two tables is non equi join when no
column in one table corresponds directly to a column in other table. Here relationship
is obtained other than “=” operator

 Self Joins:
 A self join is a join of a table to itself. This table appears twice in the FROM clause
and is followed by table aliases that qualify column names in the join condition.
To perform a self join, Oracle combines and returns rows of the table that satisfy
the join condition.

 Inner Joins:
 An inner join (sometimes called a "simple join") is a join of two or more tables that
returns only those rows that satisfy the join condition.

 Cross Joins:
 If two tables in a join query have no join condition, Oracle returns their Cartesian
product. Oracle combines each row of one table with each row of the other. A
Cartesian product always generates many rows and is rarely useful. For example,
the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always
include a join condition unless you specifically need a Cartesian product.
Outer Joins:
 An outer join extends the result of a simple join. An outer join returns all rows that
satisfy the join condition and also returns some or all of those rows from one table
for which no rows from the other satisfy the join condition.
 To write a query that performs an outer join of tables A and B and returns all
rows from A (a left outer join), use the LEFT [OUTER] JOIN syntax in the
FROM clause, or apply the outer join operator (+) to all columns of B in the join
condition in the WHERE clause. For all rows in A that have no matching rows
in B, Oracle returns null for any select list expressions containing columns of B.
 To write a query that performs an outer join of tables A and B and returns all
rows from B (a right outer join), use the RIGHT [OUTER] JOIN syntax in the
FROM clause, or apply the outer join operator (+) to all columns of A in the join
condition in the WHERE clause. For all rows in B that have no matching rows
in A, Oracle returns null for any select list expressions containing columns of
A.
 To write a query that performs an outer join and returns all rows from A and
B, extended with nulls if they do not satisfy the join condition (a full outer
join), use the FULL [OUTER] JOIN syntax in the FROM clause.

EXCERCISE:
1) Define: Join. Explain self join.
2) Retrieve employee number, employee name and their department name, in department
name order.
3) Show all employee details who lives in Baroda.
4) Display the name, salary and department number of employees whose salary is more
than 10000.
5) List the employee name, job, salary and department name for everyone in the company
except clerks. Sort on salary displaying the highest salary first.
6) List all employees by name and number along with their manager’s name and number.
7) Display all the employees who earn less than their managers.

EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 7 DATE: / /

TITLE: Applying constraint using two tables.

OBJECTIVES: On completion of this experiment student will able to…


 learn the different types of constraints.

THEORY:

 Constraints are classed as either:


1. Table constraints
 These may reference one or more columns and are defined separately from the
definitions of the columns in the table.

2. Column constraints
 These reference a single column and are defined within the specification for the
owning column.

 Constraint types-
 You may define the following constraint types-
1. Primary key
2. Foreign key
3. Unique
4. Null /Not null
5. Check

Primary key constraint: A primary key is a one or more column(s) in a table used to
uniquely identify each row in the table. None of the fields that are part of the primary key
can contain a null value. A table can have only one primary key.

PRIMARY KEY Constraint Defined at Column Level:

Syntax: <ColumnName> <Datatype> (<Size>) [Constraint constraint_name]


PRIMARY KEY

PRIMARY KEY Constraint Defined at Table Level:

Syntax: [Constraint constraint_name] PRIMARY KEY (<ColumnName 1>,


<ColumnName 2>)
Foreign key constraint:
 Foreign key represent relationships between tables. A foreign key is table whose values

are derived from the primary key or unique key of some other table.

 The table in which the foreign key is defined is called a foreign table or Detail table.

 The table that defines the primary or unique key and is referenced by the foreign key is

called the Primary table or Master table.

 The master table can be referenced in the foreign key definition by using the

REFERENCES adverb. If the name of the column is not specified, by default, oracle

references the primary key in master table.

FOREIGN KEY Constraint Defined at the Column Level:

Syntax: <ColumnName> <DataType>(<size>) [Constraint constraint_name]


REFERENCES <TableName> [(<ColumnName>)]

FOREIGN KEY Constraint Defined at the Table Level:

Syntax: [Constraint constraint_name] FOREIGN KEY ( <ColumnName>


[,<ColumnName>] ) REFERENCES <TableName> (<ColumnName>
[,<ColumnName>])

Unique constraint: The Unique column constraint permits multiple entries of NULL into
a column. These NULL values are clubbed at the top the column in order in which they
were entered into the table. This is the essential difference between the Primary Key and
Unique Constraints when applied to table column(s).

UNIQUE Constraint Defined at Column Level:

Syntax: <ColumnName> <Datatype> (<Size>) [Constraint constraint_name]


UNIQUE

UNIQUE Constraint Defined at the Table Level:

Syntax: [Constraint constraint_name] UNIQUE (<ColumnName 1>,


<ColumnName 2>)
The CHECK Constraint: Business rule validations can be applied to a table column by
using CHECK constraint. It must be specified as a logical expression that evaluates either to
TRUE or FALSE.

Note: A CHECK constraint takes substantially longer to execute as compared to NOT


NULL, PRIMARY KEY, FOREIGN KEY OR UNIQUE. Thus CHECK constraints must be
avoided if the constraint can be defined using the Not Null, Primary Key or Foreign Key
Constraint.

The CHECK Constraint defined at the Column Level:


Syntax: <ColumnName> <DataType>(<Size>) CHECK (<Logical Expression>)
Example: Create a table CUST_MSTR with the following CHECK constraints:
 Data values being inserted into the column CUST_NO must start with the capital
letter C.
 Data values being inserted into the column FNAME, LNAME should be in upper
case only.

CREATE TABLE CUST_MSTR


(CUST_NO VARCHAR2(10) CHECK (CUST_NO LIKE ‘C%’),
FNAME VARCHAR2(20) CHECK (FNAME = UPPER(FNAME)),
LNAME VARCHAR2(20) CHECK (LNAME = UPPER(LNAME)),
DOB DATE, PANCOPY VARCHAR2(1), PHOTOGRAPH VARCHAR2(25));

The CHECK Constraint defined at the Table Level:


Syntax: CHECK (<Logical Expression>)
Example: Create a table CUST_MSTR with the following CHECK constraints:
 Data values being inserted into the column CUST_NO must start with the capital
letter C.
 Data values being inserted into the column FNAME, LNAME should be in upper
case only.

CREATE TABLE CUST_MSTR


(CUST_NO VARCHAR2(10), FNAME VARCHAR2(20), LNAME VARCHAR2(20),
DOB DATE, PANCOPY VARCHAR2(1), PHOTOGRAPH VARCHAR2(25), CHECK
(CUST_NO LIKE ‘C%’), CHECK (FNAME = UPPER(FNAME)), CHECK (LNAME =
UPPER(LNAME)));
EXCERCISE:
1) Create the a table client_master with the following fields:
clientno, name, address, city, pincode, state, bal_due.
Consider the appropriate data type and size for the columns. In addition, define clientno
as the primary key column.

2) Create the a table product_master with the following fields:


Productno, Description, Qty_on_hand, Sell_price, Cost_price.
Consider the appropriate data type and size for the columns. In addition, define
Productno as the primary key column and check data values being inserted into the
column Productno must start with the capital letter ‘P’.

3) Create the a table salesman_master with the following fields:


Sno, S_name, Address, city, Pincode, State, Sal_amt, Tgt_to_get
Consider the appropriate data type and size for the columns. In addition, define Sno as
the primary key column.

4) Create the a table sales_order with the following fields:


Orderno, clientno, orderdate, delyaddr, sno, delydate.
Consider the appropriate data type and size for the columns. In addition, define
Orderno as the primary key column and define its clientno column as a foreign key,
which references the client_master table & sno column as a foreign key, which
references the salesman_master table.

5) Create the a table sales_order_details with the following fields:


Orderno, Productno, qtyordered
Consider the appropriate data type and size for the columns. In addition, define its
Orderno column as a foreign key, which references the sales_order table & Productno
column as a foreign key, which references the product_master table.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 8 DATE: / /

TITLE: How to retrieve data from different tables using sub queries and correlated queries.

OBJECTIVES: On completion of this experiment student will able to…


 use the clauses ORDER BY, GROUP BY & HAVING BY.
 know the concept of Sub Queries

THEORY:

The format of the sub query is:


SELECT column 1, column 2, …. , column N FROM table
WHERE column <operator> (SELECT column FROM table WHERE condition);

 Steps:
1. The inner queries must be enclosed in parentheses, and must be on the right hand
side of the condition.

2. The sub query may not have an ORDER BY clause.

3. The ORDER BY clause appears at the end of the main select statement.

4. Sub queries are always executed from the most deeply nested to the least deeply
nested, unless they are correlated queries.

5. Logical and SQL operators may not be used as well as ANY and ALL.

EXCERCISE:

1. Find the employees who earn the maximum salary for their department. Display the
result in ascending order of salary.
2. Find the most recently hired employees in each department. Order by hire date.
3. Find the employees who earn the highest salary in each job type. Sort in descending
salary order.
4. Show the following details for any employee who earns a salary less than the average
for their department.
ENAME SALARY DNAME JOB
5. Who are the top three earners in the company? Display their name and salary.
6. Display the empno, name, job and deptno for employees whose salary is greater than
the highest salary in any SALES department.

EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 9 DATE: / /

TITLE: Understanding of Database Objects: synonym, sequence, index and view.

OBJECTIVES: On completion of this experiment student will able to…


 learn view, synonym, index & sequence.
 create view, synonym, index & sequence.

THEORY:

 Introduction of Index:
 An index is an ordered list of the contents of a column, (or a group of columns) of a
table.
 Indexing involves forming a two dimensional matrix completely independent of the
table on which the index is being created. This two dimensional matrix will have a
single column, which will hold sorted data, extracted from the table column(s) on
which the index is created.
 Another column called the address field identifies the location of the record in the
oracle database.

 Creation of an Index:
 An index can be created on one or more columns. Based on the number of columns
included in the index, an index can be:
 Simple Index
 Composite Index
 Unique Index

 Creation of Index:
 An index is created on a single column of a table is called a Simple Index. The syntax
for creating simple index that allows duplicate values is as described:

Syntax: CREATE [UNIQUE] INDEX <IndexName> ON


TableName>(<ColumnName1>[,<ColumnName2>,..,<ColumnNameN>]);
Example: CREATE INDEX idx_c_no ON client_master(c_no);

 Dropping Index:
 Indexes associated with the tables can be removed by using the DROP INDEX
command.
Syntax: DROP INDEX <IndexName>;
Example: DROP INDEX idx_c_no;

 When a table, which has associated indexes, is dropped, the oracle engine
automatically drops all the associated indexes as well.

 Introduction of View:
 A VIEW is a virtual table in the database whose contents are defined by a query it
can represent.
 A view holds no data at all, until a specific call to the view is made. This reduces
redundant data on a HDD to a very large extent.

 Creation of views:
Syntax: CREATE VIEW <ViewName> AS
SELECT <ColumnName1>, <ColumnName2>
FROM <TableName>
WHERE <ColumnName>=expression list
GROUP BY <Grouping Criteria>
HAVING <Predicate>;

Note: The ORDER BY clause cannot be used while creating a view.

Example: Create view on the emp table for the Department 10 which access for the
columns empno,ename,sal.
Answer: create view vw_emp10 as select empno,ename,sal from emp
where deptno = 10;

 Selecting a data set from a view:


 Once a view has been created, it can be queried exactly like a base table.
 The select statement can have the clause like WHERE, ORDER BY etc.

Syntax: SELECT <ColumnName1>, <ColumnName2> FROM <ViewName>;


Example: select * from vw_emp10 where sal < 35000 order by empno;

 Introduction of Sequence:
 Most application requires automatic generation of numeric value.
 Sequences are tools used to generate a unique sequential number that can be used in
the data tables. One of the best features of sequences is that they guarantee that you
will get a unique value when you access the sequence.
 The value generated can have a maximum of 38 digits.
 Creation of Sequence:
Syntax: CREATE SEQUENCE <SequenceName>
[INCREMENT BY <IntegerValue>
START WITH <IntegerValue>
MAXVALUE <IntegerValue> / NOMAXVALUE
MINVALUE <IntegerValue> / NOMINVALUE
CYCLE/ NOCYCLE
CACHE <IntegerValue>/ NOCACHE
ORDER / NOORDER]

Note:
 Sequence is always given a name so that it can be referenced later when required.
 The ORDER, NOORDER Clause has no significance, if Oracle is configured with
Single server option. It is useful only when you are using Parallel Server in Parallel
mode option.
 If the CACHE / NOCACHE clause is omitted oracle caches 20 sequence numbers by
default.

Example:
Create sequence order_seq, which will generate numbers from 1 to 9999 in ascending
order with an interval of 1. The sequence must restart from the number 1 after
generating number 9999.
CREATE SEQUENCE order_seq INCREMENT BY 1 START WITH 1
MINVALUE 1 MAXVALUE 9999 CYCLE;

 Referencing a Sequence:
 Once a sequence is created SQL can be used to view the values held in its cache. To
simply view sequence value use a select sentence as described below.
SELECT <sequence_name>.NextVal FROM dual;
 This will display the next value held in the cache on the VDU screen. Every time
nextval references a sequence its output is automatically incremented from the old
value to the new value ready for use.
 After creating a table you can add the data by using the INSERT command like this:
INSERT INTO sales_order(o_no, o_date, c_no)
VALUES (order_seq.nextval, sysdate, ‘c0001’);
 To references the current value of a sequence:
SELECT <sequence_name>.CurrVal FROM dual;

 Introduction of Synonyms:
 A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
Syntax: CREATE [OR REPLACE] [PUBLIC] SYNONYM [SCHEMA.]
SYNONYM_NAME FOR [SCHEMA.] OBJECT_NAME [@DBLINK];

Example: Create a synonym to a table EMP held by the user SCOTT.

CREATE PUBLIC SYNONYM EMPLOYEES FOR SCOTT.EMP;

Now, users of other schemas can references the table EMP, which is now called
EMPLOYEES without having the prefix the table name with the schema named
SCOTT.

For example, SELECT * FROM EMPPLOYEES;

EXCERCISE:
6) Create view on the emp table for the job “Clerk” which access for the columns empno,
ename, job, sal and rename the column empno as “empnumber”. And access the data of
view.
7) Create a sequence “seq3” with the following parameters:
Increment by -1, cache 20, cycle, noorder and which will generate the numbers from 1 to
5000 in descending order.
8) Create a simple index on “orderid” column of a table ‘order’.
9) Create a synonym “employee“ from the table emp.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________


EXPERIMENT NO: 10 DATE: / /

TITLE: To study the concepts of Normalization.

OBJECTIVES: On completion of this experiment student will able to…


 what is normalization?
 reasons of normalization.
 forms of normalization.

THEORY:

 WHAT IS NORMALIZATION?
 “Normalization is essentially the process of taking a wide table with lots of columns
but few rows and redesigning it as several narrow tables with fewer columns but
more rows.”
 A properly normalized design allows you to use storage space efficiently, eliminate
redundant data, reduce or eliminate inconsistent data, and ease the data maintenance
burden. Before looking at the forms of normalization, you need to know one cardinal
rule for normalizing a database:
“You must be able to reconstruct the original flat view of the data.”

 Normalization is carried out for the following reasons:


1. To structure the data between tables so that data maintenance is simplified.
2. To allow data retrieval at optimal speed.
3. To simplify data maintenance through updates, inserts and deletes.
4. To reduce the need to restructure tables as new application requirements arise.
5. To improve the quality of design for an application by rationalization of table data.

 Forms of normalization:
 Relational database theorists have divided normalization into several rules called
normal forms.
 First Normal Form: No repeating groups.
 Second Normal Form: No nonkey attributes depend on a portion of the primary
key.
 Third Normal Form: No attributes depend on other non-key attributes.
 Boyce-Codd normal form (BCNF): Every non-trivial functional dependency in
the table is a dependency on a superkey.
 Fourth Normal Form: Every non-trivial multivalued dependency in the table is a
dependency on a superkey.
 Fifth Normal Form: Every non-trivial join dependency in the table is implied by
the superkeys of the table.

EXCERCISE:
10) Normalize the following table upto third normal form:

Author Author
Collection or
Last First Book Title Subject Publisher Building
Library
Name Name

PCL General
Berdahl Robert Politics History Wiley B – Block
Stacks

Legal
Yudof Mark Child Abuse Person Law Library C – Block
Procedures

Human Memory Cognitive PCL General


Harmon Glynn TMH B – Block
and Knowledge Psychology Stacks

Greek
Graves Robert The Golden Fleece Wiley Classics Library D – Block
Literature

Library and
Charles Ammi Library Information
Miksa Francis Person B – Block
Cutter Biography Science
Collection

Music Publishing Music


Hunter David TMH Fine Arts Library A – Block
and Collecting Literature

English and PCL General


Graves Robert Folksong Mahajan B – Block
Scottish Ballads Stacks

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

You might also like