DBMS Lab Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

1

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
2

TABLE OF CONTENTS:
Executive Summary:..............................................................................................................................4
Phase I:..................................................................................................................................................6
What is ER diagram?..........................................................................................................................6
WHY CHOSE COMPANY MANAGEMENT SYSTEM?............................................................................7
Reducing into tables..............................................................................................................................8
2. Phase II..............................................................................................................................................9
2.1 DDL Commands and Table Creation............................................................................................9
2.1.1 Employee Table....................................................................................................................9
2.1.2 Create Department table....................................................................................................10
2.1.3 Create Project Table...........................................................................................................10
2.2 Insert in the tables.....................................................................................................................11
2.2.1 Insert in Employee Table....................................................................................................11
2.2.2 Result of INSERT command on Employee table..................................................................13
2.2.3 Insert in Department Table.................................................................................................15
2.2.4 Result of INSERT command on Department table..............................................................16
2.2.5 Insert in Project table..........................................................................................................17
2.2.6 Result of INSERT in Project table........................................................................................18
3. Phase III...........................................................................................................................................19
3.1 Use of DML command...............................................................................................................19
a. Use of DELETE......................................................................................................................19
b. Use of ALTER TABLE add/drop:............................................................................................21
c. Use of UPDATE.....................................................................................................................22
d. Use of SELECT : COLUMNS :.................................................................................................23
e. Use of SELECT ‘WHERE’:.......................................................................................................24
3.2 Aggregate Functions..................................................................................................................25
a. Use of MAX ():......................................................................................................................25
b. Use of MIN ():.......................................................................................................................25
c. Use of COUNT ():..................................................................................................................26
d. Use of SUM ():......................................................................................................................26
f. Use of AVG ():......................................................................................................................27
3.3 Some Important key words:......................................................................................................27
Use of AND keyword:...................................................................................................................28
Use of BETWEEN keyword:..........................................................................................................29
Use of OR keyword:.....................................................................................................................30
Use of IN keyword:......................................................................................................................31

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
3

Use of GROUP BY keyword:.........................................................................................................32


Use of ORDER BY keyword:..........................................................................................................34
Use of LIMIT keyword:.................................................................................................................35
4. Phase IV...........................................................................................................................................36
4.1 Joins/Types of Joins...................................................................................................................36
4.1.1 Adding FOREIGN KEY at Employee table for Joins..............................................................36
4.1.2 INSERT DepartmentID on Employee table..........................................................................36
INNER JOIN..................................................................................................................................37
LEFT JOIN.....................................................................................................................................38
RIGHT JOIN..................................................................................................................................39
FULL OUTER JOIN.........................................................................................................................40
4.2 Some Important Relationship Queries:......................................................................................41
Sample 1:.....................................................................................................................................41
Sample 2:.....................................................................................................................................42
Sample 3:.....................................................................................................................................43
Sample 4:.....................................................................................................................................43
Sample 5:.....................................................................................................................................44
Sample 6:.....................................................................................................................................44
Sample 7:.....................................................................................................................................45
Conclusion:..........................................................................................................................................46

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
4

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
5

EXECUTIVE SUMMARY:

Introduction to Relational Database Management with MySQL

This executive summary provides an overview of the key topics covered in our discussion on working
with a relational database using MySQL. It highlights the fundamental concepts, SQL commands, and
database operations we explored.

1) Database Structure: We began by understanding the core structure of a relational database.


Tables were identified as the building blocks for storing data, consisting of columns that define
the attributes or properties of the data. We discussed the significance of primary keys, which
uniquely identify each record and ensure data integrity.

2) Establishing Relationships: We explored the importance of establishing relationships between


tables through foreign keys. These keys enable referential integrity and facilitate the proper
organization and retrieval of data across related tables. The concept of one-to-one, one-to-
many, and many-to-many relationships was introduced.

