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

DBMS Lab Manual

The document describes an experiment on applying data definition language (DDL) to relational models. The aims are to design relational models with constraints, apply DDL commands to developed models, and list the needs for business logic/constraints in databases. Key concepts covered include SQL, relational databases, tables with columns and rows to store data, and using DDL to define and manage database objects.

Uploaded by

Samrudhi Patil
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)
208 views

DBMS Lab Manual

The document describes an experiment on applying data definition language (DDL) to relational models. The aims are to design relational models with constraints, apply DDL commands to developed models, and list the needs for business logic/constraints in databases. Key concepts covered include SQL, relational databases, tables with columns and rows to store data, and using DDL to define and manage database objects.

Uploaded by

Samrudhi Patil
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/ 74

Experiment No.

01
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: Explore various fundamental concepts of DBMS and its future prospective.

A.2 Prerequisite: -

A.3 Outcome:
After successful completion of this experiment students will be able to

1. Explain fundamental terminologies of DBMS.


2. Enlist basic components of DBMS.
3. Describe the need of DBMS in software development.
4. Differentiate among various database packages and its usage in real life for solving the
problems.
5. Enlist the real life applications of DBMS.
6. Correlate the usage of DBMS for prospective areas such as Data science.

A.4 Theory:
To define the database system, the following terminologies must be clarified:

1. File
2. Database
3. Database Management System (DBMS)

File consists of only one file or table, with each entry containing all the required data defined
within it. It is like a cabinet containing only one folder which has many pages in it, each page
containing all the information for that specific entry. This makes it easy for the user to know where
to find requested entries and all the data associated with them. As entire data are at one place,
retrieval of data is easy and fast. But the flat file suffers from the problem of data redundancy.
Suppose there is an order processing application which includes the name, address, and phone
number of a customer. If this customer has placed order for two items then there could be two
entries for this customer with his name, address and phone number. In other words, the file contains
redundant data, i.e. twice the name, address, and the phone number of the customer. If his address
is to be changed then it is to be changed at two places.
Database is a collection of interrelated files, while database management system is a collection of
database, database utilities (DBMS software) operated by user groups and administered by
database administrator.

Database is a collection of interrelated files. The conventional file processing system will lead to
excessive data redundancy and associated difficulties. But, in a database system which has an
integrated single database, all the problems of the conventional file processing system will be
minimized, even though the time taken to design and implement a robust database will be relatively
longer when compared to the design of files in the conventional file processing system. There will
be greater payoff by using the robust database which will offset the cost towards longer duration
of designing and implementing the database.

A database is a collection of interrelated data stored together with controlled redundancy to serve
one or more applications in an optimal way. The data are stored in such a way that they are
independent of the programs used by the people for accessing the data. The approach used in
adding the new data, modifying and retrieving the existing data from the database is common and
controlled one.

It is also defined as a collection of logically related data stored together that is designed to meet
information requirements of an organization. We can also define it as an electronic filing system.

A database management system is a software package that controls all access to database. When a
request to access database comes, it examines the request interprets it using some commands.
There are many different types of database users, out of which database administrator is
responsible for managing overall system and all other users of the system.

The DBMS performs the following five primary functions:

1. Define, create and organize a database: The DBMS establishes the logical relationships
among different data elements in a database.
2. Input data: It performs the function of entering the data into the database through an input
device with the help of the user.
3. Process data: It performs of manipulation and processing of the data stored in the database.
4. Maintain data integrity and security: It allows limited access of the database to authorized
users to maintain data integrity and security.
5. Query database: It provides information to the decision makers that they need to make
important decisions. The information is provided by querying the database using SQL.

Database system environment:


Application programs (software)

User

Database (Hardware)

User
Data
Data

Data User

DBMS Users:
The users of a database system are:

1. End users or Naïve Users


2. Online users
3. Application programmers
4. Database administrator

Role of Database Administrator:


1. Deciding contents of database
2. Deciding structure of internal storage of database
3. Deciding users
4. Granting authorities
5. Deciding rules and constraints
6. Managing security for database
7. Monitoring the performance of the database
8. Taking backup
9. Removal of dump and maintain free space

A.5 Task to be completed in PART B


A.5.1. Task 1: Answer following
1. Define and exemplify following terms:

Data, Information, Tuple, Attributes, Entity, Record, File, Relation,

Database, Front end, Back end, Query, Schema, Entity Relationship.

2. Enlist the components of typical Database Management System (DBMS). Depict it


diagrammatically. Comment on their Responsibilities.

3. Enlist Advantages and disadvantage of database management system.

4. Discuss applications of DBMS.

5. What are various possible user roles available in the area of Databases? and what are
their responsibilities?

PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Blackboard or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black board access
available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Tasks given in PART A to be completed here


(Students must write the answers of the task(s) given in the PART A )

B.2 Observations and Learning:


(Students must write the observations and learning based on their understanding built about the subject matter
and inferences drawn)
B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)

B.4 Question of curiosity:


1. Compare following database packages:

MS Access, MySQL, PL/SQL, ORACLE, DB2, ADABAS, SYBASE

2. Justify the correctness of following statements: “The knowledge of DBMS is essential for
becoming the Data scientist ”

***************
Experiment No.02
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: Apply Data Definition language [DDL] on the relational model designed and apply
certain constrains on the relational model designed.

A.2 Prerequisite: - Fundamental knowledge of DDL instructions and the SQL

A.3 Outcome:
After successful completion of this experiment students will be able to

1. Design the relational model with basic constrains.


2. Apply the DDL commands on the developed relational models.
3. Enlist the needs of Business logic /constrains in Databases.

A.4 Theory:
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server,
Access, Ingres, etc. Although most database systems use SQL, most of them also have their own
additional proprietary extensions that are usually only used on their system. However, the standard
SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used
to accomplish almost everything that one needs to do with a database.

A relational database system contains one or more objects called tables. The data or information
for the database are stored in these tables. Tables are uniquely identified by their names and are
comprised of columns and rows. Columns contain the column name, data type, and any other
attributes for the column. Rows contain the records or data for the columns. Here is a sample table
called "weather". City, state, high, and low are the columns. The rows contain the data for this
table:

Weather
city state high low
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
New
Albuquerque 80 72
Mexico
The create table statement is used to create a new table. Here is the format of a simple create
tablestatement:

create table "tablename"("column1" "data type", "column2" "data type", "column3"


"data type");

To create a new table, enter the keywords create table followed by the table name, followed by
an open parenthesis, followed by the first column name, followed by the data type for that column,
followed by any optional constraints, and followed by a closing parenthesis. It is important to make
sure you use an open parenthesis before the beginning table, and a closing parenthesis after the
end of the last column definition. Make sure you seperate each column definition with a comma.
All SQL statements should end with a ";".

The table and column names must start with a letter and can be followed by letters, numbers, or
underscores - not to exceed a total of 30 characters in length. Do not use any SQL reserved
keywords as names for tables or column names (such as "select", "create", "insert", etc).

