0% found this document useful (0 votes)
17 views

dbms

dbms book
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

dbms

dbms book
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Ahmedabad Institute of Technology

Computer Engineering Department


DATABASE MANAGEMENT SYSTEM
(3130703)

Laboratory Manual

NAME

ENROLLMENT NUMBER

BATCH

YEAR

SUBJECT COORDINATOR SUBJECT MEMBER


DEPARTMENT OF COMPUTER ENGINEERING

Vision of the Department:

“To create competent professionals in the field of Computer Engineering and promote research
with a motive to serve as a valuable resource for the IT industry and society.”

Mission of the Department:

1. To produce technically competent and ethically sound Computer Engineering professionals by


imparting quality education, training, hands on experience and value-based education.
2. To pursue creative research, adapt to rapidly changing technologies and promote self-learning
approaches in Computer Engineering and across disciplines to serve the dynamic needs of
industry, government and society.
3. To inculcate ethical attitude, sense of responsibility towards society and leadership ability
required for a responsible professional computer engineer.

Program Educational Objectives (PEO):


PEO 1. Are proficient in fundamentals of science, mathematics, electronics and computer science and
engineering and skills necessary for a successful IT professional.
PEO 2. Learn, apply skills, techniques, and competency to use modern engineering tools to solve
computational problems.
PEO 3. Demonstrate ability to adapt to the challenges of evolving career opportunities in their chosen
fields of career including higher studies, research avenues, entrepreneurial activities etc.
PEO 4. Engage in lifelong learning, inculcate leadership qualities and teamwork ability with a sense of
ethics for a successful professional career in their chosen field.
PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
DBMS PRACTICAL BOOK
DEPARTMENT OF COMPUTER ENGINEERING
PREFACE

It gives us immense pleasure to present the first edition of DBMS Practical Book for the B.E.
2nd year students of Ahmedabad Institute of Technology.

The theory and laboratory course of Database Management System, at AIT, AHMEDABAD, is
designed in such a manner that students can develop the basic understanding of the subject during
theory classes and gain hands-on practical experience during their laboratory sessions. The main
objective of the Database Management System laboratory course is: Learning Database Management
System through its basic principles and characteristics. All the experiments are designed to
understand the characteristics of various database concepts. The objective of this DBMS Practical
Book is to provide a comprehensive source for all the experiments included in the DBMS laboratory
course.We acknowledge the authors and publishers of all the books which we have consulted while
developing this Practical book. Hopefully this Database Management System Practical Book will
serve the purpose for which it has been developed.

The student is required to keep a laboratory manual in which the raw data will be recorded as well as
the questions will be kept. The lab write-ups form a permanent record of your work.
Do’s

1 Enter the laboratory in student uniform and carry Student ID.

2 Leave footwear outside and keep bags or any other belongings in designated storage places.
Do not keep any valuable things in bags.
3 Carry only the laboratory notebook into the laboratory and keep other belongings at the place
designated for keeping belongings.
4 Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.
5 Report fires or accidents to your lecturer/laboratory technician immediately
6 Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician
immediately.
7 Read and understand how to carry out an activity thoroughly before coming to the laboratory.

8 For system problems, call laboratory staff for resolving, and do not try to repair the system
on your own.
9 Access to the internet is only on designated systems and against permission.
10 Ensure computer systems are properly shutdown and other equipment are turned-off after
use.
11 Follow the rules of the laboratory strictly. Violation of rules may attract punishment.

Don’ts

1 Do not eat or drink in the laboratory.

2 Do not carry and use any pen drive, electronic gadget or cell phone in the laboratory.
3 Do not install, update or download any software on your own in any computer inside the
laboratory.
4 Do not use any unauthorized software or tools.

5 Do not alter or delete configuration settings of any computer laboratory system.

6 Tampering, deleting or modifying CMOS/BIOS settings, IP Configuration, system


parameters, or system files stored in the hard disk are strictly prohibited in the laboratory.
7 No student or personnel is allowed to attach or detach any peripheral to and from any IT
equipment or devices without explicit permission from the Lab In charge/ Lab Technician.