3) SQL Commands: We delved into essential SQL commands used for database operations. We
covered the CREATE TABLE command for table creation, INSERT for data insertion, SELECT for
data retrieval, UPDATE for data modification, DELETE for data removal, and ALTER TABLE for
table alteration.

4) Joining Tables: We discussed the various types of joins, such as INNER JOIN, LEFT JOIN, RIGHT
JOIN, and simulating a FULL OUTER JOIN. Joins allow for the combination of data from multiple
tables based on related columns, enabling comprehensive data analysis and reporting.

5) Sorting and Limiting Results: We explored the ORDER BY command, which facilitates sorting
query results in ascending or descending order. Additionally, we examined the LIMIT keyword,
which restricts the number of rows returned by a query, aiding in pagination or retrieving a
specific subset of data.

6) Aggregate Functions: We covered a range of aggregate functions, including MAX, MIN, COUNT,
SUM, and AVG. These functions perform calculations on columns or groups of rows, providing
valuable insights and statistical summaries of the data.

7) Data Filtering: We discussed the application of the WHERE clause with comparison operators
and logical operators to filter data based on specified conditions. We also examined the usage of
the IN operator for filtering data against multiple values.

8) Grouping and Summarizing Data: The GROUP BY clause was introduced, allowing for the
grouping of rows based on one or more columns. This clause is commonly used with aggregate
functions to perform calculations on grouped data, providing valuable summaries and insights.

By covering these fundamental concepts and SQL operations, this discussion aimed to provide a solid
foundation in relational database management with MySQL. Understanding these principles

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
6

empowers users to design effective databases, manipulate and query data efficiently, and derive
meaningful insights from their data resources.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
7

PHASE I:

What is ER diagram?
Entity-Relationship (ER) diagrams serve as powerful tools to visually represent these relationships
and capture the structure of a database. In this context, we have developed a simple ER diagram
that encompasses various requirements, including multiple relations, different attribute types, the
concept of generalization/specialization, and cardinality mapping.

The ER diagram presented here comprises three main relations: Employees, Departments, and
Projects. Each relation encapsulates specific information relevant to the organization's operations
and management. The Employees relation stores essential details about the workforce, such as
employee ID, name, position, salary, department id and hire date. Additionally, the Departments
relation contains data regarding different departments within the organization, including
department ID, name, and location. Furthermore, the Projects relation captures information about
various projects undertaken by the organization, including project ID, Project Name, employee id
and department ID.

Figure 1: ER Diagram of a company


In the above figure of ER diagram, the rectangle shape represent entity. The oval shape represents
attributes of an entity and the diamond shape represent the relationship between the entity. Also, 1
to 1 means one to one relations, 1 to M means one to many relations and M to M means many to

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
8

many relations between the entities. Also the underlined attributes represents “Primary KEY”
whereas the italics underlined attributes represent “Foreign KEY” in the ER diagram.

WHY CHOSE COMPANY MANAGEMENT SYSTEM?

The choice of the "Employee," "Department," and "Project" tables in a Company Management
system is based on the fundamental components required to manage employee data, department
information, and project details within an organization. These tables provide a foundation for
various features and functionalities that support effective company management. Some of the key
features and benefits they offer include:

1. Employee Management: The "Employee" table allows storing and organizing essential
employee information such as employee ID, name, contact details, position, salary, and
other relevant attributes. It facilitates employee record keeping, tracking, and retrieval,
enabling HR processes such as employee onboarding, payroll management, performance
evaluation, and resource allocation.

2. Department Management: The "Department" table stores department-related details such


as department ID, name, location, and other relevant attributes. It enables effective
organization and categorization of departments, allowing for efficient management of
department-specific tasks, team assignments, hierarchy, and reporting structures.

3. Project Management: The "Project" table captures project-related information, including


project ID, name, duration, associated employees, and department involvement. It facilitates
project planning, tracking, and collaboration, enabling project managers to assign resources,
monitor progress, allocate budgets, and ensure timely project completion.