Data types specify what the type of data can be for that particular column. If a column called
"Last_Name", is to be used to hold names, then that particular column should have a "varchar"
(variable-length character) data type.

Here are the most common Data types:

char(size) Fixed-length character string. Size is specified in parenthesis. Max 255 bytes.

varchar(size) Variable-length character string. Max size is specified in parenthesis.

number(size) Number value with a max number of column digits specified in parenthesis.

date Date value

Number value with a maximum number of digits of "size" total, with a maximum
number(size,d)
number of "d" digits to the right of the decimal.

Constraints:
What are constraints? When tables are created, it is common for one or more columns to
have constraints associated with them. A constraint is basically a rule associated with a column
that the data entered into that column must follow. For example, a "unique" constraint specifies
that no two records can have the same value in a particular column. They must all be unique. The
other two most popular constraints are "not null" which specifies that a column can't be left blank,
and "primary key". A "primary key" constraint defines a unique identification of each record (or
row) in a table.

Format of create table if you were to use optional constraints:

create table "tablename" ("column1" "data type" [constraint],

"column2" "data type" [constraint],

"column3" "data type" [constraint]);

1. Primary key constraint:

The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys
must contain UNIQUE values. A primary key column cannot contain NULL values. Most tables
should have a primary key, and each table can have only ONE primary key.

create table Accounts(acc_no number(5) primary key, balance number(8,2));

or

create table Accounts(acc_no number(5), balance number(8,2), primary key(acc_no));

or adding primary key constraint using alter command – can be used only if table has been
already created and during creation time constraint was not given.

alter table Accounts add primary key(acc_no);

2. Unique constraint:

The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

create table person(p_id number(4) primary key, pname varchar(40),mobile_no number(10)


unique, address varchar(100));

Or
create table person(p_id number(4) primary key, pname varchar(40), mobile_no number(10),
address varchar(100), unique(mobile_no));

or adding unique key using alter command – can be used only if table is already created and at the
time of creation of table constraint was not applied.

alter table person add unique(mobile_no);

3. NOT NULL constraint:

The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL
constraint enforces a field to always contain a value. This means that you cannot insert a new
record, or update a record without adding a value to this field.

create table person(p_id primary key, pname varchar(4) not null, mobile_no number(10), address
varchar(100));

4. Foreign key:

A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the
foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3
3 22456 2

4 24562 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The
"P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN
KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN
KEY constraint also prevents invalid data from being inserted into the foreign key column, because
it has to be one of the values contained in the table it points to.

create table orders(o_id number(3) primary key, orderno number not null, p_id foreign key
references persons(p_id));

Adding foreign key with alter table command: Applicable only if table is already created and
at the time of creation foreign key was not given.

alter table orders add foreign key(p_id) references persons(p_id);

Drop Table Command:


It is used to completely delete table along with all its rows from the memory.

Syntax:

drop table table name;

drop table orders;

A.5 Task: Create below tables along with constraints:


Create following tables:

1. category_header : cat_code number(5), cat_desc varchar(20), cat_code will be primary


key

2. route_header: route_id number(5), route_no number(5), cat_code number(5), origin


varchar(20), destination varchar(20), fare number(7,2), distance number(3), capacity
number(3) , cat_code will be foreign key, route_id will be primary key
3. place_header: place_id number(5), place_name varchar(20), place_address varchar(50),
bus_station varchar(10), place_id will be primary key, place_name not null

4. fleet_header: fleet_id number(5), day date, route_id number(5), cat_code number(5),


fleet_id primary key, route_id foreign key, cat_code foreign key

5. ticket_header: fleet_id number(5), ticket_no number(5), doi date, dot date, time_travel
char(8), board_place varchar(20), origin varchar(40), destination varchar(40), adult
number(3), children number(3), total_fare number(7,2), route_id number(5)

fleet_id foreign key, ticket_no primary key, doi- not null, dot-not null, route_id – foreign
key

6. ticket_detail: ticket_no number(5), name varchar(20), sex char(1), age number(3), fare
number(5,2)

7. route_detail: route_id number(5), place_id number(5), nonstop char(1)

Solve below queries after creating tables:

1. Write a query to increase size of category description column in category header table
from varchar(20) to varchar(50).

2. Create a table Student_MPSTME with columns student number, student name, student
address, student phone number with appropriate data types.

3. Write a query to add primary key column to above created Student_MPSTME table.

4. Write a query to create new table Student_NMIMS with columns Student number,
Student name selected from table Student_MPSTME.

5. Write a query to rename Student_MPSTME table to Stu_MPSTME.

6. Write a query to add birth date column to stu_MPSTME table.

7. Write a query to delete column student phone number from Stu_MPSTME table.

8. Write a query to delete Stu_MPSTME table.


PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )

B.1.1 : Execution of each SQL query used to complete the task given in PART A :

B.1.2 : Screenshots of the tables designed with constrains:

B.2 Observations and Learning:


(Students must write the observations and learning based on their understanding built about the subject matter
and inferences drawn)

B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)

B.4 Question of curiosity:


3. Comment the statement, “Primary key is no different than Foreign key”
4. Differentiate between Business logic and constrains in Databases.
5. Which other SQL DDL Commands can be applied on the tables generated?

***************
Experiment No.03
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: Apply Data Manipulation language [DML] on the relational model designed and
apply certain constrains on the relational model designed.

A.2 Prerequisite: - Fundamental knowledge of DML instructions and the SQL

A.3 Outcome:
After successful completion of this experiment students will be able to

4. Design the relational model with basic constrains.


5. Apply the DML commands on the developed relational models.
6. Differentiate between DDL and DML and its importance in handling databases.

A.4 Theory:
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanent
to database, it can be rolled back. DML is short name of Data Manipulation Language which deals
with data manipulation, and includes most common SQL statements such as SELECT, INSERT,
UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete and update data in database.

1. SELECT: retrieve data from the database.


2. INSERT: insert into a table
3. UPDATE: updates existing data within a table
4. DELETE: delete all records from a database table without deleting the structure of the database.

1. SELECT:

Syntax:

select column_name(s) from table_name;  selects only particular column(s) and all
rows

Or
Select * from table_name  selects all columns and all rows of the table mentioned

2. INSERT:

Syntax:

insert into table_name (column1, column2, column3,….columnn) values(value1, value2,


value3,…..valuen)  used when you want to insert into particular columns not all
columns of the table.

Or

insert into table_name values(value1, value2, value3, ….. valuen)  used when you
want to insert values into all columns of the table.

3. UPDATE:

Syntax:

Update table_name set column= value;  used when you want to update all the rows
for the particular column.

Or

update table_name set column = value, column1=value where


somecolumnname=somevalue;  used when you want to update particular row(s)

4. DELETE:

Syntax:

delete from table_name; - used when you want to delete all the rows of the table.

Or