8 Do not write/scratch on monitors, walls, tables or chairs in the laboratory.

9 Avoid stepping on electrical wires or any other computer cables.


10 Do not open the system unit casing or monitor casing particularly when the power is turned
on. Some internal components hold electric voltages of up to 30000 volts, which can be fatal.

11 Do not insert metal objects such as clips, pins and needles into the computer casings. They
may cause fire.
Ahmedabad Institute of Technology
Computer Engineering Department

CERTIFICATE
This is to certify that Mr. / Ms.
Of Enrolment No has Satisfactorily
completed the course in as
by the Gujarat Technological University for Year (B.E.) semester
of Computer Engineering in the Academic year .

Date of Submission:-

Faculty Name : Dr. Dushyantsinh B.


Rathod Signature (Head Of Department)
INDEX

Sr.No. Experiment Page no. Date Marks Signature

From To

1. Introduction of Database management


systems, Oracle concepts and Create a table.

2. How to insert data in a table using


insert and display the records in a table.

3. Update or Delete records of a table


and modifying structure of a table
using Alter and Drop command.

4. Study of character functions for


manipulation of data items.

5. Study of number and date functions for


manipulation of data items.

6. To perform join operation between


various tables.

7. Applying constraint using two tables.

8. How to retrieve data from different


tables using sub queries correlated queries.

9. Understanding of Database Objects:


synonym, sequence, index and view

10. To study the concepts of


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 to accepted as the definitive
model for RDBMS. The language developed by IBM to manipulate the data stored within
model was originally called Structured English Query Language (SEQUEL) with the word
English later dropped in favor Structured Query Language (SQL).
In 197 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:
▪ Oracle Server tools: Oracle Server Product is either called Oracle Work group 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’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 need
▪ 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 IBMResearchinthemid1970 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 setup, 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 data base. 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 with in 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 upto 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.
Synt CREATE TABLE <tablename> (<ColumnName1> <DataType>(<size>),
ax: <ColumnName2> <DataType>(<size>), ……);

Exampl Create table client_master


e: (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 POST HIREDATE SALARY CONTACT DEPTNO ADDR

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:
Involvement (4) Understanding Timely Total(10)
/problem solving (3) Completion(3)

Signature with date:


EXPERIMENT NO: 2 DATE:

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

OBJECTIVES: 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.

Synta INSERT INTO <tablename> [(<ColumnName1>,


x: <ColumnName2>, …… )] VALUES(<value1>,< value2>, ……);

Exampl INSERT INTO client_master (c_no, name, address, pincode, bal_due)


e: 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 <Column Name 1> TO <Column Name N> from Table Name;

Note: Here, Column Name 1 to Column Name 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 <Table Name>;

Exam SELECT * FROM client_master;


ple:

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:

Synta SELECT <ColumnName 1>,<ColumnName 2>, …,


x: <ColumnNameN>FROM <TableName>;

Exam SELECT c_no, name FROMclient_master;


ple:

Displaying Some Specified Rows from the Table:


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

Synta SELECT <ColumnName 1>,<ColumnName 2>, …,<ColumnNameN>FROM


x: <TableName> WHERE <Condition>;

Example SELECT cno , name FROM client_master WHERE bal_due>500


:
ELIMINATION OF DUBLICATES
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.

Synt SELECT DISTINCT <ColumnName 1>, …, <ColumnName N>FROM


ax: <TableName>;

Exampl SELECT DISTINCT job FROMemp;


e:

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

Synt SELECT DISTINCT * FROM <TableName>;


ax:

Exampl SELECT DISTINCT * FROMclient_master;


e:

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.
Synta SELECT <ColumnName 1>, …, <ColumnName N>FROM<TableName>
x: ORDER BY <ColumnName 1>, …, <ColumnNameN><[Sort Order]>;

Sort Order can be ascending (use word asc) or descending (use word esc). In case there is no mention
of the sort order, the Oracle engine sorts in ascending order by default.
Examp SELECT * FROM client_master ORDERBYName;(In ascending order)
le: SELECT * FROM emp ORDER BY Job DESC; (Indescendingorder)
EXERCISES:

1) Insert records into emp table.