4. Data Integration and Reporting: The interconnectivity between the "Employee,"


"Department," and "Project" tables allows for seamless integration and extraction of data
across different entities. This integration facilitates generating comprehensive reports,
analytics, and insights related to employee performance, departmental efficiency, project
status, resource utilization, and overall company productivity.

5. Relationship Management: The tables establish relationships and associations between


employees, departments, and projects. This enables efficient management of employee-
team assignments, departmental affiliations, project ownership, and cross-department
collaborations, fostering effective teamwork, communication, and coordination.

6. Scalability and Flexibility: The structured nature of these tables allows for scalability as the
organization grows, accommodating an increasing number of employees, departments, and
projects. Additionally, the tables can be easily adapted and customized to meet specific
company requirements, making the system flexible and adaptable to evolving business
needs.

Overall, the "Employee," "Department," and "Project" tables form a foundational framework for
managing various aspects of company operations, promoting efficient workforce management,

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
9

effective departmental coordination, and streamlined project execution. They enable better
decision-making, resource allocation, and performance evaluation, contributing to improved
organizational efficiency and productivity

REDUCING INTO TABLES

Employees
EmployeeID (PK) Department
Name
DepartmentID (PK)
Position
Name
Salary
HireDate Location
HourlyWages
DepartmentID (FK)

Projects

ProjectID (PK)
ProjectName
EmployeeID (FK)
DepartmentID (FK)

Table 1: Reducing the ER Diagram into table form

Transforming an ER diagram into a tabular format plays a crucial role in database design and
implementation. It facilitates the conversion of the conceptual model and interconnections
illustrated in the ER diagram into a tangible representation suitable for utilization within database
management systems. By structuring the data into tables, it becomes easier to organize and store
information effectively. Each table corresponds to an entity depicted in the ER diagram, while the
columns within the table represent the attributes associated with that particular entity.

This process of breaking down entities and their attributes into separate tables enables the
establishment of well-defined and organized relationships between the data elements.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
10

2. PHASE II
2.1 DDL Commands and Table Creation

2.1.1 Employee Table

The Employee table is created with seven columns:

 EmployeeID is defined as an INT data type and is set as the primary key of the table. It uniquely
identifies each employee.
 Name is defined as a VARCHAR(225) data type. It stores the name of the employee.
 Position is defined as a VARCHAR(225) data type. It stores the job position or title of the
employee.
 Salary is defined as a DECIMAL(10, 2) data type. It represents the employee's salary.
 HireDate is defined as a DATE data type. It stores the location or office where the employee is
based.
 VacationDays is defined as an INT data type. It indicates the number of vacation days allocated
to the employee.
 HourlyRate is defined as a DECIMAL(10, 2) data type. It represents the employee's hourly rate,
applicable for hourly workers.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
11

2.1.2 Create Department table

The Department table is created with three columns:

 DepartmentID is defined as an INT data type and is set as the primary key of the table. It
uniquely identifies each department.
 Name is defined as a VARCHAR(50) data type. It stores the name or title of the department.
 Location is defined as a VARCHAR(50) data type. It stores the physical location or address of the
department.

2.1.3 Create Project Table

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
12

The Project table is created with four columns:

 ProjectID is defined as an INT data type and is set as the primary key of the table. It uniquely
identifies each project.
 ProjectName is defined as a VARCHAR(50) data type. It stores the name or title of the project.
 EmployeeID is defined as an INT data type. It establishes a relationship with the Employee table
by referencing the EmployeeID of the employee assigned to the project.
 DepartmentID is defined as an INT data type. It establishes a relationship with the Department
table by referencing the DepartmentID of the department to which the project belongs.

2.2 Insert in the tables


2.2.1 Insert in Employee Table
By executing this INSERT statement, the employee data is inserted into the Employee table, making
it available for retrieval and further analysis within the organization's database. To insert data into
the Employee table, you can use the following SQL INSERT statement as an example:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
13

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
14

