Mobile
Mobile
for
Fifth Semester
B.Tech in Computer Science and Engineering
(Prepared in AUG-2022)
Name
SRN
Branch
Semester
Section
INDEX
SL. No Contents Page. no
3
1 Lab Objectives
3
2 Lab Outcomes
4
3 Lab Requirements
5
4 Guidelines to Students
6
5 Introduction to Database, oracle & SQL
20
6 List of Lab Exercises
23
7 Solutions for Lab Exercises
23
1 Product Order Database
DML Commands 41
2
58
3 Employee Database System
69
8 List of Lab Queries
70
9 Solutions for Lab Assignment Exercise I:
75
10 List of Viva Questions
Part-A
transactions.
customers.
Create a Book Data Base with the fields: (ISBN, Create and
MongoDB
bname, author [], year, publisher, price) use Book. perform
5.
operations
6. Create a Food Database with the fields: (food id, Create and
food cat, food name, chef name[ ], price, perform
MongoDB
ingredients [], hotel name, hotel address {no, operations
street, locality, city})
In this modern era of online shopping no seller MySQL: Draw the E-R
wants to be left behind, moreover due to its diagram and to
simplicity the shift from offline selling model to perform its
an online selling model is witnessing a rampant SQL commands operations.
growth. Therefore, as an engineer our job is to PL/SQL Triggers
ease the path of this transition for the seller.
Amongst many things that an online site Implementation:
requires the most important is a database o Creating tables
system. Hence in this project we are planning to o Inserting data
design a database where small clothing sellers
can sell their product online.
Queries
Modules:
Basic queries
User
Delete user
Transaction
Place order
Product
Add product
Delete product
Search product
View product
every product.
product details.
the cart.
particular date.
particular date.
website.
2. Lab Outcomes:
Analyze the requirements of a given database problem and design viable ERModels.
Create database schemas, select and apply suitable integrity constraints for querying
databases using SQL interface.
Develop database applications such as Product Order System, Employee Database System
using modern tools(mongoDB).
Design and develop database application based on real life problem to address societal
issues using various database management tools.
Following are the required hardware and software for this lab, which is available in the laboratory.
Hardware: Desktop system or Virtual machine in a cloud with OS installed. Presently in the
Lab, Pentium IV Processor having 1 GB RAM and 250 GB Hard Disk is available. Desktop
systems are dual boot having Windows as well as Linux OS installed on them.
Software: The DBMS packages that fall in this category are as follows:
Microsoft Windows
Under Windows environment, the Oracle client is called SQL*Plus.The following are Steps for logging
into the SQL.
Where <yourName> is again your login name, and <Password> is the password you would like to use in
the future. This command, like all other SQL commands, should be terminated with a semicolon.
Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care.
Any damage is caused is punishable.
Students are required to carry their observation / programs book with completed
exercises while entering the lab.
Students are supposed to occupy the machines allotted to them and are not supposed
to talk or make noise in the lab. The allocation is put up on the lab notice board.
Lab can be used in free time / lunch hours by the students who need to use the
systems should take prior permission from the lab in-charge.
In C3 exam one Data base application will be asked and the set of some queries will
be given in the final exam and evaluated for 50 marks and scale down to 25 marks.
Database
DBMS consists of a collection of interrelated data and a set of programs to manage these
data.
Data Model
Relational model
SQL * Plus
SQL *Plus enables you to manipulate SQL commands and PL/SQL blocks, and to perform
many additional tasks as well. Through SQL *Plus, you can
o Enter, edit, store, retrieve, and SQL commands and PL/SQL blocks.
o Format, perform calculations on, store, and print query results in the form of reports.
o List column definitions for any table.
o Access and copy data between SQL databases.
o Send messages to and accept responses from an end user.
Oracle Overview
Oracle is one the most popular Relational Database Management System (RDBMS).
Some other famous RDBMS includes Microsoft SQL Server, Sybase, MySQL, PostgreSQL, etc.
Essentially, all the aforementioned RDBMS employs Structural Query Language (SQL) as their
query interface. Users usually issue their queries by SQL through a "client". Different RDBMS
offer different forms of clients. For example, MS SQL Server offers a GUI interface for user to
type in their SQL language, and their queries would be executed after pressing the "Execute"
button on the client. Oracle provides both GUI client and command-line client. In this lesson, we
will study the command-line client, SQL*Plus. In addition, Oracle extends the standard SQL
(e.g. select * from table) with its application-specific commands (e.g. checking how many table
you have been created in your Oracle account) into a Oracle specific language called PL/SQL. In
this tutorial, you will interact with Oracle database, thru SQL*Plus, by issuing a number of
PL/SQL queries.
SQL Basics
Structured Query Language (SQL), which is an ANSI standard language for interacting with
relational databases, is the main tool for extracting the information.
Each entity must have an identifier, which is one or more attributes that make each entity instance
unique from any other instance. The identifier should contain a value that does not change.
School of Computing and Information Technology Page 13
Examples of identifiers are student IDs, payroll numbers, or social security numbers.
Primary key - If the entity does not have an attribute that can be used as an identifier, an artificial
identifier can be created. The identifier on an entity is often called a primary key.
Foreign key - A foreign key is a set of attributes of the considered table that exists as a primary
key attributes in another table. Database records are matched (joined) through the use of primary
and foreign keys.
Zero Normal Form - Each of the relations (tables) has a unique identifier (primary key).
First Normal Form - Separate the repeating groups of attributes or multi valued attributes
into a relation of their own. Be sure to form composite keys.
Second Normal Form - Establish full functional dependency by separating out attributes
that are not fully dependent on the full primary keys.
Third Normal Form - Remove transitive dependencies by separating attributes that are
dependent on a non key attribute.
The purpose of SQL is to interface to a relational database such as Oracle, and all SQL
statements are instructions to the databases.
Querying data
Inserting, updating, and deleting rows in a table
Creating, replacing, altering, and dropping objects
Controlling access to the database and its objects
Guaranteeing database consistency and integrity
Data Types
Each literal or column value manipulated by Oracle has a data type. A value’s data type associates
a fixed set of properties with the value. These properties cause Oracle to treat values of one data
types differently values of another.
Character Data types - Character data types are used to manipulate words and freeform text.
These data types are used to store character. These data types are used for character data:
CHAR - The CHAR data type specifies a fixed length character is 1 character and
maximum allowed is 2000 character.
NCHAR - The NCHAR data types specifies a fixed-length national character set
character string. The maximum column size allowed is 2000 bytes.
Number Data type - The NUMBER data type is used to store zero, positive and negative fixed
and floating point numbers with magnitudes
Floating Point Numbers - A floating point value either can have a decimal point anywhere from
the first to the last digit or can omit the decimal point altogether.
Long Data type - LONG columns store variable length variable length character strings
containing up to 2 gigabytes, or 231 -1 bytes. LONG data type is subject to some restrictions
which are:
DATE Data type - The DATE data types is used to store date and time information.
Operators - All the normal Arithmetic, Relational, Logical operators are used in SQL.
SQL Commands - In order to define schemas, store data, retrieve data and to make amendments
in schema and data stored in the database different types of commands are used which are:
Data Definition Language (DDL) commands allow you to perform these tasks:
Ex: Create table emp (empno number(4) primary key, ename char(10)) ;
Destroying tables
Data Manipulation Language (DML) commands query and manipulate data in existing schema
objects. These commands do not implicitly commit the current transaction.
1. Select
2. Insert
3. Delete
4. Update
5. Lock table
6. Explain Plan
Inserting Data into Tables - once a table is created the most natural thing to do is load this table
with data to be manipulated later.
Delete operations
Syntax:
not null constraint at column level <col> <datatype> (size) not null ;
unique constraint at table level Create table tablename (col = format, col = format,
unique ( <col1>, <col2> );
primary key constraint at table level Create table tablename (col = format, col = format
primary key (col1>, <col2>) ;
foreign key constraint at table level foreign key (<col>[,<col>]) references <tablename>
[(<col>,<col>) ;
1. Commit
2. Rollback
3. Save point
4. Set Transaction
Oracle provides extensive feature in order to safeguard information stored in its tables from
unauthorized viewing and damage. The rights that allow the user of some or all oracle resources
on the server are called privileges.
The grant statement provides various types of access to database objects such as tables, views and
sequences and so on.
REVOKE statement:
Aggregate Functions
Aggregate functions return a single value based upon a set of other values. If used among many
other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY
clause. No GROUP BY clause is required if the aggregate function is the only value retrieved by
the SELECT statement. The supported aggregate functions and their syntax are shown in
following table.
The aggregate function name may be AVG, COUNT, MAX, MIN, or SUM. The ALL clause,
which is the default behavior and does not actually need to be specified, evaluates all rows when
aggregating the value of the function. The DISTINCT clause uses only distinct values when
evaluating the function.
The AVG function computes the average of values in a column or an expression. SUM
AVG and SUM are supported by Microsoft SQL Server, MySQL, Oracle, and
PostgreSQL.
Explanation:- The following query computes average year-to-date sales for each type of book:
This query returns the sum of year-to-date sales for each type of book:
COUNT
The COUNT function has three variations. COUNT (*) counts all the rows in the target table
whether they include nulls or not. COUNT (expression) computes the number of rows with non-
NULL values in a specific column or expression. COUNT (DISTINCT expression) computes the
number of distinct non-NULL values in a column or expression.
The following query finds the number of different countries where publishers are located:
MIN (expression) and MAX (expression) find the minimum and maximum value (string,
date time, or numeric) in a set of rows. DISTINCT or ALL may be used with these functions, but
they do not affect the result.
Aggregate functions are used often in the having clause of queries with GROUP BY. The
following query selects all categories (types) of books that have an average price for all books in
the category higher than $15.00:
CONCATENATE
SQL99 defines a concatenation operator ( || ), which joins two distinct strings into one
string value. The CONCATENATE function appends two or more strings together, producing a
single output string. Oracle support the double-pipe concatenation operator. Microsoft SQL
Server uses the plus sign (+) concatenation operator.
Creating Tables
In SQL*Plus we can execute any SQL command. One simple type of command creates a table
(relation). The form is
You may enter text on one line or on several lines. If your command runs over several lines, you
will be prompted with line numbers until you type the semicolon that ends any command.
(Warning: An empty line terminates the command but does not execute it; see editing commands
in the buffer.) An example table-creation command is:
Exercise 1 : Create a relation Student that suitable for the following instance:
Inserting Tuples
Having created a table, we can insert tuples into it. The simplest way to insert is with the INSERT
command:
For instance, we can insert the tuple (10, 'hi world') into relation test by
Exercise 2: Insert the records as stated into Exercise 1 into the student table.
Trick: Try to insert a record into test with the following SQL:
Updating Tuples
Exercise 3: Update the record of 'Eric Lo' in relation Student such that his salary change to
1234
Deleting Tuples
Having insert / update a tuple, we can delete it as well. The simplest way to delete is with the
DELETE command:
<condition> is an optional statement and is used to identify a single record when necessary.
For example, you can delete the record with i=10 in table test with the the following SQL:
Trick: Does that record really deleted successfully? Let's check it out by using SELECT
command (we will cover it in next section).
Retrieving Tuples
IS
11 ha 'world
Question: Do data values also case insensitive? i.e., can a student with name "Hammer" be
retrieved by the following SQL or not?
It provides a good back-door for you to revert the changes you have done on the data. Therefore,
unless you have issued COMMIT, the changed data would not be visible to any other session
except your own. Conversely, you can rollback all the changes by issuing the ROLLBACK
command.
Exercise 6: Issue the COMMIT command in the SQL*Plus that you have done
insert/delete/update before, and see if the effect is now visible by the new SQL*Plus?
Dropping Tables
Caution: Table dropping is a DML statement, which is an action that you cannot rollback. Since
dropping a table will also delete all data in that table, issue the DROP TABLE command with
cares.
The system keeps information about your own database in certain system tables. The most
important for now is USER_TABLES. You can recall the names of your tables by issuing the
query:
More information about your tables is available from USER_TABLES. To see all the attributes of
USER_TABLES, try:
It is also possible to recall the attributes of a table once you know its name. Issue the command:
VARCHAR2 Variable-length character data (a maximum size must be specified: Minimum size
(size) is 1; maximum size is 4000)
Fixed-length character data of length size bytes (default and minimum size is 1;
CHAR [(size)]
maximum size is 2000)
Number having precision p and scale s (The precision is the total number of
NUMBER decimal digits, and the scale is the number of digits to the right of the decimal
[(p,s)] point; the precision can range from 1 to 38 and the scale can range from -84 to
127)
Date and time values to the nearest second between January 1, 4712 B.C., and
DATE
December 31, 9999 A.D.
To create a table that declares the set of attributes (a,b,c) to be a primary key:
CREATE TABLE <tableName> (<attrs and their types>, PRIMARY KEY (a,b,c));
a. Retrieve the names of the Employees who works on all the projects
controlled by dept no 3.
b. Retrieve the names of the Employees who gets second highest salary.
c. Retrieve the names of the Employees who have no dependents in
alphabetical order.
d. List the names of all Employees with at least two dependents.
e. Retrieve the number of Employees and their average salary working in each
Department.
f. Retrieve the highest salary paid in each Department in descending order.
g. Retrieve the SSN of all Employees who work on atleast one of the project
numbers 1, 2, 3.
h. Retrieve the number of dependents for an Employee named RAM.
i. Retrieve the names of the managers working in location named xyz who has
no female dependents.
j. Retrieve the names of the Employees who works in the same Department as
that of RAM.
k. Retrieve the names of the Employees whose salary is greater than the salary
of all the Employees working in Department no 3.
l. Retrieve the names of the Employees who work for dept no 3 and have a
daughter as dependent.
m. Retrieve the names of the Employees who paid highest salary from each
Department.
n. Retrieve the names of the Employees who are paid the same salary as that of
Anil.
o. Retrieve the total the number of Employees in the ‘Research’ Department.
p. For each project, retrieve the project number, the project name, and the
number of Employees who work on that project.
School of Computing and Information Technology Page 28
Lab Exercise 1: Product - Order database
Aim: Create the tables with the appropriate integrity constraints and Insert around 10 records
in each of the tables
SQL> Create table Customer ( cid char(4) ,cname varchar(13) not null,city varchar(20),
discount real check(discount >= 0.0 and discount <= 15.0),
primary key (cid));
Table created.
Explanation: The above command will create a new table Customer in database system with 4
columns, namely cid, cname, city and discount using not null constraint for cname and primary
key constraint for cid, discount checking with constraint as discount range+ greater than zero and
less than 15 percent.
Page 29
SQL> Create table agent (aid char(3) ,
aname varchar(13) not null,
city varchar(20),
percent number(6) check (percent >= 0 and percent <= 100),
primary key (aid));
Table created.
Explanation: The above command will create a new table agent in database system with 4
columns, namely aid, aname, city and percent using not null constraint for aname and primary
key constraint for aid, percent checking with constraint as percent range greater than or equal to
zero and less than equal to 100 percent.
SQL>Create table product ( pid char(3),pname varchar(13) unique not null,city varchar(20),
quantity number(10) check(quantity > 0),price real check(price >
0.0),primary key (pid));
Table created.
Explanation: The above command will create a new table Product in database system with 5
columns, namely pid, pname, city , Quantity and price using not null constraint for pname and
primary key constraint for pid , price checking with constraint as range greater than zero.
Page 30
SQL> Create table orders ( ordno number(6),
month char(3),
cid char(4) not null,
aid char(3) not null,
pid char(3) not null,
qty number(6) not null check(qty > 0),
ordamount float default 0.0 check(ordamount >= 0.0),
primary key (ordno),
foreign key (cid) references customer,
foreign key (aid) references agent,
foreign key (pid) references product);
Table created.
Explanation: The above command will create a new table orders in database system with 7
columns, namely ordno, month, cid ,aid, pid, Qty and ordamount and with foreign key constraint
of cid referring to customer and aid referring agent, pid referring product, ordno as primary key
and quantity with check constraint with range greater than zero .
NOTE: If an attempt is made to insert the same cid , as it is having primary constraint it shows
an error.
1 row created.
Page 31
SQL>insert into customer values ('c001','Sachin','Darjeling',10.00)*
ERROR at line 1:
ORA-00001: unique constraint (DBMS.SYS_C005054) violated
SQL> select * from customer;
SQL> /
Enter value for ordno: 1012
Enter value for month: jan
Enter value for cid: c001
Enter value for aid: a01
Enter value for pid: p01
Enter value for qty: 1000
Enter value for ordamount: 9400
Page 33
SQL> select distinct p.cid from orders o, orders p where p.pid=o.pid and o.aid='a06'
Explanation: Distinct keyword gives the different values of attribute cid from table Orders and
product with the join ,pid attribute from product table and pid attribute from order table, whose
agent id is ao6.
OUTPUT: CID
c001
c004
c005
2.b) Retrieve cities in which customers or agents located.
Explanation: This query retrieves the city names as the union operator helps to combine both
the tables customer and agent containing column name city and it won’t allow duplicate values.
OUTPUT: CITY
Agra
Darjeling
Jaipur
Mumbai
NewDelhi
Srinagar
6 rows selected
2.c )List product ids which have been ordered by agents from the cities “Dargeling” or
“Srinagar”.
Explanation: Distict helps to select the distinct values of pid attribute from order table and agent
table, and the columns aid from tables order and agents with city ‘Darjeeling’ and Srinagar using
in operator.
Or
SQL> select distinct(pid) from orders where aid in (select aid from agent where
city in( ’Darjeling’,’Srinagar’));
Explanation: Distinct selects the distinct values of pid from orders table and using in operator
to select the aid attribute from agent table with city names darjeling and Srinagar.
OUTPUT: PID
Page 34
p01
p06
p07
2.d) Retrieve customer ids whose discounts are less than the maximum discount.
Explanation: This query gives the customer ids from customer table with condition whose
discount is less than max discount as max(discount) gives the maximum discount from customer
table.
OUTPUT: CID
c001
c003
c004
c005
Explanation: This Query gives the pids from prouct table ,with condition 2<= count(distinct
cid) as count gives the no.of distinct cids from orders table and pid column from product table .
OUTPUT: PID
p01
p05
p07
2.f) For each (aid,pid) pair get the sum of the orders aid has placed for pid.
Explanation: To retrieve pid and aid attribute and the sum operator is used to return the total
sum of the qty column from orders table using group by function is used to get the result in a set
of pid and aid attributes.
10 rows selected.
2.g ) Retrieve product ids and total quantity ordered for each product when the total
exceeds 1000.
SQL> select pid, aid, sum(qty) TOTAL
from orders
group by pid, aid
having suzm(qty) > 1000;
Explanation: To retrieve pid and aid attributes and the sum operator is used to return the total
sum of the qty from orders table using group by function is used to get the result in a set of pid
and aid attributes and having clause is used instead of where as condition whose sum(qty) is
greater than 1000.
2.h) List the names of the customers and agent who placed an order through that agent.
Explanation: This query gives distinct values from attributes v=cname,aname from customer,
orders and agent tables with condition cid from customer table and orders and also from aid
attribute from orders and agent table.
6 rows selected.
2 i) Retrieve the order numbers placed by customers in "Dargeling" through agents
in "NewDelhi".
SQL>select ordno from orders where cid in (select cid from customer where city =
’Darjeling’) and aid in (select aid from agent where city = ’NewDelhi’);
Explanation: To get ordno from orders table with condition using in operator for attribute
cid from customer table whose city is darjeling and aid from agent table whose city is newdelhi.
OUTPUT: ORDNO
1011
1012
1023
2 j) Retrieve names of the customers who have the same discount as that of any (one)
of the customers in "Dargeling" or "Bangalore".
Explanation: To get the cname from customer table with condition where any value of discount
from customer table whose city is Darjeeling or Bangalore.
OUTPUT: CNAME
Sobhit
Anand
Amar
2 b K) Retrieve customer ids with smaller discounts than every customer from "
Srinagar”
Explanation: To get cid from customer table, with condition whose all discount values is less
than the discount of every customer whose city is Srinagar.
Page 37
OUTPUT: CID
c005
2 B I) Retrieve names of the customers who have placed an order through agent
"a05"
(using exists )
Explanation: To get the cname from customer table as exist helps to check the existence of
query and selects the complete table from orders with condition cid attribute from customer table
and order table whose aid column from order table is a05.
or
SQL> select cname from customer where cid in (select cid from orders where aid='a05');
OUTPUT: CNAME
Sobhit
2 B m) Retrieve names of the customers who do not place orders through agent
"a05".
(using not exists)
Explanation: To retrieve cname from customer table with condition cid from orders table is
not in cid of order table where aid from order table is a05
or
OUTPUT: CNAME
Bhanu
Amar
Anand
Anand
2 B n) Retrieve customer ids whose orders placed through all the agents in "New
Delhi".
Page 38
Get cid values of customers such that (the set of agents from " NewDelhi " through
whom the customer has NOT placed an order) is EMPTY.
Explanation: To retrieve cid from customer table ,with condition not exists,as this helps to get
the values which are not existed in the agent table whose city is new delhi and also from orders
table that do not exist with condition cid column from order table equal to cid column from
customer table and also aid columns from order and agent tables.
OUTPUT: CID
c00
a. 2 b o). Retrieve agent ids either from "NewDelhi" or "Srinagar" who place orders for ALL
products priced over fifteen rupee. Get aid values of agents from "New York" or "Duluth"
such that (the set of products priced over one dollar that the agent has NOT ordered) is
EMPTY.
b.
Explanation:To retrieve aid from agent table whose cities are new delhi and srinagar and using
not exist to select the pid from product whose price is greater than 15,and also again using not
exist from orders table where pid from order and product table also aid from both tables are
equal.
OUTPUT:
no rows selected
So
insert into orders values('1026','apr','c005','a05','p02',900,17100);
OUTPUT: AID
a05
2 b p).Retrieve names and ids of the customers and agents along with total sales for that
Page 39
pair. Order the result from largest to smallest total sales. Also retain only those pairs
for which total rupee sales is at least 9000.00.
Explanation:To retrieve cname,cid,from customer table and aname and aid from agent
table,with sum function for order amount from order table ,customer and agent table with
condition cid from customer and order tables and aid from order and agent tables are equal and
to get the result in one set group by is used for cname,cid of customer table and aid ,aname from
agent table with sum of ordramount of order table is >= 9000 in descending order as result.
OUTPUT:
CNAME CID ANAME AID SUM(O.ORDAMOUNT)
Sobhit c001 Omkar a05 20900
Sobhit c001 Sonu a01 18800
Sobhit c001 John a02 15040
Anand c005 Bhargav a03 11160
Anand c004 Sonu a06 9500
Anand c005 Sonu a01 9400
6 rows selected.
Explanation:To update agent table, percentage value is set to 1.5*percent to get 50% whose city
is NewDelhi.
2 B r). Retrieve the total quantity that has been placed for each product
Explanation: To get pid with total sum of qty from orders table using group by to get the result
in one set.
3 rows selected.
Page 41
Lab Exercise 3 : Employee Database System
3.1 Problem Statement
Designing a company database which can store Department, project, Employee and his
dependent details of a particular organization.
3.2 Student Learning Outcomes
Aim: Create the tables with the appropriate integrity constraints and Insert around 10 records
in each of the tables
NOTE: Department table has a column mgr_ssn which is a foreign key referring to ssn column
of an Employee table And Employee table has a column dno which is a foreign key
referring to dnumber of Department table.So it is interlinked and deadlock appears.
step i create table Department with attributes dno, dname (without mgr_ssn column)
step ii insert data into Department
step iii create table Employee and insert data ( without super_ssn column)
step iv insert data into Employee table
step v add new column super_ssn into Employee table and update data to column super_ssn
step vi add new column mgrssn into Department referring to Employee table
stpe vii insert data of mgrssn in Department table
Page 42
OUTPUT: Name Null? Type
DNAME NOT NULL VARCHAR2(15)
DNUMBER NOT NULL NUMBER(38)
OUTPUT:
OUTPUT:
SSN NAME SALARY S ADDRESS DNO SUPER_SSN
emp001 Ram 30000 M RT Nagar, Blore 3 emp006
emp002 Sudha 75000 F Hebbal, Blore 2
emp003 Ravi 20000 M Hebbal, Blore 4 emp008
emp004 Rohan 80000 M RT Nagar, Mysore 1
emp005 Amar 35000 M MG Road, Mysore 3 emp002
emp006 Anil 45000 M MG Road, Noida 3 emp008
emp007 Tanya 35000 F Yelahanka, Blore 3 emp008
emp008 Kavita 50000 F Baglur, Blore 1 emp004
emp009 John 45000 M RT Nagar, Blore 4 emp008
Page 44
OUTPUT: Name Null? Type
DNAME NOT NULL VARCHAR2(15)
DNUMBER NOT NULL NUMBER(38)
MGR_SSN CHAR(9)
a. Retrieve the names of the Employees who gets second highest salary.
SQL> select name from Employee
where salary in ( select max(salary) from Employee
where salary not in (select max(salary) from Employee));
Page 47
or
Explanation: This Query gives the name of the Employee using max function for salary column
from Employee table, whose sal is not in max(salary) or by using < operator .
OUTPUT: NAME
Sudha
b. Retrieve the names of the Employees who have no dependents in alphabetical order.
Explanation: This query gives the name of Employee using not exists in dependent with
condition essn=e.ssn using order by name. or
By using not in and ssn column from dependent table using order by .
OUTPUT: NAME
Anil
Sudha
Ravi
Amar
Kavita
c. List the names of all Employees who have at least two dependents
Explanation: This query gives the names of the Employees, using count function as it gives the
count value of the selected table with condition ssn=Essn and >=2.
OUTPUT : NAME
John
d. Retrieve the number of Employees and their average salary working in each
department.
Page 48
SQL> select dno, count (*),avg(salary) from Employee group by dno;
Explanation: This Query gives dno,count and avg sal from Employee table using group by dno .
SQL> select dno,max(salary) from Employee group by dno order by max(salary) desc;
Explanation: This Query gives the dno and Max (salary) Using Group by and Oder by functions
with conditions group by dno and order by max(salary) as desc.
f. Retrieve the SSN of all Employees who work on atleast one of the project numbers 1, 2, 3
Explanation : This Query gives the Essn of Employee from workson table using distinct with
condition pno in (p01,p02,p03) or pno=p01 or p02,p03
OUTPUT : ESSN
emp001
emp003
emp005
Explanation : This Query gives the no .of dependents using count function for dependent table
with condition whose essn is equal to ssn of Employee table whose ename is ram .
Or
Explanation: By using count for Employee table and dependent with condition essn of
dependent table = ssn of Employee table and whose name from Employee table is ram.
OUTPUT : COUNT(*)
1
h. Retrieve the names of the managers working in location named xyz who has no
female dependents.
Or
Explanation: This query gives the name of manger from Employee table by using IN operator,
whose ssn from dependent table sex is not ‘F’ and mgr_ssn from department,whose dnumber
from dep_location is Blore.
Or
Explanation: By using distinct for name from Employee table ,department ,dependent and
location tables whose ssn from Employee =essn from dependent table and sex is not ‘F’ in
dependent and essn from dependent =mgr from department mgr_ssn and dnumber from
d=dhumber from l;and dlocation from l=’Blore’.
OUTPUT : NAME
John
i. Retrieve the names of the Employees who works in the same department as that of
Page 50
RAM
Explanation: This gives the name from Employee using condition get dno whose name is ram
from emp table and name whose name is not ram.
OUTPUT : NAME
Amar
Anil
Tanya
j. Retrieve the name of the Employees whose salary is greater than the salary of all the
Employees working in department 3.
Explanation: To get the name, salary of Employee from emp table using condition
whose salary is > All Employees and whose dno=3.
k. Retrieve the names of the Employees who work for dept no 3 and have a daughter as
dependent.
Explanation: This Query gives the name using conditions ssn fromemp=essn from dependent
and relationship from depend=daughter and dno from emp=3.
OUTPUT : NAME
Tanya
l. Retrieve the Employee name who paid highest salary from each department.
Explanation: To get the name from emp using condition whose sal in emp using max
and groupby dno.
Page 51
OUTPUT : NAME
Rohan
Sudha
John
Anil
m. Retrieve the names of the Employees who are paid the same salary as that of Anil.
OUTPUT : NAME
John
n. Retrieve the total the number of Employees in the ‘Research’ department.
SQL> select count (*) from Employee, Department
where dno =dnumber and dname=‘Research’;
Explanation: To get the total ,we use count function along with condition whose dno is
dnumber and dname is research.
OUTPUT : COUNT(*)
2
o. For each project, retrieve the project number, the project name, and the number of
Employees who work on that project.
SQL> select Pnumber, Pname, count (*)
from Project, Workson
where Pnumber=Pno
GROUP BY Pnumber, Pname;
Explanation: This query gives the pnumb ,pname and total number from project and workson
tables using condition whose pnumber is pno and group by pnumber and pname.
Page 52
4) Create an employee database with the fields: {eid, ename, dept, desig, salary, yoj, address
{dno, street, locality, city}}
Use employee
Db.createCollection(“emp”)
i. Insert 10 documents.
db.emp.insert(doc1)
ii. Display all the employees with salary in range (50000, 75000).
db.emp.find({$and:[{salary:{$gt:50000}},{salary:{$lt:75000}}]})
iii. Display all the employees with designation developer.
db.emp.find({desig:”developer”},{ename:1,desig:1,_id:0})
Page 53
db.emp.update({ename:"Rahul"},{$pull:{projects:"p3"}})
xii. Add a new embedded object “contacts” with “email” and “phone” as array objects to “Rahul”.
db.emp.update({ename:"Rahul"},{$push:{contacts:{phone:"9036240380",
email:"[email protected]"}}})
xiii. Add two phone numbers to “Rahul”.
db.emp.update({ename:"Rahul"},{$addToSet:{"contact.phone":[9738751143,988073 0784]}})
Page 54
5.Create a book Data Base with the fields: (isbn, bname, author [], year, publisher, price)
use Book
db.createCollection(“book”)
Insert 5 documents.
>db.book.insert(doc1)
db.book.find().pretty()
>db.book.find({},{year:0,price:0})
>db.book.find({author:”rudresh”})
>db.book.find({publisher:”pearson”})
>db.book.find({bname:”java”},{publisher:1,bname:1,_id:0})
List the author, publisher and year of the book “Let us C”.
>db.book.find({},{bname:1}).sort({bname:1})
Page 55
Sort and display only 3 books in descending order of price.
>db.book.find().sort({price: -1}).limit(3)
db.book.find({author:{$all:[“herbert”,”kuvempu”]}},{bname:1,author:1,price:1})
db.book.find({author:{$in:[“herbert”,”kuvempu”]}},{bname:1,author:1,price:1})
>db.book.find({"author.0":{$eq:"rama"}})
Page 56
6. Create a Food Database with the fields: (food id, food cat, food name, chef name [ ], price,
ingredients [], hotel name, hotel address {no, street, locality, city})
Insert 10 documents.
db.food.insert(doc1)
db.food.find({foodname:"pizza"},{foodname:2, ingredients:1,price:1})
db.food.find({chefname:{$all:["x","y"]}},{chefname:1,foodname:1, _id:0})
db.food.update({foodname:"burger"},{$addToSet:{ingredients:["corn","cheese"]}})
db.food.update({foodname:"burger"},{$pop:{ingredients:1}})
db.food.update({foodname:”biryani”},{$pullAll:{ingredients:[]}})
Page 57
Add food type to the food Burger.
db.food.update({foodname:"burger"},{$pop:{ingredients:1}})
db.food.update({foodname:"burger"},{$set:{price:200}})
Add or insert a new food item with the food Id “f08 “ usingupsert as True.
db.food.update({foodid:"f08"},{foodid:"f08",foodcat:"chats",foodname:"pani
Increment the price of all food item in food cat: fastfood by 120.
Page 58
8. Lab Assignments
7 rows selected.
d) Display Product name and price as a single column and the column name be “Product
and their prices” (concatenation operator and alias)
Page 24
SQL> select pname||price "product and their prices" from product;
SQL> select pname||' '||price "product and their prices" from product;
SQL> select pname||' cost is '||price "product and their prices" from product;
OUTPUT: CITY
Srinagar
Darjeling
Mumbai
Srinagar
f) Retrieve the names of the customers lives in “Mumbai”
h) Retrieve the customer ids who ordered the products “p01” and “p02”
SQL> select cid from orders where pid='p01' intersect select cid from orders where pid='p07';
OUTPUT: CID
c001
c005
OUTPUT: CNAME
Amar
Anand
Anand
j)Retrieve the customers whose name starts with letter “A” and third letter is “a” eg. Amar
OUTPUT: CNAME
Amar
Anand
Anand
k)Retrieve the customers whose name consists of letter “a”
OUTPUT: CNAME
Bhanu
Amar
Anand
Page 26
Anand
SQL> select cid from customer where discount between 8 and 10;
OUTPUT: CID
c001
c003
c004
m) Display the product name whose price is 10 or 20 using IN and OR operators
OUTPUT: PNAME
comb
brush
Highlighter
OUTPUT: SUM(QTY)
4800
OUTPUT: COUNT(DISTINCT(CNAME))
4
OUTPUT: SUM(ORDAMOUNT)
104598
q)Get total number of customers.
OUTPUT: COUNT(CID)
5
Page 27
r)Get average discount value for customers.
OUTPUT: AVG(DISCOUNT)
7.6
SQL> select aid from agent where percent in (select min(percent) from agent);
Or select aid from agent where percent= (select min(percent) from agent)
OUTPUT: AID
a05
a06
t)Display the names of the customers who placed an order through the agent who is having
aid as “a01”
SQL> Select distinct(c.cname) from customer c , orders o where c.cid=o.cid and o.aid=’a01’;
OUTPUT: CNAME
Sobhit
Anand
u)Retrieve the names of the customers who live in “Mumbai” and order product “p01”
OUTPUT: CNAME
Anand
Anand
OUTPUT: CNAME
Anand
v) Retrieve customer ids who do not order part “p01”
SQL> select cid from customer minus (select cid from orders where pid='p01') ;
or
select cid from customer minus ( select distinct (cid) from orders where pid='p01');
OUTPUT: CID
c002
Page 28
c003
1) What is an RDBMS?
2) What is the SQL?
3) What are the different kinds of DBMS?
4) What are the features of relational database?
5) What are data types?
6) What is an E-R diagram?
7) What is the referential integrity?
8) What is a foreign key?
9) What is a primary key?
10) What is an alternate key in table?
11) What is the normalization?
12) Explain the First Normal Form?
13) Explain the Second Normal Form?
14) Explain the Third Normal Form?
15) What is an index, and how is it used to improve performance?
16) What are the types of indexes, and if separate indexes are created on each column of a
table, what are the advantages and disadvantages of this approach?
17) What is the SQL Data Manipulation Language (DML)?
18) What is the SQL Data Definition Language (DDL)?
19) What is the de-normalization?
20) What is a transaction?
21) What are ACID properties?
22) What is the difference between DELETE TABLE and TRUNCATE TABLE commands?
23) What are constraints?
24) What are the different types of constraints?
25) What are cursors? What are the different types of cursors?
26) What are the advantages of cursors? How can you avoid cursors?
27) What is a join and explain different types of joins.
28) What is a self-join? Explain it with an example.
29) How do you implement one-to-one, one-to-many, many-to-many relationships while
designing tables?
30) What is the difference between primary key and a unique key?
31) What are defaults?
32) What are triggers? How do you invoke a trigger on demand?
33) What is a stored procedure? What are the advantages?
34) What is the difference between stored procedure and a trigger?
35) What are the different types of parameters available in stored procedures?
Page 29
36) How do you get the distinct rows in a table/ resultset?
37) How do you get the distinct rows without using the keyword DISTINCT?
38) How can you get the duplicated rows from the table using a single query?
39) How can you get the total number of records in a table?
40) How can you insert values in multiple rows using one insert statement?
41) What is the database replication?
42) What will happen when a Rollback statement is executed inside a Trigger?
43) What is collection in Mongo DB.
44) What is insert() method in mongo DB.
45) How to create a document in MongDB.
References:
2010.
2. C J Date, “Database Design and Relational Theory: Normal Forms and All that Jazz”, O
‘Reilly, April 2012.
3. David Hows, “The definitive guide to MongoDB”, 2nd edition, Apress Publication, 2009,
8132230485.
JOURNALS/MAGAZINES:
SWAYAM/NPTEL/MOOCs:
1. https://www.coursera.org/courses?query=database
Page 30
2. https://www.edx.org/learn/databases
3. https://academy.oracle.com/en/solutions-curriculum.html
SELF-LEARNINGEXERCISES:
1. Data warehousing, Data Marts, Getting data into the warehouse More exploration on GIThub
Page 31