001, 'employee1','programmer', '07-aug-2020', 20000,20,2000,1000
002, 'employee2','programmer', '08-sep-1999', 20000,20,2000,1000
003, 'employee3','develpoer', '09-sep-2020', 20000,10,2000,1000
004, 'employee4','develpoer', '08-sep-2020', 30000,10,3000,2000
005, 'employee5','ceo', '09-oct-1999', 40000,10,5000,5000
2) Insert records into dept table.
10,computer ,baroda 10,IT ,baroda 20, EC ,AHEMADABAD 20,Civil ,AHEMEDBAD
10,MARCH ,baroda
3) Insert records into stud_master table.
6001,PATEL RAM ,IT 7001,SHAH KAVI ,COMP 5001, THAKOR RAVI ,EC 4001,THAKKR
SITA,MECH 3001,PATE RADHA , CIVIL
4) Insert records into stud_detail table.
6001,703,DBMS,30 ,3 7001, 703,DBMS,29 ,3 5001, 701,PE,28 ,3 4001, 705,IC,27 ,3
3001, 700,SE,30 ,3
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 employee in department 20.
8) Display all the different job types.
9) List department numbers and names in department name order.
10) Select register no and marks of student from stud_details whose marks is 30
11) Display Registration number and name of students whose department is“comp”.from
stud_master
12) display distinct city name from dept table order by city name

EVALUATION:

Involvement (4) Understanding Timely Total(10)


/problem solving (3) Completion(3)

Signature with date:


EXPERIMENT NO: 3 DATE:

TITLE: Update or Delete records of a table and modifying structure of a table using Alter and
Drop command.

OBJECTIVES: 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 modifydatavalues in


table.

Updating of All Rows:


Syntax: UPDATE <TableName> SET <ColumnName 1> = <Expression1orValue 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> = <Expression1orValue 1>,


<ColumnName N> = <Expression Nor Value N>WHERE<Condition>;

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

❖ Delete Operations:
The DELETE command deletes rows from the table that satisfies theconditionprovided 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 fromthe


ACCT_DTLStable.
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.

Syn INSERT INTO <TableName> SELECT <ColumnName1>, …,


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

Here the WHERE clause is optional. If you are not specify the WHEREclausethen 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
FROMACCT_MSTRWHERE 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 ALTERTABLE it is possible to add or
delete columns, change the data type of existing 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 COLUMNCITY;

Modifying Existing Columns:

Syntax: ALTER TABLE <TableName> MODIFY(<ColumnName>


<NewDataType>(<NewSize>));

Example: Alter table BRANCH_MSTR to allow the NAME fieldtoholdmaximum


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

❖ Destroying Tables:
Sometimes tables within a particular database become obsolete andneedtobe
discarded. In such situation using DROP TABLE statement with the tablenamecan destroy a specific
table. If a table is dropped all records held withinit arelostand 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) Add a column “email” to emp table
3) update spouse name 'sunita' for eno=001; 'rita' for eno=002;'mita' for eno=003;

'lata' for eno=004;'shamita' for eno=005; and email of emp table


4) Delete the record of emp whose spouse name is “smita”

5) modify the column reg_no of stud_master table to hold digit of 5 only


6) Modify the job of employees to “trainer” whose job is “programmer”.
7) Delete record whose location is “Baroda” from dept table.
8) Drop a table “stud_master”.
9) Create a table “ManagerHist” from emp whose job is “developer”.
10) Create a table marklist from stud_record whose mark is 30
.

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

Signature with date:


EXPERIMENT NO: 4 DATE:

TITLE: Study of character functions for manipulation of data items.

OBJECTIVES: know the concept of character function.

THEORY:

❖ Character functions:

Function Description Example

INITCAP(s) Returns the string s with the first character of INITCAP('hello SIR') ='Hello
Sir'
each word in uppercase and all others lowercas

LENGTH(s) Returns the number of characters in the string. LENGTH('Welco


me Sir') =11

LOWER(s) Returns the string s with all characters in lowe LOWER('Welcome Sir') ='welco
sir'
case.

LTRIM(s,s1) Returns s without any leading character that LTRIM('welcome', 'slow') =


appear in s1. If no s1 character are trailing leading
characters in s, then s is returned unchanged. ‘elcome'

RTRIM(s,s1) Returns s without any trailing character that RTRIM('Mississippi', 'pi') =

appear in s1. If no s1 character are trailing trailing


characters in s, then s is returned unchanged. 'Mississ'

REPLACE Returns s with all occurrences of substring REPLACE('www.yahoo.


(s,s1[,s2]) com',
s1 replaced with s2. By default s2 is NULL and
'yahoo', 'google')
all occurrences of s1 are removed.
='www.google.com'

SUBSTR Returns the portion of the string s that is len SUBSTR('welcome', 4)


(s,pos[,len]) ='come'
characters long, beginning at position pos.if
SUBSTR('welcome',2,2) ='el'
pos is negative, the position is counted SUBSTR('welcome',-
backwards from the end of the string. The 3,2) ='om'

function returns NULL if len is less or equal to


zero. If len is skipped, it returns the remaining
of s.
TRANSLAT Returns the string s with all occurrences of
E(s,s1,s2) TRANSLATE('alfabet',
characters in s1 replaced with the positionally
'abscde', 'BCDE') =
corresponding characters is s2.If s2 isshorter 'BlfBCt'
than s1, the unmatched characters in s1 are
removed.

TRIM([LEA This function returns the string s with all s1


DING|TRA TRIM(BOTH'.' FROM'etc...')
(leading, trailing, or both (by default it's BOTH)
ILING| = 'etc '
) occurrences of characters in s removed.
BOTH[s1
The default value of s1 is a character.
FROM]]s)

UPPER(s) Returns the string s with all character in UPPER('Welcome Sir') =


'WELCOME SIR'
uppercase.

VSIZE(s) Returns the number of bytes in the internal VSIZE('SCT on the net') =14

representation of an s.

LPAD(s,n[,s1 Returns s, left-padded to length n with LPAD('Page 1',10,’*’) =****Page


])
sequence of characters specified in s1. is 1
if s1 not specified Oracle uses blanks by
default.

RPAD(s,n[,s Returns s, right-padded to length n with RPAD('Page 1',10,’*’) =Page is


1])
sequence of characters specified in s1. If 1****
s1not specified Oracle uses blanks by default.

INSTR(<str Returns the location of a substring in a


ing1,string INSTR(‘SCT on the net’,’t’) =8
String. String2 is the substring to search for in
2, INSTR(‘SCT on the net’,’t’,1,2) th
[<startposit
string1. The default start position is 1. If the
= 14
ion>],[nth start position is negative, the function
appearance]) counts back start position number characters
from the end of string1 and then searches
towards the beginning of string1. nth
appearance is the nth appearance string2
and default is 1.

CONCAT String2 is concated to string1. CONCAT(‘Nirma’, ’Univers


ity’) = ‘Nirma University’
(<string1>,
<string2>)
EXCERCISE:

1) Print your name with intcap(s) function

2) print length of your name


3) print your collage name with lower case character

4) replace all ‘A’ wit ‘z’ in your name

5) Print the first four character of ‘Ahmedabad’ and 4 character from the last

6) trim comp from ’computer’

7) print ‘AIT’ with 5 leftpad ‘*’

8) join ‘computer’ and ‘information technology’

9) print your name and college name uppercase

EVALUATION:

Involvement (4) Understanding Timely Total(10)


/problem solving (3) Completion(3)

Signature with date:


EXPERIMENT NO: 5 DATE: / /

