DBS Lab Manual 2022-2023
DBS Lab Manual 2022-2023
LABORATORY MANUAL
Vision of Institute
To prepare the students ready with socially sensitive
Engineers of Excellence who will grow with the Institute and
add value to the nation.
Mission of Institute
Vision of Department
To create quality computer professional through excellent
academic environment.
Mission of Department
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO2: Problem-Solving Skills- The ability to apply standard practices and strategies in software
project development using open-ended programming environments to deliver advanced computing
systems.
PSO3: Professional Career and Entrepreneurship- The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an entrepreneur,
and a zest for higher studies and research.
2 Using SQL prompt create database and use of SQL commands (DDL, DML and DCL).
Using SQL to Create Table and Rename table for suitable database schema also apply
database constraint like primary key, foreign key and NOT Null. Then design at least
3
ten SQL queries SQL DML statements: Insert, Select, Update, Delete using distinct
and count clause.
Consider the suitable database schema and design five SQL Nested Queries
4
with/without Where clause.
5 Write a stored procedure to insert and retrieve data from database table.
Design a queries for suitable database application using SQL DML statements: all
8
types of Join, Views.
Design database schema using normalization concepts for office automation or hotel
10
management or hospital management.
Implement small database system for office automation or hotel management or
11
hospital management.
Assignment/Experiment :
Date of Performance: Date of submission :
Marks Split Up to Maximum Marks Marks Obtained
Performance/ conduction 3
Report Writing 3
Attendance 2
Viva/Oral 2
Total Marks 10
COURSE OBJECTIVES:
• This lab enables the students to practice the concepts learnt in the subject DBMS by developing a
database.
• The student is expected to practice the designing, developing and querying a database.
• Students are expected to use “Mysql/Oracle” database
COURSE OUTCOMES:
At the end of this course Students will be able to:
Experiment No. 1
Theory:
Once the installer has been downloaded, double-click the setup file to start the installation process. On
the Choosing a Setup Type page, you can see four installation options.
1. Developer default: If you want to create a development machine, you can use this option. It
installs the components which are required for application development, e.g., MySQL Server,
MySQL Shell, MySQL connectors, MySQL
2. Server Only: If you want to create a standalone database server with specific components, you
can use this option
3. Full: If you want to install MySQL Server with its all components, then you can use this option
4. Custom: If your requirements are limited to the few components, you can use this option
We are going to install MySQL Server with all components; hence, choose “Full” and click on Next.
Before installation begins, the installer checks all the prerequisites that are required to install all the
components of the MySQL database server. If any software prerequisites are missing, then you can
see the details of failing requirements on the “Check Requirements” screen. It shows the name of the
product, required component/software, and its status. As you can see, to install the MySQL database
server for visual studio, we must install visual studio 2015 or above. Similarly, to install Python
connector, we must install python on the work station. Click on Next.
An installer gives us a warning. We can continue our installation without installing the visual studio
and python. Click on Yes.
On the Installation screen, you can see the list of the MySQL products/software that are going to be
installed on my workstation. Review the list and click on Execute.
The installer downloads all the products/software. After that, it installs all the products.
Wait for a few mins. Once the installation process completes, we are ready to configure the MySQL
database server and other components. Click on Next.
On the Product configuration screen, you can see the list of the products that need to be configured.
First, let us configure the MySQL Server. Click on Next.
On the High availability screen, we can choose to install the InnoDB cluster or Standalone MySQL
Server. InnoDB cluster is the High availability solution of MySQL. It uses group replication. I will
explain more about it in my future series of articles. We are going to perform a standalone installation
of MySQL Server hence choose “Standalone MySQL Server / Classic MySQL Replication”.
Network Connectivity
In this section, we can control how clients can connect to MySQL databases. We can use TCP/IP
protocol or Named Pipe or Shared Memory. If you want to configure Named Pipe / Shared Memory,
we must provide the Pipe Name and Memory Name. You can also specify the default port to connect
to the database server. You can also choose to allow the port number specified in Port textbox in the
firewall. See the following image:
In MySQL 8.0 version, we can use SHA256 based strong passwords. On the Authentication
Method screen, choose the option to use the Legacy authentication method or Strong password for
authentication. Note: If you are using Strong Password Encryption for Authentication, then make
sure that all the connectors must be updated to the latest version. We are going to use Strong password
Encryption for Authentication.
On Accounts and Roles screen, you can specify the MySQL root account password. MySQL Root
account is a default sysadmin account, and it must be disabled.
You can also create other users to do that click on Add user. On MySQL User account dialog box,
provide a username, hostname, Role of the User, type of authentication, and password. Once the user
is created, click on Next. See the following image:
On the Windows Service screen, you can configure the MySQL server to run as a windows service.
You can provide the desired name and configure it to auto-start the service when the system reboots.
Moreover, you can provide the credentials under which the MySQL Service will run. You can choose
the standard system account or provide a specific user. See the following image:
On the Apply Configuration screen, you can see the list of confirmation steps. Once all the
configuration settings are verified, click on Execute.
The MySQL installation process starts. You can view the installation process in the “Log” tab. Once
installation completes successfully, click on “Finish” to close the installer.
On the Apply Configuration Screen, click on Execute to start the installation of the Sample database.
See the following:
Once the sample database has been installed, click on the Finish button.
The installer continues to the Product Configuration screen. On this screen, you can see that the
installation of the MySQL Server 8.0.19 and Sample and Example 8.0.19 has been completed
successfully. See the following image:
Once the installation completes, you can copy the installation logs on the clipboard to review it later.
Moreover, if you want to start exploring MySQL straight away, then you can select “Start MySQL
workbench after Setup” and “Start MySQL Shell after Setup” and click on Finish. See the
following image:
When you click on the connection, you must enter the credentials to connect the database server. Enter
the password and click on OK.
First, let’s create a simple database on MySQL Server. Write the following query in the query editor
window and click on execute. See the following image:
1 Create database Demodatabase
Once the query executes successfully, you can see the new database in the “SCHEMAS” pan. See the
following image:
Experiment No. 2
Problem Statement: : Using SQL prompt create database and use of SQL
commands (DDL, DML and DCL).
Theory:
SQL Commands
-Rename - Delete
1. CREATE TABLE
Syntax: Create table table name( fieldname1 datatype(),fieldname2 datatype()...);
2. ALTER
A) ADD
B) MODIFY
ADD
Syntax: Alter table table name ADD (fieldname datatype()...);
1. GRANT
2. REVOKE
GRANT: It provides the user's access privileges to the database. In the MySQL database offers both
the administrator and user a great extent of the control options. By the administration side of the
process includes the possibility for the administrators to control certain user privileges over the
MySQL server by restricting their access to an entire the database or use limiting permissions for a
specific table. It Creates an entry in the security system that allows a user in the current database to
work with data in the current database or execute specific statements.
Syntax :
Grant Privileges_Names ON Object To User
1. privileges_name: These are the access rights or privileges granted to the user.
2. Object: It is the name of the database object to which permissions are being granted. In the
case of granting privileges on a table, this would be the table name.
3. User: It is the name of the user to whom the privileges would be granted.
REVOKE: The REVOKE statement enables system administrators and to revoke the privileges from
MySQL accounts.
REVOKE privileges ON Object FROM User;
1. Object: It is the name of the database object from which permissions are being revoked. In the
case of revoking privileges from a table, this would be the table name.
2. User: It is the name of the user from whom the privileges are being revoked.
Experiment No. 3
Problem Statement: : Create tables for suitable database schema with constraint
like primary key, foreign key and NOT Null. Then design at least ten SQL queries
SQL DML statements: Insert, Select, Update, Delete using distinct and count
clause.
Theory:
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used to limit the type of data
that can go into a table. This ensures the accuracy and reliability of the data in the database.
1. NOT NULL Constraint: Ensures that a column cannot have NULL value. By default, a
column can hold NULL values. If you do not want a column to have a NULL value, then you
need to define such constraint on this column specifying that NULL is now not allowed for that
column.
Example: Create Table Student( Roll_No Int Primary Key,
F_Name Varchar(20) NOT NULL,
L_Name Varchar(20) NOT NULL );
2. Primary Key Constraint: A primary key is a field in a table which uniquely identifies each
row/record in a database table. Primary keys must contain unique values. A primary key
column cannot have NULL values. A table can have only one primary key, which may consist
of single or multiple fields. When multiple fields are used as a primary key, they are called a
composite key. Consider the above example.
3. Foreign Key Constraint: A foreign key is a key used to link two tables together. This is
sometimes called a referencing key. Foreign Key is a column or a combination of columns
whose values match a Primary Key in a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table.
Example: Create Table Country (Country_Code Primary Key, Name);
SQL IN Clause:
Syntax: SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
Consider the following database schema and creates tables with primary key, foreign key and not
null constraints.
Fifth Table
Create table Works_On (
W_Emp_ID int Not Null,
W_Pro_Num int ,
Dept_No int,
Relation Varchar(15),
Hrs int Not Null,
foreign key (W_Emp_ID) references Employe(Emp_ID),
foreign key (W_Pro_Num) references Project(Pro_No),
foreign key (Dept_No) references Dept(Dept_No)
);
Experiment No. 4
Problem Statement: : Consider suitable database schema and design five SQL
Nested Queries with/without where clause.
Theory:
What is Sub Quires?
In SQL a Subquery can be simply defined as a query within another query. In other words we can
say that a Subquery is a query that is embedded in WHERE clause of another SQL query.
Important rules for Subqueries:
- You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause,
FROM clause. Subqueries can be used with SELECT, UPDATE, INSERT, DELETE
statements along with expression operator. It could be equality operator or comparison
operator such as =, >, =, <= and Like operator.
- A subquery is a query within another query. The outer query is called as main query and
inner query is called as subquery.
- The subquery generally executes first, and its output is used to complete the query condition
for the main or outer query.
- Subquery must be enclosed in parentheses.
- Subqueries are on the right side of the comparison operator.
- ORDER BY command cannot be used in a Subquery. GROUPBY command can be used to
perform same function as ORDER BY command.
- Use single-row operators with singlerow Subqueries. Use multiple-row operators with
multiple-row Subqueries.
);
Note: Consider the database schema of Assignment No-03 and solve the following
Queries.
1. Find Employe ID of who works for Codepro project.
2. Find the First Name and Last Name of Employe who worked more than 200 hrs.
3. Find the Dept Name of project Jabalpur.
4. Select All data of employe who works as 'Jr.Eng.' and 'Sr.Eng.' and working Hrs are greater
than 120.
5. A. Create Backup Table EMP_Backup Contains Only Emp_ID,
F_Name,L_Name,Join_Date, Salary Columns.
B. Insert the values into EMP_Backup table with the help of sub query from Employe table.
6. Update the salary in EMP_Backup table by 30% who works for project ‘HAL’.
Experiment No. 5
Problem Statement: : Write a stored procedure to insert and retrieve data from
database table.
Theory:
Introduction:
A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular
computing language, stored in database. A procedure has a name, a parameter list, and SQL
statement(s). All most all relational database system supports stored procedure.
A stored procedure has , a (possibly empty) parameter list, and an SQL statement, which can
contain many more SQL statements. There is new syntax for local variables, error handling, loop con
trol, and IF conditions.
Advantages
Share logic with other applications. Stored procedures encapsulate functionality; this ensures
that data access and manipulation are coherent between different applications.
Isolate users from data tables. This gives you the ability to grant access to the stored
procedures that manipulate the data but not directly to the tables.
Provide a security mechanism. Considering the prior item, if you can only access the data
using the stored procedures defined, no one else can execute a DELETE SQL statement and
erase your data.
To improve performance because it reduces network traffic. With a stored procedure,
multiple calls can be melded into one.
Delimiter (//):
The delimiter is the character or string of characters that you'll use to tell the mySQL client that
you've finished typing in an SQL statement. For ages, the delimiter has always been a
semicolon. That, however, causes problems, because, in a stored procedure, one can have many
statements, and each must end with a semicolon.
2. Fine(Roll_no,Fine_Date,Amount)
Create Table Fine( Roll_no int References Borrower(Roll_NO), Fine_Date Date, Amount int);
mysql>Delimiter //
1. Create Procedure:
2. With IN Parameter :
Create Procedure BN_GateData1( IN ID Int)
Begin
Select * from Borrower
Where Roll_NO= ID;
End //
Run procedure:- mysql> call BN_GetData(105)//
4. Variables in Procedures:
Query- Insert new row into table Borrower
Solution: As per the Borrower table we required five variables to insert data into borrower table
4. IF-Then-Else
Create Procedure BN_IF_Then_Else(IN T1 Int)
Begin
IF(T1>101&&T1<107)
Then
select * from Borrower
where Roll_NO=T1;
Else
Select 'Not Found';
End If;
End//
5. Loops:
WHILE ... END WHILE
Create table Temp (val int)//
Query: Check the number of days (from date of issue), if days are between 15 to 30 then fine
amount will be Rs 5per day. If no. of days>30, per day fine will be Rs 50 per day & for days less
than 30, Rs. 5 per day. After submitting the book, status will change from Issue to Return. If
condition of fine is true, then details will be stored into fine table.
Delimiter //
/**************************************************************************
Description: Accpet Roll Number and Book Name and calculate Fine amount as per
Number of days. Handle Exception if Roll Number not found.
Create Date: 03-05-2022
**************************************************************************/
Create Procedure BRN( Roll_New int,Book_Name Varchar(15))
BEGIN
Declare X1 integer;
Declare Continue Handler for NOT FOUND
BEGIN
Select 'Not Found';
END;
Select DATEDIFF ( curdate(), Date_of_Issue) into X1 from Borrower where
Roll_NO=Roll_New;
IF (X1>15&&X1<30)
Then
Insert Into Fine Values( Roll_New, curdate(),(X1*5));
UPDATE Borrower SET Status='Return' WHERE Roll_NO=Roll_New;
End IF;
IF (X1>30)
Then
Insert into Fine values( Roll_New, curdate(),(X1*50));
UPDATE Borrower SET Status='Return' WHERE Roll_NO=Roll_New;
End IF ;
END;
//
Experiment No. 6
Theory:
In MySQL, a cursor allows row-by-row processing of the result sets. A cursor is used for the
result set and returned from a query. By using a cursor, you can iterate, or by step through the results
of a query and perform certain operations on each row. The cursor allows you to iterate through the
result set and then perform the additional processing only on the rows that require it.
In a cursor contains the data in a loop. Cursors may be different from SQL commands that
operate on all the rows in the returned by a query at one time.
There are some steps we have to follow, given below:
Declare a cursor
open a cursor statement
Fetch the cursor
close the cursor
1. Declaration of Cursor: To declare a cursor you must use the DECLARE statement. With
the help of the variables, conditions and handlers we need to declare a cursor before we can
use it. first of all we will give the cursor a name, this is how we will refer to it later in the
procedure. We can have more than one cursor in a single procedure so its necessary to give it
a name that will in some way tell us what its doing. We then need to specify the select statement
we want to associate with the cursor
Syntax: DECLARE cursor_name CURSOR FOR select_statement;
2. Open a cursor statement: For open a cursor we must use the open statement. If we want to
fetch rows from it you must open the cursor.
Syntax: OPEN cursor_name;
3. Cursor fetch statement: When we have to retrieve the next row from the cursor and move
the cursor to next row then you need to fetch the cursor.
Synatx : FETCH cursor_name INTO var_name;
If any row exists, then the above statement fetches the next row and cursor pointer moves ahead
to the next row.
4. Cursor close statement: By this statement closed the open cursor.
Syntax: CLOSE_name;
When an error occurs inside a stored procedure, it is important to handle it appropriately, such as
continuing or exiting the current code block’s execution, and issuing a meaningful error message.
MySQL provides an easy way to define handlers that handle from general conditions such as warnings
or exceptions to specific conditions e.g., specific error codes.
Declaring a handler
To declare a handler, you use the DECLARE HANDLER statement as follows:
DECLARE action HANDLER FOR condition_value statement;
The action accepts one of the following values:
CONTINUE: the execution of the enclosing code block ( BEGIN … END ) continues.
EXIT: the execution of the enclosing code block, where the handler is declared, terminates.
Query:
Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored
by students in examination is <=1500 and marks>=990 then student will be placed in distinction
category if marks scored are between 989 and900 category is first class, if marks 899 and 825
category is Higher Second Class. Write a PL/SQL block for using procedure created with above
requirement.
Stud_Marks(Roll_No,name, total_marks)
Result(Roll,Name, Class)
1.Stud_Marks
Mysql> Create Table Stud_Marks(Roll_No Int,Name Varchar(15),Total_Marks Int);
2. Result
Mysql> Create Table result(Roll_No Int,Class Varchar (15));
/********************************************************************************
**
Description: Read Data from Stud_Marks Table i.e roll number and marks and as per problem
statement categorization of marks and store the result into result table.
Create Date: 10-09-2022
*********************************************************************************
*/
Create Procedure Pro_Grade()
Begin
Declare v1 Int;
Declare v2 Int;
Declare noMoreRows int;
Declare Grade_Check cursor for select Roll_No,Total_Marks from Stud_Marks ;
Declare continue handler for not found set noMoreRows = 1;
Set noMoreRows = 0;
Open Grade_Check;
Loop_Name:Loop
Fetch Grade_Check into v1,v2;
If (v2>=990&&v2<=1500)
Then
Insert into result values(v1,'Distinction');
End If;
If(v2>=900&&v2<=989)
Then
Insert Into result values(v1,'First Class');
End If;
If(v2>=825&&v2<=899)
Then
Insert Into result values(v1,'Higher Sec.Class');
End If;
If noMoreRows Then
Leave Loop_Name;
End If;
Triggers:
In MySQL, a trigger is a stored program invoked automatically in response to an event such
as insert, update, or delete that occurs in the associated table. For example, you can define a trigger
that is invoked automatically before a new row is inserted into a table.
MySQL supports triggers that are invoked in response to the INSERT, UPDATE or DELETE event.
The SQL standard defines two types of triggers: row-level triggers and statement-level triggers.
A row-level trigger is activated for each row that is inserted, updated, or deleted. For
example, if a table has 100 rows inserted, updated, or deleted, the trigger is automatically
invoked 100 times for the 100 rows affected.
A statement-level trigger is executed once for each transaction regardless of how many
rows are inserted, updated, or deleted.
MySQL supports only row-level triggers. It doesn’t support statement-level triggers.
Query:
Write a database trigger on Library table. The System should keep track of the records that are
being updated or deleted. The old value of updated or deleted records should be added in
Library_Audit table.
Create Tables:
Mysql> Create table Library (Book_ID int, Title Varchar(20), Auther_Name Varchar(20),Dept
Varchar(20) );
Insert suitable data into Library table.
Mysql> Create table Lib_Audit(Book_ID Int,Old_Book_ID_Before_Update Int, Up_Del_Date Date,
Staus Vacrchar(20));
Create Trigger
1. Trigger for Update data of library table:
CREATE TRIGGER Lib_Trig_Update AFTER update ON Library
FOR EACH ROW
BEGIN
INSERT INTO Lib_Audit (Book_ID,Old_Book_ID_Before_Update,Up_Del_Date,Status)
Values( NEW.Book_ID,Old.Book_ID,Now(),'Update');
END;
Experiment No. 7
Theory:
In database management an aggregate function is a function where the values of multiple rows are
grouped together as input on certain criteria to form a single value of more significant meaning.
Include COUNT, SUM, MAX, MIN, and AVG.
Example 1: Find the maximum salary, the minimum salary, and the average salary among all
employees.
SELECT MAX(SALARY),MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE;
Example 2: Retrieve the total number of employees in the company , and the number of employees
in the 'Research' department.
a) SELECT COUNT (*)
FROM EMPLOYEE;
b) SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research’;
Grouping:
In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation.Each
subgroup of tuples consists of the set of tuples that have the same value for the grouping
attribute(s).The function is applied to each subgroup independently.
SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the
SELECT-clause
Example: For each department, retrieve the department number, the number of employees in the
department, and their average salary.
Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain
conditions.
The HAVING-clause is used for specifying a selection condition on groups (rather than on
individual tuples)
Example: For each project on which more than two employees work, retrieve the project number,
project name, and the number of employees who work on that project.
Q22: SELECT PNUMBER, PNAME, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2
Experiment No. 8
Problem Statement: : Design a queries for suitable database application using SQL
DML statements: all types of Join,Views.
Theory:
MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed
whenever two or more tables are joined in a SQL statement.
INNER JOIN (or sometimes called simple join)
LEFT OUTER JOIN (or sometimes called LEFT JOIN)
RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
The MySQL INNER JOIN would return the records where table1 and table2 intersect.
The MySQL LEFT OUTER JOIN would return the all records from table1 and only those records from table2
that intersect with table1.
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).
The syntax for the RIGHT OUTER JOIN in MySQL is:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those records
from table1 that intersect with table2.
Create Table
Create table for following Schema
Schema:
Supplier( Sup_ID- Primary Key,Sup_Name ,Address)
Parts(Part_ID- Primary Key,Part_Name,Part_Type)
Orders(Order_No,Part_ID,Sup_ID,Order_Date)
Catalog(P_ID,Part_Name,Cost, Available_Stock)
1. Find the Supplier ID’s and date of supply of supplier from the list of suppliers (Solve using
Join).
Experiment No. 9
This table is not normalized. We will see the problems that we face when a table in database
is not normalized.
Update anomaly: In the above table we have two rows for employee Rick as he belongs to
two departments of the company. If we want to update the address of Rick then we have to
update the same in two rows or the data will become inconsistent. If somehow, the correct
address gets updated in one department but not in other then as per the database, Rick would
be having two different addresses, which is not correct and would lead to inconsistent data.
Insert anomaly: Suppose a new employee joins the company, who is under training and
currently not assigned to any department then we would not be able to insert the data into the
table if Emp_Dept field doesn’t allow null.
Delete anomaly: Let’s say in future, company closes the department D890 then deleting the
rows that are having Emp_Dept as D890 would also delete the information of
employee Maggie since she is assigned only to this department.
To overcome these anomalies we need to normalize the data. In the next section we will
discuss about normalization.
Normalization
Here are the most commonly used normal forms:
First normal form(1NF)
Second normal form(2NF)
Third normal form(3NF)
Boyce & Codd normal form (BCNF)
First normal form (1NF)
A relation is said to be in 1NF (first normal form), if it doesn’t contain any multi-valued attribute.
In other words you can say that a relation is in 1NF if each attribute contains only atomic(single)
value only.
As per the rule of first normal form, an attribute (column) of a table cannot hold multiple values. It
should hold only atomic values.
Example: Let’s say a company wants to store the names and contact details of its employees. It
creates a table in the database that looks like this:
8812121212 ,
102 Jon Kanpur
9900012222
9990000123,
104 Lester Bangalore
8123450987
Two employees (Jon & Lester) have two mobile numbers that caused the Emp_Mobile field to have
multiple values for these two employees.
This table is not in 1NF as the rule says “each attribute of a table must have atomic (single) values”,
the Emp_Mobile values for employees Jon & Lester violates that rule.
To make the table complies with 1NF we need to create separate rows for the each mobile number in
such a way so that none of the attributes contains multiple values.
111 Maths 38
111 Physics 38
222 Biology 38
333 Physics 40
333 Chemistry 40
Teacher_Id Teacher_Age
111 38
222 38
333 40
Teacher_Subject table:
Teacher_Id Subject
111 Maths
111 Physics
222 Biology
333 Physics
333 Chemistry
Example: Let’s say a company wants to store the complete address of each employee, they create a
table named Employee_Details that looks like this:
Employee_Zip table:
The table is not in BCNF as neither Emp_Id nor Emp_Dept alone are keys.
To make the table comply with BCNF we can break the table in three tables like this:
Emp_Nationality table:
Emp_Id Emp_Nationality
1001 Austrian
1002 American
Emp_Dept table:
Emp_Dept_Mapping table:
Emp_Id Emp_Dept
1001 stores
Functional dependencies:
Emp_Id -> Emp_Nationality
Emp_Dept -> {Dept_Type, Dept_No_Of_Emp}
Candidate keys:
For first table: Emp_Id
For second table: Emp_Dept
For third table: {Emp_Id, Emp_Dept}
This table is now in BCNF as in both the functional dependencies left side part is a key.
Q-1. Write an SQL query to fetch “FIRST_NAME” from Worker table using the
alias name as <WORKER_NAME>.
Ans.
Select FIRST_NAME AS WORKER_NAME from Worker;
Q-2. Write an SQL query to fetch “FIRST_NAME” from Worker table in upper
case.
Ans.
The required query is:
Select upper(FIRST_NAME) from Worker;
Q-3. Write an SQL query to fetch unique values of DEPARTMENT from Worker
table.
Ans.
The required query is:
Select distinct DEPARTMENT from Worker;
Q-4. Write an SQL query to print the first three characters of FIRST_NAME from
Worker table.
Ans.
Select substring(FIRST_NAME,1,3) from Worker;
Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the first name
column ‘Amitabh’ from Worker table.
Ans.
The required query is:
Select INSTR(FIRST_NAME, BINARY'a') from Worker where FIRST_NAME = 'Amitabh';
Notes.
The INSTR method is in case-sensitive by default.
Using Binary operator will make INSTR work as the case-sensitive function.
Q-6. Write an SQL query to print the FIRST_NAME from Worker table after
removing white spaces from the right side.
Ans.
The required query is:
Select RTRIM(FIRST_NAME) from Worker;
Q-7. Write an SQL query to print the DEPARTMENT from Worker table after
removing white spaces from the left side.
Ans.
The required query is:
Select LTRIM(DEPARTMENT) from Worker;
Q-8. Write an SQL query that fetches the unique values of DEPARTMENT from
Worker table and prints its length.
Ans.
The required query is:
Select distinct length(DEPARTMENT) from Worker;
Q-9. Write an SQL query to print the FIRST_NAME from Worker table after
replacing ‘a’ with ‘A’.
Ans.
The required query is:
Select REPLACE(FIRST_NAME,'a','A') from Worker;
Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME from
Worker table into a single column COMPLETE_NAME. A space char should
separate them.
Ans.
The required query is:
Select CONCAT(FIRST_NAME, ' ', LAST_NAME) AS 'COMPLETE_NAME' from Worker;
Q-11. Write an SQL query to print all Worker details from the Worker table order
by FIRST_NAME Ascending.
Ans.
The required query is:
Select * from Worker order by FIRST_NAME asc;
Q-12. Write an SQL query to print all Worker details from the Worker table order
by FIRST_NAME Ascending and DEPARTMENT Descending.
Ans.
The required query is:
Select * from Worker order by FIRST_NAME asc,DEPARTMENT desc;
Q-13. Write an SQL query to print details for Workers with the first name as
“Vipul” and “Satish” from Worker table.
Ans.
The required query is:
Select * from Worker where FIRST_NAME in ('Vipul','Satish');
Q-14. Write an SQL query to print details of workers excluding first names, “Vipul”
and “Satish” from Worker table.
Ans.
The required query is:
Select * from Worker where FIRST_NAME not in ('Vipul','Satish');
Q-15. Write an SQL query to print details of Workers with DEPARTMENT name as
“Admin”.
Ans.
The required query is:
Select * from Worker where DEPARTMENT like 'Admin%';
Q-16. Write an SQL query to print details of the Workers whose FIRST_NAME
contains ‘a’.
Ans.
The required query is:
Select * from Worker where FIRST_NAME like '%a%';
Q-17. Write an SQL query to print details of the Workers whose FIRST_NAME ends
with ‘a’.
Ans.
Q-18. Write an SQL query to print details of the Workers whose FIRST_NAME ends
with ‘h’ and contains six alphabets.
Ans.
The required query is:
Select * from Worker where FIRST_NAME like '_____h';
Q-19. Write an SQL query to print details of the Workers whose SALARY lies
between 100000 and 500000.
Ans.
The required query is:
Select * from Worker where SALARY between 100000 and 500000;
Q-20. Write an SQL query to print details of the Workers who have joined in
Feb’2014.
Ans.
The required query is:
Select * from Worker where year(JOINING_DATE) = 2014 and month(JOINING_DATE) = 2;
Q-21. Write an SQL query to fetch the count of employees working in the department
‘Admin’.
Ans.
The required query is:
SELECT COUNT(*) FROM worker WHERE DEPARTMENT = 'Admin';
Q-22. Write an SQL query to fetch worker names with salaries >= 50000 and <=
100000.
Ans.
The required query is:
SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) As Worker_Name, Salary
FROM worker
WHERE WORKER_ID IN
(SELECT WORKER_ID FROM worker
WHERE Salary BETWEEN 50000 AND 100000);
Q-23. Write an SQL query to fetch the no. of workers for each department in the
descending order.
Ans.
The required query is:
SELECT DEPARTMENT, count(WORKER_ID) No_Of_Workers
FROM worker
GROUP BY DEPARTMENT
ORDER BY No_Of_Workers DESC;
Q-24. Write an SQL query to print details of the Workers who are also Managers.
Ans.
The required query is:
SELECT DISTINCT W.FIRST_NAME, T.WORKER_TITLE
FROM Worker W
INNER JOIN Title T
ON W.WORKER_ID = T.WORKER_REF_ID
AND T.WORKER_TITLE in ('Manager');
Q-25. Write an SQL query to fetch duplicate records having matching data in some
fields of a table.
Ans.
The required query is:
SELECT WORKER_TITLE, AFFECTED_FROM, COUNT(*)
FROM Title
GROUP BY WORKER_TITLE, AFFECTED_FROM
HAVING COUNT(*) > 1;
Q-26. Write an SQL query to show only odd rows from a table.
Ans.
Q-27. Write an SQL query to show only even rows from a table.
Ans.
The required query is:
SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) = 0;
Q-28. Write an SQL query to clone a new table from another table.
Ans.
The general query to clone a table with data is:
SELECT * INTO WorkerClone FROM Worker;
The general way to clone a table without information is:
SELECT * INTO WorkerClone FROM Worker WHERE 1 = 0;
An alternate way to clone a table (for MySQL) without is:
CREATE TABLE WorkerClone LIKE Worker;
Q-30. Write an SQL query to show records from one table that another table does
not have.
Ans.
The required query is:
SELECT * FROM Worker
MINUS
SELECT * FROM Title;
Q-31. Write an SQL query to show the current date and time.
Ans.
Q-33. Write an SQL query to determine the nth (say n=5) highest salary from a table.
Ans.
The following MySQL query returns the nth highest salary:
SELECT Salary FROM Worker ORDER BY Salary DESC LIMIT n-1,1;
The following SQL Server query returns the nth highest salary:
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP n Salary
FROM Worker
ORDER BY Salary DESC
)
ORDER BY Salary ASC;
Q-34. Write an SQL query to determine the 5th highest salary without using TOP or
limit method.
Ans.
The following query is using the correlated subquery to return the 5th highest salary:
SELECT Salary
FROM Worker W1
WHERE 4 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Use the following generic method to find nth highest salary without using TOP or limit.
SELECT Salary
FROM Worker W1
WHERE n-1 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Q-35. Write an SQL query to fetch the list of employees with the same salary.
Ans.
The required query is:
Select distinct W.WORKER_ID, W.FIRST_NAME, W.Salary
from Worker W, Worker W1
where W.Salary = W1.Salary
and W.WORKER_ID != W1.WORKER_ID;
Q-36. Write an SQL query to show the second highest salary from a table.
Ans.
The required query is:
Select max(Salary) from Worker
where Salary not in (Select max(Salary) from Worker);
Q-37. Write an SQL query to show one row twice in results from a table.
Ans.
The required query is:
select FIRST_NAME, DEPARTMENT from worker W where W.DEPARTMENT='HR'
union all
select FIRST_NAME, DEPARTMENT from Worker W1 where W1.DEPARTMENT='HR';
Q-39. Write an SQL query to fetch the first 50% records from a table.
Ans.
The required query is:
SELECT *
FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);
Q-40. Write an SQL query to fetch the departments that have less than five people in
it.
Ans.
The required query is:
SELECT DEPARTMENT, COUNT(WORKER_ID) as 'Number of Workers' FROM Worker
GROUP BY DEPARTMENT HAVING COUNT(WORKER_ID) < 5;
Q-41. Write an SQL query to show all departments along with the number of people
in there.
Ans.
The following query returns the expected result:
Q-42. Write an SQL query to show the last record from a table.
Ans.
The following query will return the last record from the Worker table:
Select * from Worker where WORKER_ID = (SELECT max(WORKER_ID) from Worker);
Q-44. Write an SQL query to fetch the last five records from a table.
Ans.
The required query is:
SELECT * FROM Worker WHERE WORKER_ID <=5
UNION
SELECT * FROM (SELECT * FROM Worker W order by W.WORKER_ID DESC) AS W1
WHERE W1.WORKER_ID <=5;
Q-45. Write an SQL query to print the name of employees having the highest salary
in each department.
Ans.
The required query is:
SELECT t.DEPARTMENT,t.FIRST_NAME,t.Salary from(SELECT max(Salary) as
TotalSalary,DEPARTMENT from Worker group by DEPARTMENT) as TempNew
Inner Join Worker t on TempNew.DEPARTMENT=t.DEPARTMENT
and TempNew.TotalSalary=t.Salary;
Q-46. Write an SQL query to fetch three max salaries from a table.
Ans.
The required query is:
SELECT distinct Salary from worker a WHERE 3 >= (SELECT count(distinct Salary) from
worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;
Q-47. Write an SQL query to fetch three min salaries from a table.
Ans.
The required query is:
SELECT distinct Salary from worker a WHERE 3 >= (SELECT count(distinct Salary) from
worker b WHERE a.Salary >= b.Salary) order by a.Salary desc;
Q-48. Write an SQL query to fetch nth max salaries from a table.
Ans.
The required query is:
SELECT distinct Salary from worker a WHERE n >= (SELECT count(distinct Salary) from
worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;
Q-49. Write an SQL query to fetch departments along with the total salaries paid for
each of them.
Ans.
The required query is:
SELECT DEPARTMENT, sum(Salary) from worker group by DEPARTMENT;
Q-50. Write an SQL query to fetch the names of workers who earn the highest salary.
Ans.
The required query is:
SELECT FIRST_NAME, SALARY from Worker WHERE SALARY=(SELECT max(SALARY)
from Worker);