This above example inserts rows of employee data into the Employee table. Each row represents an
employee, and the values provided correspond to the respective attributes of the table. Please note
that the EmployeeID column is assumed to be an auto-incrementing primary key, so there is no
values in the INSERT statement above. You may need to adjust the values according to your specific
employee data.

Also, note that the HourlyRate column has a NULL value in the different rows, indicating that those
employees are not paid on an hourly basis.

2.2.2 Result of INSERT command on Employee table

After executing the INSERT statement to add different employee data on the Employee table, the
result would be the successful insertion of the provided data into the table. The Employee table
would now contain the following rows:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
15

The Employee table now consists of three records representing the inserted employees. Each record
corresponds to an employee and contains the provided values for their attributes, such as
EmployeeID, Name, Position, Salary, HireDate, VacationDays, and HourlyRate.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
16

2.2.3 Insert in Department Table

To insert data into the Department table, you can use the following SQL INSERT statement as an
example:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
17

2.2.4 Result of INSERT command on Department table


By executing this INSERT statement, the department data is inserted into the Department table,
resulting in the following table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
18

After the successful execution of the INSERT statement, the Department table now contains the
inserted department records. Each row represents a department and includes the values provided
for the respective attributes: department_id, name, and location.

This insertion of department data into the Department table allows for the organization and
management of departments within the organization. It provides a foundation for linking employees,
projects, and other data related to specific departments, enabling efficient retrieval and analysis of
department-related information.

2.2.5 Insert in Project table

To insert data into the Project table, you can use the following SQL INSERT statement as an example:

Each row represents a project, and the values provided correspond to the respective attributes of
the table.

Let's break down the INSERT statement by taking the first three query as an example:

 The first row represents a project with a project_id of 1 and a name of 'Project A’. It is associated
with an employee_id of 1 (referring to an employee in the Employee table) and a department_id
of 4 (referring to a department in the Department table).
 The second row represents a project with a project_id of 2 and a name of 'Project B’. It is
associated with an employee_id of 7 and a department_id of 6.
 The third row represents a project with a project_id of 3 and a name of ‘Project C’. It is
associated with an employee_id of 3 and a department_id of 9.

By executing this INSERT statement, the project data is inserted into the Project table, allowing you
to track and manage projects within your organization.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
19

2.2.6 Result of INSERT in Project table

After executing the INSERT statement to populate the Project table, the result would be the
successful insertion of the provided data into the table. The Project table would now contain the
following rows:

The Project table now consists of above records representing the inserted projects. Each record
corresponds to a project and includes the values provided for the attributes: ProjectID, name,
EmployeeID, and DepartmentID.

By inserting the data into the Project table, you have successfully added project information,
enabling further management, analysis, and retrieval of project-related data within your
organization's database.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
20

3. PHASE III
3.1 Use of DML command

a. Use of DELETE

 To use the DELETE command on the Department table, you can specify the condition for
deletion using a WHERE clause. Here's an example of how you can delete a department
from the table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
21

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
22

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
23

The row corresponding to the department with ‘Name ‘Consulting’ and its associated data would no
longer exist in the table.

It's important to note that the DELETE command permanently removes the specified rows from the
table, so exercise caution when using it to avoid unintended deletions.

b. Use of ALTER TABLE add/drop:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
24

Executing this SQL statement will remove the HourlyRate column from the Employee table.

After executing the above command, the Employee table will be altered, and the HourlyRate column
will no longer exist in the table. The resulting table structure would exclude the HourlyRate column.
It's important to note that the ADD/DROP COLUMN operation is a permanent action, and any data
stored in the dropped column will be lost. Make sure to have a backup of your data or ensure that
the column is no longer needed before performing this operation.

c. Use of UPDATE

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
25

To use the UPDATE command on the Department table, you can modify the values of specific
attributes within existing rows. Here's an example of how you can update the location of a
department:

In the above example, the UPDATE command is used to change the location of the department with
department_id equal to 1 to "CSIT" and “NewDelhi”.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
26