TITLE: Study of number and date functions for manipulation of data items.

OBJECTIVES:know the concept of number function


know the concept of date function.
THEORY:

❖ Number functions:
Number functions are described as follow:

Function Description Example


AVG Returns Average of all Row Values for AVG ([DISTINCT | ALL ]
particular Column column_name) ;
SELECT AVG(BALANCE)
FROM ACCOUNT_MASTER;
MIN Returns minimum value of expression MIN ([DISTINCT | ALL]
column_name) ;
SELECT MIN(BALANCE)
FROM ACCOUNT;
MAX Returns maximum value of expression MAX ([ DISTINCT | ALL ]
column_name);
SELECT MAX(BALANCE)
FROM ACCOUNT_MASTER ;
COUNT COUNT Function Returns Number of Rows COUNT ( [ DISTINCT | ALL ]
Present in Particular Column column_name) ;
Count(*) returns the number of rows in the SELECT
table including duplicates and those with COUNT(ACCOUNT_NO)
nulls.
FROM ACCOUNT_MASTER;
SUM Returns sum of Values for particular Column SUM( [ DISTINCT | ALL ]
column_name);
SELECT SUM(BALANCE)
FROM ACCOUNT_MASTER;
GREATEST Used to Find out the Greatest Valued from GREATEST (exp1,exp2,.,expn);
the Expression. Select Greatest(21,10,30)From
dual;=30

LEAST Used to Find out Lowest Value from the LEAST (exp1,exp2,.,expn);
Expression Select Least(35,75,25) From
dual;=25
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 e^d 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 (d^p). POWER(2,5)= 32
Returns d rounded to i digits of precision to
the right of the decimal point. If i is negative, ROUND(2.6586,2) = 2.66
ROUND(d, i) d is rounded to the left of the ROUND(289.6586,-2)= 300
decimal point.
SIGN(-25) = -1
SIGN(d) Returns -1 if d is negative, 1 if d is positive,
and 0 if d is zero. SIGN(0) = 0
SIGN(25) = 1
SQRT(d) Returns the square root of d. SQRT(81) = 9
❖ 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) = 07-dec-2021
by truncating the decimal portion (it
may also be negative).

MONTHS_BETWEEN(
Returns the number of months that '01-JAN-

MONTHS_BETWEEN(dt1,
dt1 is later than dt2. 2009',SYSDATE) = 4
dt2) Months_Between('02-feb-08','
02-jan-08') "Month" from
dual;=1

Returns the date that corresponds to


the next day of week specified by the
string s following the date dt. The time
NEXT_DAY(SYSDATE
portion of the date is the same as the
NEXT_DAY(dt, s)
time portion of dt. The string s should , 'Mon') = 11-oct-2021
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- 'HH24') = 13-08-2008
ROUND(dt[, fmt])
format string fmt. See date format
codes.
Returns the current date/time, takes SYSDATE = 13-08-
SYSDATE
no arguments. 2008
❖ 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

TO_CHAR(x[, format string specifying the format that x will appear in, and nls specifies
fmt[, nls]]) 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.

TO_CHAR( SYSDATE,'fmdd MONTH YEAR') from TABLE_NAME;


Converts string s to DATE datatype accordingly the format string fmt. The
TO_DATE(s[,
fmt string uses the same date format code. The default is the value stored in
fmt[, nls]])
the NLS_DATE_FORMAT session variable.

ELEMENT OF DATE FORMAT

EXCERCISE:

1) Calculate average of all salary from employee table


2) print name of employee from employee table whose whose has least salary
3) print student enrollment no. who scored highest marks in stud_detail
4) print count of total employee entries
5) print count of total student entries in stud_detail
6) what is the total sum of marks of student from stud_detail
7) print greatest and smallest number from 130, 135,137,255,251,129,254,753
8) select name of employee ,hiredate from employee table and convert hiredate in format
of (07 september 1993)
9) print employee number ,hiredate and review date (2 month after hiredate )from
employee table order by employee number in decreasing order
10) print your system date in format of name of day, month and year(monday 11 october
twenty twenty one)
11) create a table salary with output