delete from table_name where somecolumn=somevalue; - used when you want to


delete only particular row(s) from the table.

A.5 Task: insert below values into table and apply queries
category_header

route_header

Place Header:

Fleet Header:
Ticket Header:

Ticket Detail:

Route Detail:

Queries:
a. Display all records of Category Header table.
b. Display place name and place address.
c. Check what will be the fare if it is incremented by 10 rs for each route. (Give new
column alias as new_fare).
d. Display distinct destination from route header table. [Hint : Use ‘distinct’ keyword]
e. Display structure of table route detail. [Hint; Use ‘desc’]
f. Gautam’s fare got increased by 1 unit. Make changes in the appropriate table.
g. Write a query to change age of ‘Anand’ from 28 to 30.
h. Write a query to insert a new record into Route_Detail table with details as below:
a. Route_id: 105 , Place_id : 01, NonStop: S
i. Write a query to delete row inserted above from Route_Detail table.
PART B
PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Student Portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black board access
available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )

B.1.1 : Execution of each SQL query used to complete the task given in PART A :

B.1.2 : Screenshots of the tables designed with inserted records.

B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation noted in section B.3)

B.3 Curiosity Questions:


6. Differentiate between ‘ALTER’ and ‘UPDATE’ SQL Commands in used for Databases.
7. Which other SQL DML Commands can be applied on the tables generated?
Experiment No.04
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: To design Entity Relationship and relational model for the given case study.

A.2 Prerequisite: - Basic concepts of database, data models like ER-models and relational
model.

A.3 Outcome:
After successful completion of this experiment, students will be able to

7. Explain the basics of ER/EER Diagram and its importance in database design.
8. Design ER diagram for the case study given.
9. Convert the ER diagram into equivalent relational model.
10. Enlist the difference between ER and Relational model.

A.4 Theory:
Summary of symbols used in ER notation:
Reduction of ER model to relational model:
Rules:

 Build a table for each entity set

 Build a table for each relationship set if necessary (depending upon cardinality)

 Make a column in the table for each attribute in the entity set

 Weak Entity Set Cannot exists alone

 To build a table/schema for weak entity set

 Construct a table with one column for each attribute in the weak entity set

 Remember to include discriminator

 Augment one extra column on the right side of the table, put in there the
primary key of the Strong Entity Set (the entity set that the weak entity set is
depending on)
 Primary Key of the weak entity set = Discriminator + foreign key

 Representation of relationship set:

 For one-to-one relationship w/out total participation

 Build a table with two columns, one column for each participating entity set’s
primary key. Add successive columns, one for each descriptive attributes of
the relationship set (if any).

 For one-to-one relationship with one entity set having total participation

 Augment one extra column on the right side of the table of the entity set with
total participation, put in there the primary key of the entity set without
complete participation as per to the relationship.

 For one-to-many relationship w/out total participation

 Same thing as one-to-one

 For one-to-many/many-to-one relationship with one entity set having total


participation on “many” side

 Augment one extra column on the right side of the table of the entity set on
the “many” side, put in there the primary key of the entity set on the “one”
side as per to the relationship.

 For many-to-many relationship

 Same thing as one-to-one relationship without total participation.

 Primary key of this new schema is the union of the foreign keys of both entity
sets.

 No augmentation approach possible

 Representing composite attribute:

 One column for each component attribute

 NO column for the composite attribute itself

 Representing multi-valued attribute:

 For each multivalue attribute in an entity set/relationship set

 Build a new relation schema with two columns


 One column for the primary keys of the entity set/relationship set that has
the multivalue attribute

 Representing Generalization\Specialization:

 Two general approaches depending on disjointness and completeness

 For non-disjoint and/or non-complete class hierarchy:

 create a table for each super class entity set according to normal
entity set translation method.

 Create a table for each subclass entity set with a column for each of
the attributes of that entity set plus one for each attributes of the
primary key of the super class entity set

 This primary key from super class entity set is also used as the
primary key for this new table

 For disjoint AND complete mapping class hierarchy:

 DO NOT create a table for the super class entity set

 Create a table for each subclass entity set include all attributes of that
subclass entity set and attributes of the superclass entity set

A.5 Task to be completed in PART B:

A.5.1 Task1
Draw an ER diagram for given case study and convert it into relational model:

We need to create a database schema design based on the following (simplified) requirements of
the COMPANY Database:

1. The company is organized into DEPARTMENTs. Each department has a name, number
and an employee who manages the department. We keep track of the start date of the
department manager. A department may have several locations.

2. Each department controls a number of PROJECTs. Each project has a unique name, unique
number and is located at a single location.

3. There are two types of employees in company- technical employee and non-technical
employee (administrative staff).

4. We store each EMPLOYEE’s Aadhar number, address, salary, sex, and birthdate.
5. Each technical employee works for one department but may work on several projects.

6. We keep track of the number of hours per week that a technical employee currently works
on each project.

7. The technical employee gains score based on work done. The latest score of each technical
employee is stored.

8. The non-technical employees are given incentives based on their work.

9. We also keep track of the direct supervisor of each employee.

10. Each employee may have a number of DEPENDENTs.

11. For each dependent, we keep track of their name, sex, birthdate, and relationship to the
employee.

******************
PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black student portal
access available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :
B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )

B.1.1 : Draw the ER diagram here

B.1.2 : Conversion of ER model into Relational Model:

B.1.3 : Schema Diagram

B.2 Observations and Learning:


(Students must write the observations and learning based on their understanding built about the subject matter
and inferences drawn)

Write your observation related to difference between ER model and Relational Model.

B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)

B.4 Question of curiosity:


(Students must provide reference list of the sources from where the answers of these questions are found, in case
referred any specific book or website.)

8. Justify the statement, “The MISTAKES made in ER diagram badly affects the complete
database design”
9. Design ER diagram for library management system considering following entities and its
interrelationships: Books, Students, Book_Issued, Books_returned

***************
Experiment No.05
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: Apply DML select statement with where clause, and, or, not, in, between and like
clauses.

A.2 Prerequisite: - Fundamental knowledge of DML instructions and the SQL

A.3 Outcome:
After successful completion of this experiment students will be able to

11. Design the relational model with basic constrains.


12. Apply the DML commands on the developed relational models.
13. Differentiate between various clauses used with DML commands.

A.4 Theory:

The select statement is used to view records from the database. In order to view only specific
records, select statement is used with where clause. The SQL WHERE clause is used to specify
a condition while fetching the data from single table or joining with multiple tables. If the given
condition is satisfied then only it returns specific value from the table. You would use WHERE
clause to filter the records and fetching only necessary records.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc.,

SQL syntax for Select statement with where clause:

SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

Example:

select * from customers where country=’CHINA’;


The above query will select customers from the country CHINA.

The SQL requires single quotes around text values (as shown in above example). However
numeric fields should not be enclosed in quotes.

Example:

select * from customers where customer_id=1;


The following operators can be used in the WHERE clause:

Operator Description

= Equal

<> Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

Between Between an inclusive range

Like Search for a pattern

IN To specify multiple possible values for a column

AND To combine two conditions – both condition needs to be true

OR To combine two conditions- either of the two condition has to be true

Using > operator with where clause:

Example:

select employee_id, name from employee where salary>50000;

Using = operator with where clause:

select employee_id, name,salary from employee where name = ‘Hardik’;


SQL AND- OR operator:

The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.

The basic syntax of AND operator with WHERE clause is as follows:

SELECT column1, column2, columnN

FROM table_name

WHERE [condition1] AND [condition2]...AND [conditionN];

You can combine N number of conditions using AND operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, all conditions separated by the AND must be
TRUE.

Example:

select employee_id, name, salary from employee where salary >2000 and age <25;

The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

The basic syntax of OR operator with WHERE clause is as follows:

SELECT column1, column2, columnN

FROM table_name

WHERE [condition1] OR [condition2]...OR [conditionN]

You can combine N number of conditions using OR operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, only any ONE of the conditions separated by
the OR must be TRUE.

Example:

select employee_id, name, salary from employee where salary>2000 or age<25;

The IN operator:
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Example:

The following SQL statement selects all customers with a City of "Paris" or "London":

select * from customers where city in (‘Paris’,’London’);

SQL Between operator:

The BETWEEN operator is used to select values within a range. The values can be number, text
or dates.

SQL BETWEEN syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Example:

The following SQL statement selects all products with a price BETWEEN 10 and 20:

select * from products where price between 10 and 20;

To display the products outside the range of the previous example, use NOT BETWEEN:

select * from products where price not between 10 and 20;

SQL LIKE operator:

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

SQL LIKE syntax:


SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

SQL Wildcard characters:

In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to
search for data within a table.

With SQL, the wildcards are:

Wildcard Description

% A substitute for zero or more characters

_ A substitute for a single character

[charlist] Sets and ranges of characters to match

[^charlist] Matches only a character NOT specified within the brackets


or
[!charlist]

Using LIKE with SQL Wildcard characters:

The following SQL statement selects all customers with a City starting with "ber":

select * from customers where city like ‘ber%’;

The following SQL statement selects all customers with a City containing the pattern "es":

select * from customers where city like ‘%es%’;

The following SQL statement selects all customers with a City starting with any character,
followed by "erlin":

select * from customers where city like ‘_erlin’;

The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":

select * from customers where city like ‘L_n_on’;


The following SQL statement selects all customers with a City starting with "b", "s", or "p":

select * from customers where city like ‘[bsp]%’;

A.5 Task: For given tables solve below queries:

category_header

route_Header

Place Header:

Fleet Header:
Ticket Header:

Ticket Detail:

Route Detail:

A.5 Tasks to be completed:

Write DML Queries for completing the tasks given below


1. Display only those routes that originate in “madras” and terminate in “cochin”.

2. Display only those rows from route_header whose origin begins with ‘m’.

3. Display only those rows whose fare ranges between 30 and 50.

4. Display the fare and the origin for route_no which are greater than 15.

5. Display all details of places whose name begins with ‘m’.

6. Display those routes whose distance is in range of 200 and 400.

7. Find out fleets which travel through route 102 or 103.

8. Find out routes which are non stop.

9. Find out category whose category description starts with ‘s’ and ends with ‘t’.

10. Find out routes which have category code 1, 2 or 4.

11. Display details of place with bus station “charminar”.

12. Display details of those routes whose fare is less than 70 and distance greater than 120.

13. Find out details of tickets issued to female travelers and with age greater than 10.

14. What will be fare of each route after incrementing fare by 10 percent?

15. Find out details of routes with 101 or 105 or 107.

16. Display those routes for which origin is “Madras” and distance is greater than 300 or
destination is “Madras” and distance less than 300.

17. Create a new table temp_MPSTME with columns as place_id, place_name and
place_address (column data type and size must be same as columns of place_header
table).

18. Write a query to insert records into temp_MPSTME table from place_header table. Only
those records are to be selected for which place_id is between 1 to 4 and place_name starts
from ‘m’.
PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )

B.1.1 : Execution of each SQL query used to complete the task given in PART A :

B.2 Observations and Learning:


(Students must write the observations and learning based on their understanding built about the subject matter
and inferences drawn)

B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)

B.2 Curiosity Questions:


10. Justify the statement, “Various clauses used with DML helps for better manipulation of
the given table”
11. Differentiate between ‘in’ and ‘Between’ operators used for Databases.
12. What is wild card character used in databases?
Experiment No.06
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: To apply order by clause and concept of different types of Joins for solving queries.

A.2 Prerequisite:

DML commands of SQL

A.3 Outcome:
After successful completion of this experiment students will be able to

7. Apply knowledge of relational algebra and structural query language to retrieve and
manage data in relational databases.

A.4 Theory:

Order By Clause:
An ORDER BY clause allows you to specify the order in which rows appear in the result set. The
SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.

Syntax for Order By clause:

ORDER BY { column-Name | ColumnPosition | Expression }