After executing this command, the department's location will be updated in the Department table.
The resulting table would look like above. The row corresponding to the department with
department_id 1 will have its Name changed to "CSIT" and Location changed to "Neww Delhi"..

d. Use of SELECT : COLUMNS :

To retrieve data from the Employee table, you can use the SELECT statement. Here's an
example of how you can select all columns from the Employee table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
27

Executing this SELECT statement will fetch all the selected rows and columns from the Employee
table.

The result of the SELECT query will be a table-like structure showing the selected employee data in
the Employee table, including all columns such as EmployeeID, Name, Position and Salary present in
the table.

e. Use of SELECT ‘WHERE’:

Here's an example of how you can use the SELECT statement with a WHERE clause to
retrieve specific data from the Employee table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
28

In the above example, the SELECT statement is used to fetch the Employee ID, name, position,
salary, Hire Date and Vacation Days columns from the Employee table. The WHERE clause is added
to filter the results based on the condition position = 'Software Engineer', which means only
employees with the position 'Software Engineer' will be included in the result.

You can customize the SELECT statement further by modifying the columns to retrieve or by
specifying different conditions in the WHERE clause to filter the data based on your specific
requirements.

3.2 Aggregate Functions

a. Use of MAX ():

The MAX function is used in conjunction with the SELECT statement to retrieve the maximum value
from a specific column in a table. Here's an example of how you can use the MAX function:

In the above example, the MAX function is used to find the maximum value of the salary column in
the Employee table. The result will include a single row with a column alias MAX(salary) that
represents the maximum salary value found in the table.

b. Use of MIN ():

The MIN function is used in conjunction with the SELECT statement to retrieve the minimum value
from a specific column in a table. Here's an example of how you can use the MIN function:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
29

In the above example, the MIN function is used to find the minimum value of the salary column in
the Employee table. The result will include a single row with a column alias MIN(salary) that
represents the minimum salary value found in the table.

c. Use of COUNT ():

The COUNT function is used in conjunction with the SELECT statement to retrieve the number of
rows or non-null values in a specific column. Here are a couple of examples of how you can use the
COUNT function:

In the above example, the COUNT function with the asterisk (*) is used to count the total number of
rows in the Employee table. The result will include a single row with a column alias count(*)
representing the count of rows in the table.

In this example, the COUNT function is applied to the Vacaation Days column in the Employee table.
It counts the number of non-null values in that column. The result will include a single row with a
column alias total_employees_with_Vacations representing the count of employees who have a
non-null Vacation Days.

d. Use of SUM ():

The SUM function is used in conjunction with the SELECT statement to calculate the sum of values in
a specific column. Here's an example of how you can use the SUM function on specific coloums:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
30

In the above example, the SUM function is used to calculate the total vacation days by summing up
the values in the vacation days column of the Employee table. The result will include a single row
with a column alias Total_Vacation, representing the sum of vacation days for all employees.

f. Use of AVG ():

The AVG function is used in conjunction with the SELECT statement to calculate the average value of
a specific column. Here's an example of how you can use the AVG function of employees table:

In the above example, the AVG function is used to calculate the average salary by calculating the
mean value of the salary column in the Employee table. The result will include a single row with a
column alias AVG(Salary), representing the average salary of all employees.

3.3 Some Important key words:

In MySQL, there are several important keywords that are used to perform various operations and
define the structure and behavior of your database. Some of the essential keywords in MySQL
include:

 AND
 BETWEEN
 OR
 IN
 GROUP BY
 ORDER BY
 LIMIT

These are just a few examples of important keywords in MySQL. The MySQL documentation
provides a comprehensive list of keywords along with their usage and syntax

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
31

Use of AND keyword:

The AND keyword is used in conjunction with the WHERE clause to combine multiple conditions in a
query. Here's an example of how you can use the AND keyword to filter data based on the position
and salary criteria in the Employee table:

In the above example, the SELECT statement retrieves all columns from the Employee table. The
WHERE clause is used to filter the data based on two conditions:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
32

I. The condition position = 'Sales Manager' specifies that only employees with the position
'Manager' will be included in the result.
II. The condition salary = 5200 specifies that only employees with a salary equals to
5200.00 will be included in the result.

The AND keyword is used to combine these two conditions, ensuring that both conditions must be
true for a row to be included in the result.

You can customize the SELECT statement further by specifying different columns or modifying the
conditions in the WHERE clause to filter the data based on your specific requirements.

Use of BETWEEN keyword:

The BETWEEN keyword is used in conjunction with the WHERE clause to specify a range of values for
a column in a query. Here's an example of how you can use the BETWEEN keyword to filter data
based on a salary range in the Employee table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
33

In the above example, the SELECT statement retrieves all columns from the Employee table. The
WHERE clause is used to filter the data based on the salary range. The condition salary BETWEEN
4300.00 AND 4600.00 specifies that only employees with a salary between 4300.00 and 4600.00
(inclusive) will be included in the result.

You can customize the SELECT statement further by specifying different columns or modifying the
salary range in the WHERE clause to filter the data based on your specific requirements,

Use of OR keyword:

The OR keyword is used in conjunction with the WHERE clause to specify multiple conditions, where
at least one of the conditions must be true for a row to be included in the result. Here's an example
of how you can use the OR keyword to filter data based on the name and position criteria in the
Employee table:

In the above example, the SELECT statement retrieves all columns from the Employee table. The
WHERE clause is used to filter the data based on two conditions:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
34

 The condition name = 'Aakash Gole’ specifies that rows where the name is 'Aakash Gole’ will be
included in the result.
 The condition position = 'Sales Manager' specifies that rows where the position is ‘Sales
Manager’ will be included in the result.

When executing the SELECT query with the OR condition, the result would include the rows where at
least one of the conditions is true. The OR keyword is used to combine these two conditions,
indicating that a row will be included in the result if either of the conditions is true.

Use of IN keyword:

The IN keyword is used in conjunction with the WHERE clause to check if a value matches any value
in a list. Here's an example of how you can use the IN keyword to filter data based on salary values in
the Employee table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
35

In the above example, the SELECT statement retrieves all columns selected (Name and Position)
from the Employee table. The WHERE clause is used to filter the data based on the salary values. The
condition salary IN (4800,5200) specifies that only employees with a salary of either 4800 or 5200will
be included in the result.

You can customize the SELECT statement further by specifying different columns or modifying the
salary values in the WHERE clause to filter the data based on your specific requirements. The IN
keyword allows you to easily match values against a list of values, providing flexibility in filtering
rows based on multiple options.

Use of GROUP BY keyword:

The GROUP BY command is used to group rows in a query result based on one or more columns.
Here's an example of how you can use the GROUP BY command in conjunction with the SUM
function to calculate the total salary for each position in the Employee table:

GROUP BY with COUNT keyword:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
36

In the above example, the SELECT statement retrieves the salary column and counts the number of
employees for each unique salary value. The result is grouped by the salary column.

The GROUP BY clause is used to specify the column(s) by which the result should be grouped. In this
case, the result will be grouped by the salary column. The COUNT(*) function is used to count the
number of employees for each unique salary value.

The result of the SELECT query will display the unique salary values along with the corresponding
employee count. In this above case, the result shows the count of employees for each unique salary
value based on the data in the Employee table. Each salary value has one employee associated with
it

GROUP BY using SUM keyword:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
37

In the above example, the SELECT statement retrieves the position column and calculates the sum of
salary for each unique position. The result is grouped by the position column.

The GROUP BY clause is used to specify the column(s) by which the result should be grouped. In this
case, the result will be grouped by the position column. The SUM function is used to calculate the
total salary for each position.

The result of the SELECT query will display the unique positions along with their corresponding total
salary. For example:

In this case, the result shows the total salary for each position based on the data in the Employee
table. The salaries for the 'Software Engineer', 'Sales Manager', and 'Financial Analyst' and so on
positions are calculated and displayed in the result.

You can customize the SELECT statement further by including additional columns or applying other
aggregate functions (such as MIN, MAX, AVG) to calculate different statistics based on the grouped
data. The GROUP BY command is useful for generating summary information and performing
calculations on groups of data within a table.

Use of ORDER BY keyword:

The ORDER BY command is used to sort the result of a query in ascending or descending order based
on one or more columns. Here's an example of how you can use the ORDER BY command in a
SELECT statement:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
38

In this case, the result will be sorted first by the name column in ascending order (A to Z). The ORDER
BY command is flexible and allows you to customize the sorting behavior based on your specific
requirements. It is commonly used to sort query results and present the data in a desired order.

Use of LIMIT keyword:

The LIMIT keyword is used to restrict the number of rows returned by a query. It allows you to
specify a limit on the number of rows to be retrieved from a table. Here's an example of how you
can use the LIMIT keyword in the Employee table:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
39

In the above example, the SELECT statement retrieves Employee ID, Name, Position and Vacation
Days from the Employee table. The LIMIT clause is used to restrict the result to only the first 13
rows.

The result of the SELECT query will display the first 13 rows from the Employee table, based on the
order determined by the database.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
40

4. PHASE IV
4.1 Joins/Types of Joins

4.1.1 Adding FOREIGN KEY at Employee table for Joins

Foreign keys play a crucial role in ensuring data integrity and establishing relationships between
tables in a relational database. When performing a join operation, foreign keys serve the following
important purposes: The importance of foreign keys while making joins are

Relationship establishment, Data consistency and integrity, Query optimization, Clarity and
understanding of data model, Data validation and constraint enforcement.

4.1.2 INSERT DepartmentID on Employee table

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
41

INNER JOIN

By using INNER JOIN, you can combine the data from multiple tables based on a common column,
allowing you to retrieve information that is related and relevant across different tables., the INNER
JOIN command to combine the Department and Employee tables based on the department ID:

In the above example, the SELECT statement retrieves the employee_id and name columns from the
Employee table, as well as the Location column from the Department table (aliased as Location). The
INNER JOIN clause is used to join the Employee and Department tables based on the department_id
column.

 Employees and Department are the names of the tables being joined.
 Employees.DepartmentID and Department.DepartmentID represent the related columns
between the two tables.

The result of the SELECT query will display the employee ID, name, and corresponding department
nlocation for each employee. The join operation ensures that only the records with matching
department IDs between the Employee and Department tables are included in the result set.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
42

LEFT JOIN

By using LEFT JOIN, you can combine the data from the Employee and Department tables while
including all records from the Employee table, even if there is no corresponding department
information. This allows you to retrieve employee details along with their department location,
when available.

In the above example, the SELECT statement retrieves the employee_id, name, position columns
from the Employee table, and the location column from the Department table. The LEFT JOIN clause
is used to join the Employee and Department tables based on the department_id column.

 Employee and Department are the names of the tables being joined.
 Employee.DepartmentID and Department.DepartmentOD represent the related columns
between the two tables.

The result of the SELECT query will display the employee ID, name, position, and corresponding
department location for each employee. The LEFT JOIN ensures that all records from the Employee
table are included in the result set, regardless of whether there is a matching department ID in the
Department table. If a match is not found, NULL values will be displayed for the department
location.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
43

RIGHT JOIN

By using RIGHT JOIN, you can combine the data from the Employee and Department tables while
including all records from the Department table, even if there is no corresponding employee
information. This allows you to retrieve department details along with the employee details, when
available.

In the above example, the SELECT statement retrieves the employee_id, name, position columns
from the Employee table, and the name column from the Department table (aliased as
department_name). The RIGHT JOIN clause is used to join the Employee and Department tables
based on the department_id column.

 Employee and Department are the names of the tables being joined.
 Employee.DepartmentID and Department.Department.ID represent the related columns