name salary

ashish 23000.562

roma 43250.466

kamal 21111.111

divya 32151.110

a) print salary of each candidate round of two digit in ascending order of salary
b) print name ,round value of salary and pf (square root of sal upto 2 decimal) from
salary table in decreasing order of salary

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 other table e.g. deptno in EMP table as well as
in DEPT table. Here relationship is obtained using “=” operator.

SYNTAX: SELECT column_list FROM table1, table2 WHERE


table1.column_name =table2.column_name;

❖ 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

SYNTAX: SELECT * FROM table_name1, table_name2 WHERE


table_name1.column [> | < | >= | <= ] table_name2.column;

❖ 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.
SYNTAX: SELECT*FROM <TABLE NAME> INNER JOIN <TABLE
NAME 2> USING (join_predicate);
SELECT * FROM T1 INNER JOIN T2 ON join_predicate;
EXAMPLE: SELECT *FROM orders INNER JOIN order_items USING
(order_id )
SELECT * FROM orders INNER JOIN order_items ON
order_items.order_id = orders.order_id

❖ 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.
SYNTAX: SELECT * FROM table1 CROSS JOIN table2;
EXAMPLE:
SELECTfoods.item_name,foods.item_unit,company.company_name,compa
n y.company_city FROM foods CROSS JOIN company;

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. Create Salesman Table

salesman_id | name | city | commission(%)


-------------+------------+----------+------------
5001 | James Hoog | New York | 15
5002 | Nail Knite | Paris | 13
5005 | Pit Alex | London | 11
5006 | Mc Lyon | Paris | 14
5007 | Paul Adam | Rome | 12
2. Create Customer Table

customer_id |cust_name| city | grade | salesman_id


------------+---------+----------+-------+------------
3002 | Nick Rimando | New York | 100 | 5001
3007 | Brad Davis | New York | 200 | 5001
3005 | Graham Zusi | California | 200 | 5002
3008 | Julian Green | London | 300 | 5002
3004 | Fabian Johnson | Paris | 300 | 5006

3. Create Order Table


ord_no purch_amt ord_date customer_id salesman_id

70001 150.5 05-oct-2012 3005 5002


70009 270.65 10-sep-2012 3001 5005
70002 65.26 05-oct-2012 3002 5001
70004 110.5 17-aug-2012 3009 5003
70007 948.5 10-sep-2012 3005 5002

4. Write a SQL query to print the name of salesperson and customer who
belongs to same city.
5. Print order id,customer name where purchase amount exists between
500 and 1000.
6. print customer name ,salesman name,city ,commision using inner join
the salesperson(s) and the customer(s) he handle.
7. Write a SQL query to find those customers name who received a
commission from the company more than 13%.
8. Write a SQL query to find the details of an order like order number,
order date, amount of order, customer and salesman name
9. Write a SQL query to combine each row of salesman table with each
row of customer table.
10. Write a SQL statement to make a list in ascending order for the
salesmen who works either for one or more customer or not yet join
under any of the customers.

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:
❖ ORDERBY
The ORDER BY keyword sorts the records in ascending order by default. To
sort the records in descending order, use the DESC keyword.
SYNTAX: SELECT column1, column2, ...FROM table_name ORDER BY
column1, column2, ... ASC|DESC;

❖ GROUP BY

The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one
or more columns.

SYNTAX:SELECT column_name(s)FROM table_name WHERE condition

GROUP BY column_name(s) ORDER BY column_name(s);

❖ HAVING BY

The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.

SYNTAX:SELECT column_name(s)FROM table_name


WHERE condition GROUP BY column_name(s)HAVING condition
ORDER BY column_name(s);
EXAMPLE:SELECT COUNT (CustomerID), Country FROM Customers
GROUP BY Country HAVING COUNT(CustomerID) > 5;

The format of the sub query is:


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) Create table emp