[ ASC | DESC ]
[ NULLS FIRST | NULLS LAST ]
[ , column-Name | ColumnPosition | Expression
[ ASC | DESC ]
[ NULLS FIRST | NULLS LAST ]

Consider Emp table as below:

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7839 KING PRESIDENT - 11/17/1981 5000 - 10


7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7369 SMITH CLERK 7902 12/17/1980 800 - 20
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
7900 JAMES CLERK 7698 12/03/1981 950 - 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
101 A b 7839 04/01/2004 1000 10 20
102 B - - - - - 30

Example:

Sorting above table using order by clause using salary (SAL) column in ascending order.

Query:

select * from emp order by SAL asc;

Result:

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 12/17/1980 800 - 20


7900 JAMES CLERK 7698 12/03/1981 950 - 30
101 A b 7839 04/01/2004 1000 10 20
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7839 KING PRESIDENT - 11/17/1981 5000 - 10
102 B - - - - - 30

Sorting above table using order by clause using salary (SAL) column in ascending order.

Query:
select * from emp order by SAL desc;

Result:

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

102 b - - - - - 30
7839 KING PRESIDENT - 11/17/1981 5000 - 10
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
101 a b 7839 04/01/2004 1000 10 20
7900 JAMES CLERK 7698 12/03/1981 950 - 30
7369 SMITH CLERK 7902 12/17/1980 800 - 20

The table can also be sorted using column number or column position. While sorting we can
specify whether to display null values first or last using “NULL FIRST” or “NULL LAST” clause.

For example in EMP table column position of SALARY column is 6. Using column position table
will be sorted as below:

select * from emp order by 6;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 12/17/1980 800 - 20


7900 JAMES CLERK 7698 12/03/1981 950 - 30
101 a b 7839 04/01/2004 1000 10 20
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7839 KING PRESIDENT - 11/17/1981 5000 - 10
102 b - - - - - 30

Example:

select * from emp order by comm nulls first;

Result:

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7839 KING PRESIDENT - 11/17/1981 5000 - 10


7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
7369 SMITH CLERK 7902 12/17/1980 800 - 20
102 b - - - - - 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
7900 JAMES CLERK 7698 12/03/1981 950 - 30
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
101 a b 7839 04/01/2004 1000 10 20
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30

Joins:
JOINS are used to retrieve data from multiple tables. A JOIN is performed whenever two or more
tables are joined in a SQL statement.
There are 4 different types of Oracle joins:

 Oracle INNER JOIN (or sometimes called simple join)


 Oracle LEFT OUTER JOIN (or sometimes called LEFT JOIN)
 Oracle RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
 Oracle FULL OUTER JOIN (or sometimes called FULL JOIN)

INNER JOIN:


 It is the most common type of join. Oracle INNER JOINS return all rows from multiple
tables where the join condition is met.

Syntax

The syntax for the INNER JOIN in Oracle/PLSQL is:

SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Example:

Consider supplier and Orders table as below:

Supplier:

supplier_id supplier_name

10000 IBM

10001 Hewlett Packard

10002 Microsoft

10003 NVIDIA

Orders:
order_id supplier_id order_date

500125 10000 2003/05/12

500126 10001 2003/05/13

500127 10004 2003/05/14

Applying inner join between supplier and orders table in order to fetch supplier id, supplier
name and order date from both tables supplier and orders.
Syntax:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers INNER JOIN orders


ON suppliers.supplier_id = orders.supplier_id;

Result:

supplier_id Name order_date

10000 IBM 2003/05/12

10001 Hewlett Packard 2003/05/13

Old Syntax: In earlier version of Oracle inner joins were specified as below:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers, orders WHERE


suppliers.supplier_id = orders.supplier_id;

Joining more than one table:

Example: Consider tables as below:


To join n tables together, you need a minimum of n-1 join conditions. For example to join three
tables, a minimum of two joins is required.

In order to join above three tables to fetch employee last name, department in which employee is
working and the city where department is located below query will be used.

select employees.last_name, departments.department_id, locations.city from employees, departments, locations where


employees.department_id=departments.department_id and departments.location_id=locations.location_id;

Left Outer Join:

Another type of join is called an Oracle LEFT OUTER JOIN. This type of join returns all rows
from the LEFT-hand table specified in the ON condition and only those rows from the other table
where the joined fields are equal (join condition is met).

Syntax

The syntax for the Oracle LEFT OUTER JOIN is:

SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column;

Visual Illustration

In this visual diagram, the Oracle LEFT OUTER JOIN returns the shaded area:
The Oracle LEFT OUTER JOIN would return the all records from table1 and only those records
from table2 that intersect withtable1.

Example

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers LEFT OUTER JOIN


orders ON suppliers.supplier_id = orders.supplier_id;

This LEFT OUTER JOIN example would return all rows from the suppliers table and only those
rows from the orders table where the joined fields are equal.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the orders
table will display as <null> in the result set.

Result:

supplier_id supplier_name order_date

10000 IBM 2003/05/12

10001 Hewlett Packard 2003/05/13

10002 Microsoft <null>

10003 NVIDIA <null>

Right Outer Join:


Another type of join is called an Oracle RIGHT OUTER JOIN. This type of join returns all rows
from the RIGHT-hand table specified in the ON condition and only those rows from the other table
where the joined fields are equal (join condition is met).

Syntax

The syntax for the Oracle RIGHT OUTER JOIN is:

SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column;

In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.

Visual Illustration
In this visual diagram, the Oracle RIGHT OUTER JOIN returns the shaded area:

The Oracle RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.

Example

Here is an example of an Oracle RIGHT OUTER JOIN:

SELECT orders.order_id, orders.order_date, suppliers.supplier_name FROM suppliers RIGHT OUTER JOIN


orders ON suppliers.supplier_id = orders.supplier_id;

This RIGHT OUTER JOIN example would return all rows from the orders table and only those
rows from the suppliers table where the joined fields are equal.

If a supplier_id value in the orders table does not exist in the suppliers table, all fields in the
suppliers table will display as <null>in the result set.

Full Outer Join:


Another type of join is called an Oracle FULL OUTER JOIN. This type of join returns all rows
from the LEFT-hand table and RIGHT-hand table with nulls in place where the join condition is
not met.

Syntax

The syntax for the Oracle FULL OUTER JOIN is:

SELECT columns FROM table1 FULL [OUTER] JOIN table2 ON table1.column = table2.column;

In some databases, the FULL OUTER JOIN keywords are replaced with FULL JOIN.

Visual Illustration
In this visual diagram, the Oracle FULL OUTER JOIN returns the shaded area:

The Oracle FULL OUTER JOIN would return the all records from both table1 and table2.

Natural Join:
The natural join clause is based on all columns in the two tables that have the same name. It
selects rows from the two tables that have equal values in all matched columns.

Syntax:

SELECT * FROM table1 NATURAL JOIN table2;

Consider below tables: foods and company


ITEM_ID | ITEM_NAME | ITEM_UNIT | COMPANY_ID |
+---------+--------------+-----------+------------+
| 1 | Chex Mix | Pcs | 16 |
| 6 | Cheez-It | Pcs | 15 |
| 2 | BN Biscuit | Pcs | 15 |
| 3 | Mighty Munch | Pcs | 17 |
| 4 | Pot Rice | Pcs | 15 |
| 5 | Jaffa Cakes | Pcs | 18 |
| 7 | Salt n Shake | Pcs | |
+---------+--------------+-----------+------------+

COMPANY_ID | COMPANY_NAME | COMPANY_CITY |


+------------+---------------+--------------+
| 18 | Order All | Boston |
| 15 | Jack Hill Ltd | London |
| 16 | Akas Foods | Delhi |
| 17 | Foodies. | London |
| 19 | sip-n-Bite. | New York |
+------------+---------------+--------------+

Query:

select * from foods natural join company;

Result:

COMPANY_ID ITEM_ID ITEM_NAME ITEM_UNIT COMPANY_NAME COMPANY_CITY

---------- ---------- ------------------------- ---------- ------------------------- -


-------------

16 1 Chex Mix Pcs Akas Foods Delhi

15 6 Cheez-It Pcs Jack Hill Ltd London

15 2 BN Biscuit Pcs Jack Hill Ltd London

17 3 Mighty Munch Pcs Foodies. London

15 4 Pot Rice Pcs Jack Hill Ltd London

18 5 Jaffa Cakes Pcs Order All Boston

A.5 Task: For given tables solve below queries:

category_header
route_Header

Place Header:

Fleet Header:

Ticket Header:
Ticket Detail:

Route Detail:

Queries:
1. Display all routes sorted using distance (descending order).
2. Display details of those routes for which category description is “Delux”.
3. Find out details of ticket issued to passenger “Charu”.
4. Find out places for which routes are non stop.
5. Display all rows from route header and only matching rows from route detail.
6. Find out common route id’s those are present in route_header and route_detail.
7. Find out names of passengers who travel through routes with origin as ‘Madurai’
and destination as ‘Madras’.
8. Find out fleets which passes through routes which are not non stop.
9. Insert into category_header table new row with below details:
Cat code: 05 cat description: fast
10. Display cat_code, cat_description and all route details for all the categories, whether
route available for category or not.
11. Find out details of those tickets for which origin of one ticket is same as destination
of another ticket.

PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Commands and Output:

B.2 Curiosity Questions:


1. Justify the statement, “Joins are must for better manipulation of the given table”
2. Differentiate between ‘inner join’ and ‘outer join’ operators used for Databases.
3. Solve below queries for given tables:
Distributor (Dno, Dname, Daddress, Dphone)
Item (Itemno, Itemname, Colour, Weight)
Dist_Item(Dno, Itemno, Qty)

a. Find out distributors, who have supplied item number 01.

b. Find out details of item supplied by distributor 01.

B.3 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.07
PART A

(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: To implement group by, having clause, aggregate functions, sub queries, set
operation and views for solving queries.

A.2 Prerequisite:

DML commands of SQL

A.3 Outcome:
After successful completion of this experiment students will be able to

8. Apply knowledge of relational algebra and structural query language to retrieve and
manage data in relational databases.

A.4 Theory:

Aggregate Functions:
Aggregate functions are statistical functions such as count, min, max etc. They are used to compute
a single value from a set of attribute values of a column:

count Counting Rows


Example: How many tuples are stored in the relation EMP?
select count(*) from EMP;
Example: How many different job titles are stored in the relation EMP?
select count(distinct JOB) from EMP;

max Maximum value for a column


min Minimum value for a column
Example: List the minimum and maximum salary.
select min(SAL), max(SAL) from EMP;
Example: Compute the difference between the minimum and maximum salary.
select max(SAL) - min(SAL) from EMP;
sum Computes the sum of values (only applicable to the data type number)
Example: Sum of all salaries of employees working in the department 30.

select sum(SAL) from EMP where DEPTNO = 30;

avg Computes average value for a column (only applicable to the data type number)
Note: avg, min and max ignore tuples that have a null value for the specified attribute, but
count considers null values.

Grouping:

We have seen how aggregate functions can be used to compute a single value for a column. Often
applications require grouping rows that have certain properties and then applying an aggregate
function on one column for each group separately. For this, SQL provides the clause group by
<group column(s)>. This clause appears after the where clause and must refer to columns of tables
listed in the from clause.
Syntax:
select <column(s)> from <table(s)> where <condition> group by <group column(s)> [having
<group condition(s)>];

Those rows retrieved by the selected clause that have the same value(s) for <group column(s)> are
grouped. Aggregations specified in the select clause are then applied to each group separately. It
is important that only those columns that appear in the <group column(s)> clause can be listed
without an aggregate function in the select clause!

Example: For each department, we want to retrieve the minimum and maximum salary.

select DEPTNO, min(SAL), max(SAL) from EMP group by DEPTNO;

Rows from the table EMP are grouped such that all rows in a group have the same department
number. The aggregate functions are then applied to each such group.
We thus get the following query result:
DEPTNO MIN(SAL) MAX(SAL)
10 1300 5000
20 800 3000
30 950 2850

Rows to form a group can be restricted in the where clause. For example, if we add the condition
where JOB = ’CLERK’, only respective rows build a group. The query then would retrieve the
minimum and maximum salary of all clerks for each department. Note that is not allowed to specify
any other column than DEPTNO without an aggregate function in the select clause since this is
the only column listed in the group by clause (is it also easy to see that other columns would not
make any sense).

Once groups have been formed, certain groups can be eliminated based on their properties, e.g., if
a group contains less than three rows. This type of condition is specified using the having clause.
As for the select clause also in a having clause only <group column(s)> and aggregations can be
used.

Example: Retrieve the minimum and maximum salary of clerks for each department having
more than three clerks.

select DEPTNO, min(SAL), max(SAL) from EMP where JOB = ’CLERK’ group by DEPTNO
having count(job) > 3;

A query containing a group by clause is processed in the following way:


1. Select all rows that satisfy the condition specified in the where clause.
2. From these rows form groups according to the group by clause.
3. Discard all groups that do not satisfy the condition in the having clause.
4. Apply aggregate functions to each group.
5. Retrieve values for the columns and aggregations listed in the select clause.

Sub Queries:
Up to now we have only concentrated on simple comparison conditions in a where clause, i.e., we
have compared a column with a constant or we have compared two columns. As we have already
seen for the insert statement, queries can be used for assignments to columns. A query result can
also be used in a condition of a where clause. In such a case the query is called a subquery and the
complete select statement is called a nested query.

In a where clause conditions using subqueries can be combined arbitrarily by using the logical
connectives and and or.

Example: List the name and salary of employees of the department 20 who are leading
a project that started before December 31, 1990:

select ENAME, SAL from EMP where EMPNO in (select PMGR from PROJECT
where PSTART < ’31-DEC-90’) and DEPTNO =20;

Explanation: The subquery retrieves the set of those employees who manage a project that started
before December 31, 1990. If the employee working in department 20 is contained in this set (in
operator), this tuple belongs to the query result set.

Example: List all employees who are working in a department located in BOSTON:

select * from EMP where DEPTNO in (select DEPTNO from DEPT where LOC =
’BOSTON’);

The subquery retrieves only one value (the number of the department located in Boston). Thus it
is possible to use “=” instead of in. As long as the result of a subquery is not known in advance,
i.e., whether it is a single value or a set, it is advisable to use the in operator.

Conditions of the form <expression> <comparison operator> [any|all] <subquery> are used to
compare a given <expression> with each value selected by <subquery>.
• For the clause any, the condition evaluates to true if there exists at least on row selected by the
subquery for which the comparison holds. If the subquery yields an empty result set, the condition
is not satisfied.
• For the clause all, in contrast, the condition evaluates to true if for all rows selected by the
subquery the comparison holds. In this case the condition evaluates to true if the subquery does
not yield any row or value.

Example: Retrieve all employees who are working in department 10 and who earn at least
as much as any (i.e., at least one) employee working in department 30:

select * from EMP where SAL >= any (select SAL from EMP where DEPTNO = 30)
and DEPTNO = 10;

Note: Also in this subquery no aliases are necessary since the columns refer to the innermost
from clause.

Example: List all employees who are not working in department 30 and who earn more than
all employees working in department 30:

select * from EMP where SAL > all (select SAL from EMP where DEPTNO = 30) and DEPTNO
<> 30;

SET OPERATION
According to SQL Standard there are following Set operator types:

 Union [DISTINCT];
 Union All;
 Intersect [DISTINCT];
 Intersect All
 Minus
Some facts:

 UNION and INTERSECT operators are commutative, i.e. the order of queries is not
important; it doesn't change the final result.
 Minus operator is NOT commutative, it IS important which query is first, which second
using Minus operator.
 UNION, Minus and INTERSECT used without anything or with DISTINCT returns only
unique values. This is especially interesting when one query returning many nonunique
rows is UNIONED to another query returning zero rows. The final result contains fewer
rows than first query.

These usually are most widely used set operators. Quite many times one cannot get all the
result from one Select statement. Then one of the UNIONS can help. Graphically UNION can
be visualised using Venn diagrams. Assume we have two row sets.

Then Query1 UNION Query2 would be as follows. Grey area shows resultant set.

Example of Union:
The First table,
ID Name

1 John

2 adam

The Second table,


ID Name

2 Adam

3 Chirag

Union SQL query will be:

select * from First UNION select * from second

The result table will be:

ID Name

1 John

2 Adam

3 Chirag

Union All:

This operation is similar to Union. But it also shows the duplicate rows.

For above tables, Union all will be:

select * from First UNION ALL select * from second

The result table will be:


ID Name

1 John

2 Adam

2 Adam

3 Chirag

Intersect:
Intersect operation is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and data type must be same.

For the given above tables (In example of Union), intersect query will be:
select * from First INTERSECT select * from second
The result table will be as below:
ID Name

2 Adam

Minus:
Minus operation combines result of two Select statements and return only those results which
belong to first set of result.

For the above tables (given in example of Union), Minus query will be:
select * from First MINUS select * from second

The result table will be:


ID Name

1 John

DCL command:
Data Control Language(DCL) is used to control privilege in Database. To perform any operation
in the database, such as for creating tables, sequences or views we need privileges. Privileges are
of two types,

 System : creating session, table etc are all types of system privilege.
 Object : any command or query to work on tables comes under object privilege.

DCL defines two commands,

 Grant : Gives user access privileges to database.


 Revoke : Take back permissions from user.

Example:
To give access of table faculty to user U2 command will be:
grant all on faculty to U2;
To revoke access of table faculty from user U2 command will be:
Revoke all on faculty from U2;

Views:
After a table is created, it may become necessary to prevent all users from accessing all columns
of a table, for data security reasons. This would mean creating several tables having the appropriate
number of columns and assigning specific users to each table as required. But this will increase
redundancy. To reduce redundant data, oracle allows the creation of an object called a view. A
view takes the output of a query and treats it as a table, therefore view can be thought of as a ‘stored
query’ or a ‘virtual table’. The tables upon which views are based are known as base tables.
The syntax for creating a view:

create [or replace][no][force]view <viewname>[column alias name] as <query>[with check


option][read only][constraint];
1. Or replace – replaces an existing view with the same name, if it already exists
2. The force option- creates a view even though underlying table does not exist.
3. The column alias are used for the columns selected by the sub-query.
4. With read only – is to make sure that the data in the underlying table are not
changed.
Example:
create view emp_vw as select * from emp;
Suppose we want to create view on employee table to see only employees of department 10, view
can be written as:
create view emp_vw_dept as select & from emp where dept_no=10;

If we don’ t want user to update data of table through views we can create read only views
as below:
create or replace emp_vw as select * from emp with read only;
If we now fire query as below then it will give an error:
update emp_vw set sal=10000 where empno=7456;

A.5 Task: For given tables solve below queries:

category_header

route_Header

Place Header:

Fleet Header:
Ticket Header:

Ticket Detail:

Route Detail:

Queries:
1. Give average of the total fare.
2. Give the total collection of fare.
3. Which bus runs for minimum distance?
4. Give the total number of people who have traveled so far group by ticket
number.
5. Find out total fare for routes with same origin.
6. Find out total fare for routes with origin as madras.
7. Calculate average fare for each ticket.
8. Find out details of fleets that run on route number 33 or 25.
9. Count how many male or female passengers have travelled till now.
10. Count total number of routes for each category except category 02.
11. Find out place names for which nonstop buses run.
12. Find out details of tickets from ticket header having more than one passenger.
13. Find out details of route having category code same as category code of a route
having maximum distance.
14. Display distinct ticket number from both ticket_header and ticket_detail.
15. Display all ticket numbers from both ticket_header and ticket_detail.
16. Display only common fleet_id’s that are present in fleet_header and
ticket_header.
17. Select distinct route_id from route_header and not in route_detail using both the
tables.
18. Display distinct route_id’s from route header and route_detail.
19. Display all category_code from route_header and category_header.
20. Display only common place_id’s that are present in place_header and
route_detail.
21. Select common ticket_numbers from ticket_header and ticket_detail where the
route_id’s are smaller than the route_id which belong to place id as 01.
22. Select unique fleet_id’s from ticket_header and fleet_header where the route_id
is greater than route_id’s in route_header which belongs to the category_code as
01.
23. Create read only view route_vw on table route_header to display route_id,
origin and destination.
24. Try to update any record of view route_vw and explain error message.
25. Create view route_vw2 on table route_header with columns route_no, cat_code,
orgin and destination.
26. Display records of view route_vw2.
27. Try to insert record into view route_vw2 and state the output if possible else
explain error message.
28. Create view route_category_vw to display those routes which belong to category
‘delux’.
PART B

(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Portal or emailed to the concerned lab in
charge faculties at the end of the practical in case the there is no Portal access available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Commands and Output:

B.2 Curiosity Questions:


1. Solve below queries for given tables:

Distributor (Dno, Dname, Daddress, Dphone)


Item (Itemno, Itemname, Colour, Weight)
Dist_Item(Dno, Itemno, Qty)

c. Find distributor who has never supplied any item (using sub query).
d. Count total number of items of each colour.
e. Count number of items supplied by each distributor.

2. Justify the statement, “Views can be used for better manipulation of the given table”

3. Differentiate between ‘Union and ‘Union All’ used for Databases.

4. Explain at least one real life Application of views to solve any real life problem.

B.3 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.08
PART A

(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: To implement advanced aggregation features like ranking, partition by, Top-N queries,
Rollup and Cube Operators.

A.2 Prerequisite:

DML commands of SQL

A.3 Outcome:
After successful completion of this experiment, students will be able to

 Implement concepts of advanced aggregation.

A.4 Theory:
The aggregation support in SQL, which we have seen earlier, is quite powerful and handles most
common tasks with ease. However, some tasks are hard to implement efficiently with the basic
aggregation features.

1. Ranking and Partition By: RANK calculates the rank of a value in a group of values. The
return type is NUMBER. Rows with equal values for the ranking criteria receive the same rank.
As an aggregate function, RANK calculates the rank of a hypothetical row identified by the
arguments of the function with respect to a given sort specification. The arguments of the function
must all evaluate to constant expressions within each aggregate group, because they identify a
single row within each group. The constant argument expressions and the expressions in
the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments
must be the same and their types must be compatible.

As an analytic function, RANK computes the rank of each row returned from a query with respect
to the other rows returned by the query, based on the values of the value_exprs in
the order_by_clause.

For example:

select rank(5000) within group(order by sal desc) from emp

select empno,sal,rank() over(order by sal) from emp

select deptno,empno,sal,rank() over(partition by deptno order by sal) from emp


2. ntile : For a given constant n, the ranking function ntile(n) takes the tuples in each partition in
the specified order and divides them into n buckets with equal numbers of tuples. For each tuple,
ntile(n) then gives the number of the bucket in which it is placed, with bucket numbers starting
with 1.

3. Top-N analysis: Top-N queries provide a method for limiting the number of rows returned
from ordered sets of data.

• Top-N queries ask for the n largest or smallest values of a column. For example:

• – What are the ten best selling products?

• – What are the ten worst selling products

• Both largest values and smallest values sets are considered Top-N queries.

• They are extremely useful when you want to return the top or bottom "N" number of rows
from a set or when you are paging through data.

General Syntax:

SELECT [column_list], ROWNUM

FROM (SELECT [column_list]

FROM table

ORDER BY Top-N_column) WHERE ROWNUM <= N;

4. Rollup and Cube Operator: ROLLUP and CUBE are simple extensions to
the SELECT statement's GROUP BY clause. ROLLUP creates subtotals at any level of
aggregation needed, from the most detailed up to a grand total. CUBE is an extension similar
to ROLLUP, enabling a single statement to calculate all possible combinations of
subtotals. CUBE can generate the information needed in cross-tab reports with a single query. To
enhance performance, both CUBE and ROLLUP are parallelized: multiple processes can
simultaneously execute both types of statements.

A.5 Task: For given tables solve below queries:

category_header
route_Header

Place Header:

Fleet Header:

Ticket Header:
Ticket Detail:

Route Detail:

Queries:
1. Find the rank of a record with route id 105 as per the descending order of distance
in a route_header table.
2. Find out first three routes having largest distance.
3. Find out first three routes having lowest distance.
4. Find out rank of the tickets in the ascending order of the age of the passenger.
5. Find out rank of the routes for each category in the ascending order of distance
6. Find out total fare for all routes and total fare for each category.
7. Display sum of fare of all tickets, sum of fare for each ticket and sum of fare for
each sex.
PART B

(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Portal or emailed to the concerned lab in
charge faculties at the end of the practical in case the there is no Portal access available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Commands and Output:

B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.09
PART A
(PART A: TO BE REFFERED BY STUDENTS)

A.1 Aim: To Study commands of transaction management, commands like Commit, Rollback
and concept of concurrency control.

A.2 Prerequisite:

DDL, DML commands of SQL, concept of transaction and types of index.

A.3 Outcome:
After successful completion of this experiment students will be able to

Recognize the importance of concurrency, security, storage, recovery, indexing and


transaction management in database management systems.

A.4 Theory:

Transaction:
A transaction is a logical unit of work that contains one or more SQL
statements. A transaction is an atomic unit. The effects of all the SQL
statements in a transaction can be either all committed (applied to the
database) or all rolled back (undone from the database).
A transaction begins with the first executable SQL statement. A
transaction ends when it is committed or rolled back, either explicitly with
a COMMIT or ROLLBACK statement or implicitly when a DDL
statement is issued.
To illustrate the concept of a transaction, consider a banking database.
When a bank customer transfers money from a savings account to a
checking account, the transaction can consist of three separate operations:
Decrement the savings account
Increment the checking account
Record the transaction in the transaction journal

Oracle must allow for two situations. If all three SQL statements can be performed to maintain the
accounts in proper balance, the effects of the transaction can be applied to the database. However,
if a problem such as insufficient funds, invalid account number, or a hardware failure prevents one
or two of the statements in the transaction from completing, the entire transaction must be rolled
back so that the balance of all accounts is correct.

There are following commands used to control transactions:


COMMIT: to save the changes.
ROLLBACK: to rollback the changes.
SAVEPOINT: creates points within groups of transactions in which to ROLLBACK
SET TRANSACTION: Places a name on a transaction.

Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only. They can not be used while creating tables or dropping them because these
operations are automatically commited in the database.

1. COMMIT Command:
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.

Syntax for commit command:


commit;
Example:
SQL> DELETE FROM CUSTOMERS WHERE AGE = 25;

SQL> COMMIT;

2. The Rollback command:


The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
The syntax for Roll back command:
ROLLBACK;
For example:

SQL> DELETE FROM CUSTOMERS WHERE AGE = 25;

SQL> ROLLBACK;

3. The Savepoint Command:


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point
without rolling back the entire transaction.
The syntax for SAVEPOINT command is as follows:

SAVEPOINT SAVEPOINT_NAME;

This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as follows:

ROLLBACK TO SAVEPOINT_NAME;

Example:
SQL> SAVEPOINT SP1;

Savepoint created.

SQL> DELETE FROM CUSTOMERS WHERE ID=1;

1 row deleted.

SQL> SAVEPOINT SP2;

Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;

1 row deleted.

SQL> SAVEPOINT SP3;

Savepoint created.

SQL> DELETE FROM CUSTOMERS WHERE ID=3;

1 row deleted.

SQL> ROLLBACK TO SP2;

Rollback complete.

A.5 Tasks:
Task 1:

1. Open two SQL command line windows. Do the login with same username in both windows.

2. Type below code in first window:

begin

update emp set sal=sal+1000 where empno=7900;

end;

3. Type below code in second window:


select * from emp where empno=7900; (do not press enter)
4. Now in first window type ‘/’ and press enter. It will show message “PL/SQL Procedure
Successfully completed”.
5. Now press enter in second window and execute select query. See the salary column value.
What value are you getting? Note it down in Part B.
6. Now type below command in first window
commit;

7. Now again fire select query in second window select * from emp where empno=7900;. Note
what value are you getting for salary column? Note it down in part B. Why this difference?

Task 2:

1. Now let use try update the same tuple concurrently from two windows. In first window
execute:
begin
update emp set sal=sal+1000 where empno=7900;
end;

then in second window type same above code. Now in first window press enter and type ‘/’ to
execute procedure. Same time immediately in second window press enter and type ‘/’ to
execute procedure.

See what is happening. Note it down in part B.

Now type commit; in first window. See what happen? Not it down in part B.
Now fire below SQL query in both windows and note down salary column value in both
windows.
select * from emp where empno=7900;

Now type commit in second window and fire same SQL query in both window.
PART B
(PART B: TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black student portal
access available)

Roll No. Name:


Program : Division:
Batch: Date of Experiment:
Date of Submission: Grade :

B.1 Answer below questions

1. What is transaction?
2. What is rollback and commit command? Explain with an example.
3. What was your observation about savepoint command? Explain with an
example?
4. Explain your observation about task1.
5. Explain your observation about task2.

B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)

You might also like