between the two tables.

The result of the SELECT query will display the employee ID, name, position, and corresponding
department name for each employee. The RIGHT JOIN ensures that all records from the Department
table are included in the result set, regardless of whether there is a matching department ID in the
Employee table. If a match is not found, NULL values will be displayed for the employee details.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
44

FULL OUTER JOIN

The FULL OUTER JOIN command is not directly supported in MySQL. However, you can achieve the
same result by combining a LEFT JOIN and a RIGHT JOIN. Here's an example of how you can simulate
a FULL OUTER JOIN between the Employee and Department tableds:

In the above example, the SELECT statement combines a LEFT JOIN and a RIGHT JOIN using the
UNION operator. The first part of the UNION selects records from the LEFT JOIN operation, and the
second part selects records from the RIGHT JOIN operation.

 Employee and Department are the names of the tables being joined.
 Employee.DepartmentID and Department.DepartmentID represent the related columns
between the two tables.

The result of the SELECT query will display the employee ID, name, position, salary, and department
location for each employee, including those without a matching department or employees without a
matching record in the Employee table.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
45

4.2 Some Important Relationship Queries:


Sample 1:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
46

Sample 2:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
47

Sample 3:

Sample 4:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
48

Sample 5:

Sample 6:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
49

Sample 7:

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
50

CONCLUSION:
In conclusion, our exploration of relational database management with MySQL has provided a
comprehensive understanding of the core concepts and operations involved in working with
databases. We began by familiarizing ourselves with the structure of a relational database,
emphasizing the importance of tables and primary keys in maintaining data integrity.

We explored various SQL commands, including CREATE TABLE for table creation, INSERT for data
insertion, SELECT for data retrieval, UPDATE for data modification, DELETE for data removal, and
ALTER TABLE for table alteration. These commands form the backbone of manipulating and
managing data within a database.

Throughout our discussion, we emphasized the significance of SQL constraints, such as NOT NULL,
UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK, in maintaining data integrity and enforcing
validation rules.

Additionally, we examined sorting and limiting results using the ORDER BY command and the LIMIT
keyword, respectively. Aggregate functions, such as MAX, MIN, COUNT, SUM, and AVG, were
introduced for performing calculations on columns or groups of rows, enabling statistical summaries
and insights.

We discussed the importance of data filtering using the WHERE clause with comparison and logical
operators, as well as the IN operator for filtering against multiple values. The GROUP BY clause
allowed us to group rows based on one or more columns, facilitating the analysis and summarization
of data.

We delved into the significance of establishing relationships between tables using foreign keys,
enabling efficient data organization and retrieval across related tables. This understanding of
relationships laid the foundation for performing joins, such as INNER JOIN, LEFT JOIN, RIGHT JOIN,
and simulating a FULL OUTER JOIN. Joins enable the combination of data from multiple tables,
facilitating comprehensive data analysis and reporting.

By acquiring knowledge and understanding of these fundamental concepts and operations, users
can effectively design databases, manipulate data efficiently, and derive valuable insights from their
data resources.

In conclusion, relational database management with MySQL offers a robust framework for
organizing, manipulating, and analyzing data. It forms the backbone of modern data-driven
applications and empowers businesses to make informed decisions based on accurate and well-
structured information.

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE
51

Signature and Date:

Student Signature: _________________________ Date: ______________________

Student Name: Kunjan Subedi

College Roll No: 15

Exam Roll No: 4741/19

Registration No: 7-2-710-15-2019

BBM 6th Semester

Nesfield International College

Teacher Feedback or Evaluation:


Feedback:

Teacher/Supervisor Signature: _________________________ Date: ______________________

Teacher Name: Saurab Adhikari

Subject: Database Management System

KUNJAN SUBEDI
NESFIELD INTERNATIONAL COLLEGE

You might also like