emp_id emp_name job_name manager_id hire_date salary comm dep_id

68319 KAYLING MANAGER 68319 1 may 1991 60000 2000 3001

66928 BLAZE MANAGER 68319 20 aug 1991 56000 1500 1001


67832 CLARE MANAGER 68319 23mar 2001 61000 2000 2001
65646 ADELYN SALESMAN 66928 17 jan 2001 45000 400 3001

67858 TUCKER SALESMAN 66928 09 may 1995 45320 1400 1001


69062 JULIUS SALESMAN 66928 10 apr 1996 42500 1300 2001
69324 MARKER CLERK 67832 12 aug 1995 32000 500 2001

69000 SCARLET CLERK 66928 12 sep 1996 23500 600 1001


2) Find the employees who earn the maximum salary for their
department. Display the result in ascending order of salary.
3) Find the most recently hired employees in each department. Order by
hire date.
4) Show the all details for any employee who earns a salary less than the
average for their department.
5) Who are the top three earners in the company? Display their name and
salary.

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:
1. Simple Index
2. Composite Index
3. 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;
EXPERIMENT NO: 10 DATE: / /

TITLE: Understanding of normalization database.

THEORY:

Normalization: Normalization is a database design technique that reduces data


redundancy and eliminates undesirable characteristics like Insertion, Update and Deletion
Anomalies. Normalization rules divides larger tables into smaller tables and links them
using relationships. The purpose of Normalisation in SQL is to eliminate redundant
(repetitive) data and ensure data is stored logically.

list of Normal Forms in SQL:

● 1NF (First Normal Form)


● 2NF (Second Normal Form)
● 3NF (Third Normal Form)
● BCNF (Boyce-Codd Normal Form)

Database table:

1NF (First Normal Form) Rules

● Each table cell should contain a single value.


● Each record needs to be unique.

1NF Example
2NF (Second Normal Form) Rules

● Rule 1- Be in 1NF
● Rule 2- Single Column Primary Key that does not functionally dependant on any
subset of candidate key relation

It is clear that we can’t move forward to make our simple database in 2 nd Normalization
form unless we partition the table above.

We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
member information. Table 2 contains information on movies rented.

We have introduced a new column called Membership_id which is the primary key for
table 1. Records can be uniquely identified in Table 1 using membership id.

Database – Foreign Key


In Table 2, Membership_ID is the Foreign Key

Foreign Key references the primary key of another Table! It helps connect your Tables

● A foreign key can have a different name from its primary key
● It ensures rows in one table have corresponding rows in another
● Unlike the Primary key, they do not have to be unique. Most often they aren’t
● Foreign keys can be null even though primary keys can not

Why do you need a foreign key?


Suppose, a novice inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the unique key in
the parent table. This helps in referential integrity.

The above problem can be overcome by declaring membership id from Table2 as foreign
key of membership id from Table1

Now, if somebody tries to insert a value in the membership id field that does not exist in
the parent table, an error will be shown!

What are transitive functional dependencies?


A transitive functional dependency is when changing a non-key column, might cause any
of the other non-key columns to change

Consider the table 1. Changing the non-key column Full Name may change Salutation.

Let’s move into 3NF


3NF (Third Normal Form) Rules

● Rule 1- Be in 2NF
● Rule 2- Has no transitive functional dependencies

To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example
Below is a 3NF example in SQL database:

We have again divided our tables and created a new table which stores Salutations.

There are no transitive functional dependencies, and hence our table is in 3NF

In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to


primary key in Table 3

Now our little example is at a level that cannot further be decomposed to attain higher
normal form types of normalization in DBMS. In fact, it is already in higher normalization
forms. Separate efforts for moving into next levels of normalizing data are normally needed
in complex databases. However, we will be discussing next levels of normalisation in
DBMS in brief in the following.
BCNF (Boyce-Codd Normal Form)

Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it
has more than one Candidate Key.Sometimes is BCNF is also referred as 3.5 Normal
Form.

You might also like