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

DBMS Final

Database Management System Practical

Uploaded by

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

DBMS Final

Database Management System Practical

Uploaded by

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

INDEX

Sr. No. Programs Date Signature

1 Introduction to Database Management 24/07/2024


System (DBMS)
2 Use of operators in My SQL 07/08/2024
3 Use of operators in SQL 14/08/2024
4 Use of Single Row functions 11/09/2024
5 Use of Join in SQL 09/11/2024
6 SQL query examples 23/10/2024
Practical 1
Aim: Introduction to Database Management System (DBMS)
Database Management System: A Database Management System (DBMS) is a
software system that is designed to manage and organize data in a structured manner. It allows
users to create, modify, and query a database, as well as manage the security and access controls
for that database.

Why Use Database Management System?


A Data Base Management System is a system software for easy, efficient and reliable data
processing and management. It can be used for:
• Creation of a database.
• Retrieval of information from the database.
• Updating the database.
• Managing a database.

o Multiple User Interface

o Data scalability, expandability and flexibility: We can change schema of the


database, all schema will be updated according to it.

o Overall the time for developing an application is reduced.

o Security: Simplifies data storage as it is possible to assign security permissions


allowing restricted access to data.

Data organization: DBMS allow users to organize large amounts of data in a structured
and systematic way. Data is organized into tables, fields, and records, making it easy to manage,
store, and retrieve information.

Data scalability: DBMS are designed to handle large amounts of data and are scalable to
meet the growing needs of organizations. As organizations grow, DBMS can scale up to handle
increasing amounts of data and user traffic.

Where is Database Management System being used


o Railway Reservation System
In the rail route reservation framework, the information base is needed to store the
record or information of ticket appointments, status of train’s appearance, and flight.
Additionally, if trains get late, individuals become acquainted with it through the
information base update.

o Library Management System


There are many books in the library so; it is difficult to store the record of the relative
multitude of books in a register or duplicate. Along these lines, the data set
administration framework (DBMS) is utilized to keep up all the data identified with the
name of the book, issue date, accessibility of the book, and its writer.

o Banking
Database the executive’s framework is utilized to store the exchange data of the client
in the information base
.
o Education Sector
Presently, assessments are led online by numerous schools and colleges. They deal with
all assessment information through the data set administration framework (DBMS). In
spite of that understudy’s enlistments subtleties, grades, courses, expense, participation,
results, and so forth all the data is put away in the information base.

Advantages of Database Management System


o Data Security: The more accessible and usable the database, the more it is prone to
security issues. As the number of users increases, the data transferring or data sharing
rate also increases thus increasing the risk of data security. It is widely used in the
corporate world where companies invest large amounts of money, time, and effort to
ensure data is secure and used properly. A Database Management System (DBMS)
provides a better platform for data privacy and security policies thus, helping companies
to improve Data Security.

o Data integration: Due to the Database Management System we have access to well-
managed and synchronized forms of data thus it makes data handling very easy and
gives an integrated view of how a particular organization is working and also helps to
keep track of how one segment of the company affects another segment.

o Data abstraction: The major purpose of a database system is to provide users with
an abstract view of the data. Since many complex algorithms are used by the developers
to increase the efficiency of databases that are being hidden by the users through various
data abstraction levels to allow users to easily interact with the system.

o Reduction in data Redundancy: When working with a structured database,


DBMS provides the feature to prevent the input of duplicate items in the database. for
e.g. – If there are two same students in different rows, then one of the duplicate data
will be deleted.
o Data sharing: A DBMS provides a platform for sharing data across multiple
applications and users, which can increase productivity and collaboration.

o Data consistency and accuracy: DBMS ensures that data is consistent and accurate
by enforcing data integrity constraints and preventing data duplication. This helps to
eliminate data discrepancies and errors that can occur when data is stored and managed
manually.

Components of Database Management System

The five major components of a database are:


o Hardware
Hardware refers to the physical, electronic devices such as computers and hard disks
that offer the interface between computers and real-world systems.

o Software

Software is a set of programs used to manage and control the database and includes the
database software, operating system, network software used to share the data with other
users, and the applications used to access the data.

o Data

Data are raw facts and information that need to be organized and processed to make it
more meaningful. Database dictionaries are used to centralize, document, control, and
coordinate the use of data within an organization. A database is a repository of
information about a database (also called metadata).
o Procedures

Procedures refer to the instructions used in a database management system and


encompass everything from instructions to setup and install, login and logout, manage
the day-to-day operations, take backups of data, and generate reports.

o Database Access Language

Database Access Language is a language used to write commands to access, update,


and delete data stored in a database. Users can write commands using Database Access
Language before submitting them to the database for execution. Through utilizing the
language, users can create new databases, tables, insert data, and delete data.

My SQL
o MySQL is a relational database management system
o MySQL is open-source
o MySQL is free
o MySQL is ideal for both small and large applications
o MySQL is very fast, reliable, scalable, and easy to use
o MySQL is cross-platform
o MySQL is compliant with the ANSI SQL standard
o MySQL was first released in 1995
o MySQL is developed, distributed, and supported by Oracle Corporation
o MySQL is named after co-founder Monty Widenius's daughter: My

Features of My SQL
The following are the most important features of MySQL:

Relational Database Management System (RDBMS)

MySQL is a relational database management system. This database language is based on the
SQL queries to access and manage the records of the table.

o Easy to use
o It is secure
o Client/ Server Architecture
o Free to download

Advantages of My SQL
Here are some of the main advantages of MySQL:
o Data Security: MySQL is globally renowned for being the most secure and reliable
database management system used in popular web applications, including
WordPress, Drupal, Joomla, Facebook, and Twitter.
o High Performance: MySQL features a different storage-engine framework that
facilitates system administrators to configure the MySQL database server for
flawless performance.
o Cost-Effective: The database is open-source and free.

Disadvantages of My SQL
Here are some of the key disadvantages of MySQL:

o MySQL does not support a huge database size efficiently.


o It is challenging to debug stored procedures.
o MySQL is not fully SQL compliant. Because of this, developers find it challenging
to cope with the syntax of SQL in MySQL.

Oracle Database
Oracle database is a relational database management system (RDBMS) from Oracle
Corporation. This article will explain a complete overview of the Oracle database, features,
history, and editions. Before discussing the oracle, we will first need to know about the
database.

Features of Oracle Database


o Availability: It is never offline or out of service that means supported 24*7
availability of the database. It provides high availability of databases because of the
Oracle Data Guard functionality. This functionality allows using of the secondary
database as a copy of the primary database during any failure. As a result, all normal
processes such as backups and partial failures do not interrupt the database from being
used.

o Security: Oracle has a mechanism for controlling and accessing the database to
prevent unauthorized access. It provides high security because of the Oracle Advanced
Security features. It offers two solutions to protect databases that are TDE (Transparent
Data Encryption) and Data Redaction. TDE supports data encryption both at the source
and after export. Redaction is performed at the application level. Oracle has some other
security features like Oracle Database Vault that regulates user privileges and Oracle
Label Security.

o Scalability: It provides features like RAC (Real Application Cluster) and Portability,
which makes an Oracle database scalable based on usage. In a clustered environment,
it includes capabilities such as rolling instance migrations, performing upgrades,
maintaining application continuity, quality of service management, etc.

o Performance: Oracle provides performance optimization tools such as Oracle


Advanced Compression, Oracle Database In-Memory, Oracle Real Application
Testing, and Oracle Times Ten Application-Tier Database Cache. Their main objective
is to improve system performance to the highest possible level.

Advantages of Oracle Database


The following are the main advantages of an Oracle database:

o Performance: Oracle has procedures and principles that help us to get high levels of
database performance. We can increase query execution time and operations with the
use of performance optimization techniques in its database. This technique helps to
retrieve and alter data faster.

o Portability: The Oracle database can be ported on all different platforms than any of
its competitors. We can use this database on around 20 networking protocols as well as
over 100 hardware platforms. This database makes it simple to write an Oracle
application by making changes to the OS and hardware in a secure manner.
o Backup and Recovery: It is always better to take a proper backup of your entire
oracle online backup and recovery. The Oracle database makes it easy to accomplish
recovery quickly by using the. RMAN (Recovery Manager) functionality. It can recover
or restore database files during downtime or outages. It can be used for online backups,
archived backups, and continuous archiving. We can also use SQL* PLUS for recovery,
which is known as user-managed recovery.

o PL/SQL: One of the greatest benefits of using the Oracle database is to support
PL/SQL extension for procedural programming.

o Multiple Database: Oracle database allows several database instances management


on a single server. It provides an instance caging approach for managing CPU
allocations on a server hosting database instances. The database resource management
and instance caging can work together to manage services across multiple instances.

o Flashback Technology: This advantage comes with the recent Oracle version. It
allows us to recover those data that are incorrectly deleted or lost by human errors like
accidental deletion of valuable data, deleting the wrong data, or dropping the table.

Disadvantages of Oracle Database


The following are the disadvantages of the Oracle database:

o Complexity: Oracle is not recommended to use when the users are not technically
savvy and have limited technical skills required to deal with the Oracle Database. It is
also not advised to use if the company is looking for a database with limited
functionality and easy to use.
o Cost: The price of Oracle products is very high in comparison to other databases.
Therefore users are more likely to choose other less expensive options such as MS SQL
Server, MySQL, etc.
o Difficult to manage: Oracle databases are often much more complex and difficult
in terms of the management of certain activities.
Mongo db
MongoDB is a powerful and flexible solution for handling modern data needs. As a leading
NoSQL database, MongoDB offers a dynamic schema design, enabling developers to store and
manage data in a way that aligns seamlessly with contemporary application requirements.

Unlike traditional relational databases, MongoDB’s document-oriented architecture allows for


greater agility and scalability, making it a preferred choice for businesses and developers
aiming to handle large volumes of unstructured or semi-structured data.

Features of MongoDB
• Schema-less Database: It is the great feature provided by the MongoDB. A
Schema-less database means one collection can hold different types of documents in it.
Or in other words, in the MongoDB database, a single collection can hold multiple
documents and these documents may consist of the different numbers of fields, content,
and size. It is not necessary that the one document is similar to another document like
in the relational databases. Due to this cool feature, MongoDB provides great flexibility
to databases.

• Document Oriented: In MongoDB, all the data stored in the documents instead of
tables like in RDBMS. In these documents, the data is stored in fields(key-value pair)
instead of rows and columns which make the data much more flexible in comparison
to RDBMS. And each document contains its unique object id.

• Indexing: In MongoDB database, every field in the documents is indexed with


primary and secondary indices this makes easier and takes less time to get or search
data from the pool of the data. If the data is not indexed, then database search each
document with the specified query which takes lots of time and not so efficient.

• Scalability: MongoDB provides horizontal scalability with the help of sharding.


Sharding means to distribute data on multiple servers, here a large amount of data is
partitioned into data chunks using the shard key, and these data chunks are evenly
distributed across shards that reside across many physical servers. It will also add new
machines to a running database.

• Replication: MongoDB provides high availability and redundancy with the help of
replication, it creates multiple copies of the data and sends these copies to a different
server so that if one server fails, then the data is retrieved from another server.

• Aggregation: It allows to perform operations on the grouped data and get a single
result or computed result. It is similar to the SQL GROUPBY clause. It provides three
different aggregations i.e, aggregation pipeline, map-reduce function, and single-
purpose aggregation methods
• High Performance: The performance of MongoDB is very high and data
persistence as compared to another database due to its features like scalability,
indexing, replication, etc.

Advantages of MongoDB
• It is a schema-less NoSQL database. You need not to design the schema of the database
when you are working with MongoDB.

• It does not support join operation.

• It provides great flexibility to the fields in the documents.

• It contains heterogeneous data.

• It provides high performance, availability, scalability.

• It supports Geospatial efficiently.

• It is a document oriented database and the data is stored in BSON documents.

• It also supports multiple document ACID transition(string from MongoDB 4.0).

• It does not require any SQL injection.

• It is easily integrated with Big Data Hadoop

Disadvantages of MongoDB

• It uses high memory for data storage.

• You are not allowed to store more than 16MB data in the documents.

• The nesting of data in BSON is also limited you are not allowed to nest data more than
100 levels.

SQL
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987
Types of SQL

DDL (Data Definition Language)

DDL or Data Definition Language actually consists of the SQL commands that can be used to
define the database schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in the database.

DDL is a set of SQL commands used to create, modify, and delete database structures but not
data. These commands are normally not used by a general user, who should be accessing the
database via an application.

List of DDL Commands


Some DDL commands and their syntax are:

Command Description Syntax

Create database or its objects (table, index,


CREATE TABLE table_name (column1
CREATE function, views, store procedure, and
data_type, column2 data_type, ...);
triggers)
Command Description Syntax

DROP Delete objects from the database DROP TABLE table_name;

ALTER TABLE table_name ADD


ALTER Alter the structure of the database
COLUMN column_name data_type;

Remove all records from a table, including


TRUNCATE all spaces allocated for the records are TRUNCATE TABLE table_name;
removed

COMMENT 'comment_text' ON
COMMENT Add comments to the data dictionary
TABLE table_name;

RENAME TABLE old_table_name TO


RENAME Rename an object existing in the database
new_table_name;

DQL (Data Query Language)


DQL statements are used for performing queries on the data within schema objects. The
purpose of the DQL Command is to get some schema relation based on the query passed to
it. We can define DQL as follows it is a component of SQL statement that allows getting data
from the database and imposing order upon it. It includes the SELECT statement.

This command allows getting the data out of the database to perform operations with it. When
a SELECT is fired against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program i.e. a front-end.

DQL Command

There is only one DQL command in SQL i.e.

Command Description Syntax

It is used to retrieve data from SELECT column1, column2, ...FROM


SELECT table_name<br>WHERE condition;
the database

DML(Data Manipulation Language)

The SQL commands that deal with the manipulation of data present in the database belong to
DML or Data Manipulation Language and this includes most of the SQL statements.

It is the component of the SQL statement that controls access to data and to the database.
Basically, DCL statements are grouped with DML statements.

List of DML commands

Some DML commands and their syntax are:


Command Description Syntax

INSERT INTO table_name (column1, column2, ...) VALUES


INSERT Insert data into a table
(value1, value2, ...);

Update existing data UPDATE table_name SET column1 = value1, column2 =


UPDATE
within a table value2 WHERE condition;

Delete records from a


DELETE DELETE FROM table_name WHERE condition;
database table

LOCK Table control concurrency LOCK TABLE table_name IN lock_mode;

Call a PL/SQL or JAVA


CALL CALL procedure_name(arguments);
subprogram

EXPLAIN Describe the access path to


EXPLAIN PLAN FOR SELECT * FROM table_name;
PLAN data

DCL (Data Control Language)

DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.

List of DCL commands:

Two important DCL commands and their syntax are:

Command Description Syntax

Assigns new privileges to a user account, GRANT privilege_type [(column_list)] ON


GRANT allowing access to specific database [object_type] object_name TO user [WITH
objects, actions, or functions. GRANT OPTION];

Removes previously granted privileges REVOKE [GRANT OPTION FOR]


from a user account, taking away their privilege_type [(column_list)] ON
REVOKE
access to certain database objects or [object_type] object_name FROM user
actions. [CASCADE];

TCL (Transaction Control Language)

Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of the
tasks fail, the transaction fails.
Therefore, a transaction has only two results: success or failure. You can explore more about
transactions here. Hence, the following TCL commands are used to control the execution of a
transaction:

List of TCL Commands

Some TCL commands and their syntax are:

Command Description Syntax

BEGIN BEGIN TRANSACTION


Starts a new transaction
TRANSACTION [transaction_name];

Saves all changes made during the


COMMIT COMMIT;
transaction

Undoes all changes made during the


ROLLBACK ROLLBACK;
transaction

Creates a savepoint within the current


SAVEPOINT SAVEPOINT savepoint_name;
transaction
Practical 2
Aim: Use of operators in My SQL
Operator: An operator is a sign or symbol that specifies the type of calculation to perform
within an expression. There are mathematical, comparison, logical, and reference operators.
MySQL Arithmetic Operators

+ Addition

- Subtract

* Multiply

/ Divide

% Modulo

MySQL Bitwise Operators

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR
MySQL Comparison Operators

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not equal to

MySQL Compound Operators

Operator Description

+= Add equals

-= Subtract equals

*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals

^-= Bitwise exclusive equals

|*= Bitwise OR equals

MySQL Logical Operators

ALL TRUE if all of the subquery values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the subquery values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

EXISTS TRUE if the subquery returns one or more records


IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern

NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE

SOME TRUE if any of the subquery values meet the condition


Practical 3
Aim: Use of Operators in SQL
SQL Operators perform arithmetic, comparison, and logical operations to manipulate and
retrieve data from databases.
In this article, we will discuss Operators in SQL with examples, and understand how they
work in SQL.

Operators in SQL
Operators in SQL are symbols that help us to perform specific mathematical and logical
computations on operands. An operator can either be unary or binary.
The unary operator operates on one operand, and the binary operator operates on two
operands.

Types of Operators in SQL


Different types of operators in SQL are:
• Arithmetic operator
• Comparison operator
• Logical operator
• Bitwise Operators
• Compound Operator
• SQL Arithmetic Operators

SQL arithmetic operators


Arithmetic operators in SQL are used to perform mathematical operations on numeric
values in queries. Some common arithmetic operators are:

Operator Description

+ The addition is used to perform an addition operation on the data values.

– This operator is used for the subtraction of the data values.

This operator works with the ‘ALL’ keyword and it calculates division
/
operations.

* This operator is used for multiplying data values.


Operator Description

% Modulus is used to get the remainder when data is divided by another.

SQL Comparison Operators


Comparison operator in SQL are used to compare one expression’s value to other
expressions. SQL supports different types of comparison operator, which are described
below:

Operator Description

= Equal to.

> Greater than.

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.

SQL Logical Operators


Logical operator in SQL are used to combine or manipulate conditions in SQL queries to
retrieve or manipulate data based on specified criteria.
Operator Description

Logical AND compares two Booleans as expressions and returns


AND
true when both expressions are true.

Logical OR compares two Booleans as expressions and returns


OR
true when one of the expressions is true.

Not takes a single Boolean as an argument and change its value


NOT
from false to true or from true to false.

SQL Bitwise Operators


Bitwise operators in SQL are used to perform bitwise operations on binary values in SQL
queries, manipulating individual bits to perform logical operations at the bit level. Some SQL
Bitwise Operators are:

Operator Description

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise XOR (exclusive OR) operator

~ Bitwise NOT (complement) operator

<< Left shift operator

>> Right shift operator


SQL Compound Operators
Compound operator in SQL are used to perform an operation and assign the result to the
original value in a single line. Some Compound operators are:

Operator Description

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulo and assign

&= Bitwise AND and assign

^= Bitwise XOR and assign

|= Bitwise OR and assign

SQL Special Operators


Special operators are used in SQL queries to perform specific operations like comparing
values, checking for existence, and filtering data based on certain conditions.

Operators Description

ALL is used to select all records of a SELECT


STATEMENT. It compares a value to every value in a
ALL list of results from a query. The ALL must be preceded
by the comparison operators and evaluated to TRUE if
the query returns no rows.
Operators Description

ANY compares a value to each value in a list of results


ANY from a query and evaluates to true if the result of an
inner query contains at least one row.

The SQL BETWEEN operator tests an expression


BETWEEN against a range. The range consists of a beginning,
followed by an AND keyword and an end expression.

The IN operator checks a value within a set of values


IN separated by commas and retrieves the rows from the
table that match.

The EXISTS checks the existence of a result of a


subquery. The EXISTS subquery tests whether a
EXISTS
subquery fetches at least one row. When no data is
returned then this operator returns ‘FALSE’.

SOME operator evaluates the condition between the


outer and inner tables and evaluates to true if the final
SOME
result returns any one row. If not, then it evaluates to
false.

The UNIQUE operator searches every unique row of a


UNIQUE
specified table.
Practical 4
Aim: Use of Single Row functions
Single row functions in SQL operate on individual rows and return a single value for each row.
Here are some common types of single row functions with examples:

1. String Functions
• UPPER (): Converts a string to uppercase.
SELECT UPPER (name) AS uppercase_name
FROM employees;

• LOWER (): Converts a string to lowercase.


SELECT LOWER(name) AS lowercase_name
FROM employees;

2. Numeric Functions
• ROUND(): Rounds a number to a specified number of decimal places.
SELECT ROUND(salary, 2) AS rounded_salary
FROM employees;

• CEIL(): Returns the smallest integer greater than or equal to a number.


SELECT CEIL(salary) AS ceiling_salary
FROM employees;

• FLOOR(): Returns the largest integer less than or equal to a number.


SELECT FLOOR(salary) AS floor_salary
FROM employees;

3. Date Functions
• CURRENT_DATE: Returns the current date.
SELECT CURRENT_DATE AS today
FROM dual;
• ADD_MONTHS(): Adds a specified number of months to a date.
SELECT ADD_MONTHS(hiringdate, 6) AS new_hire_date
FROM employees;
• EXTRACT(): Retrieves sub-parts from a date (like year, month, day).
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year
FROM employees;
4. Conversion Functions
• TO_CHAR(): Converts a number or date to a string.
SELECT TO_CHAR(hiringdate, 'YYYY-MM-DD') AS formatted_hire_date
FROM employees;
• TO_NUMBER(): Converts a string to a number.
SELECT TO_NUMBER(salary_string) AS salary
FROM employee_salaries;
• TO_DATE(): Converts a string to a date.
SELECT TO_DATE('2024-01-01', 'YYYY-MM-DD') AS formatted_date
FROM dual;
5. Miscellaneous Functions
• NVL(): Replaces null with a specified value.
SELECT NVL(phone_number, 'N/A') AS contact_number
FROM employees;
• COALESCE(): Returns the first non-null value in a list.
SELECT COALESCE(middle_name, 'No Middle Name') AS full_name
FROM employees;

Multi row functions in SQL


Multi-row functions in SQL, often referred to as aggregate functions, operate on a set of
rows and return a single summary value. These functions are typically used with the
GROUP BY clause to summarize data. Here are some common multi-row functions with
examples:
1. COUNT()
Counts the number of rows or non-null values.
SELECT departmentid, COUNT(*) AS employee_count
FROM employees
GROUP BY departmentid;
2. SUM()
Calculates the total of a numeric column.
SELECT departmentid, SUM(salary) AS total_salary
FROM employees
GROUP BY departmentid;

3. AVG()
Calculates the average value of a numeric column.
SELECT departmentid, AVG(salary) AS average_salary
FROM employees
GROUP BY departmentid;

4. MIN()
Returns the minimum value of a column.
SELECT departmentid, MIN(salary) AS lowest_salary
FROM employees
GROUP BY departmentid;
5. MAX()
Returns the maximum value of a column.
SELECT departmentid, MAX(salary) AS highest_salary
FROM employees
GROUP BY departmentid;

6. GROUP_CONCAT() (or equivalent)


Concatenates values from multiple rows into a single string (available in MySQL and
other databases with similar functionality).
SELECT departmentid, GROUP_CONCAT(first_name) AS employees_names
FROM employees
GROUP BY departmentid;

7. HAVING
Used to filter groups based on the result of aggregate functions.
SELECT departmentid, COUNT(*) AS employee_count
FROM employees
GROUP BY departmentid
HAVING COUNT(*) > 10;
8. ROLLUP
Creates subtotals and grand totals.
SELECT departmentid, COUNT(*) AS employee_count
FROM employees
GROUP BY ROLLUP(departmentid);
Practical 6
Aim: SQL QUERY EXAMPLES
1. Selecting Data
Basic SELECT Statement
SELECT name
FROM employees;

2. Filtering Data
Using WHERE Clause
SELECT name
FROM employees
WHERE departmentid = 3;

3. Sorting Data
Using ORDER BY
SELECT name, salary
FROM employees
ORDER BY salary DESC;
4. Grouping Data
Using GROUP BY
SELECT departmentid, COUNT(*) AS employee_count
FROM employees
GROUP BY departmentid;

5. Filtering Groups
Using HAVING
SELECT departmentid, AVG(salary) AS average_salary
FROM employees
GROUP BY departmentid
HAVING AVG(salary) > 50000;

6. Joining Tables
INNER JOIN Example
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
7. Inserting Data
INSERT Statement
INSERT INTO employees (empid,name, department, salary,hiringdate,departmentid)
VALUES (5,'John','engineering', 60000,2020-04-12,5);

8. Updating Data
UPDATE Statement
UPDATE employees
SET salary = salary * 1.10
WHERE departmentid = 2;

9. Deleting Data
DELETE Statement
DELETE FROM employees
WHERE empid = 5;

10. Using Aggregate Functions


SUM Example
SELECT departmentid, SUM(salary) AS total_salary
FROM employees
GROUP BY departmentid;

11. Using Subqueries


Subquery in SELECT
SELECT name,
(SELECT department FROM department WHERE departmentid =
employees.departmentid) AS department
FROM employees;
12. Using CASE Statement
Conditional Logic in SELECT
SELECT name,
CASE
WHEN salary < 40000 THEN 'Low'
WHEN salary BETWEEN 40000 AND 70000 THEN 'Medium'
ELSE 'High'
END AS salary_range
FROM employees;

13. Using DISTINCT


Eliminating Duplicate Values
SELECT DISTINCT departmentid
FROM employees;

14. Using LIKE for Pattern Matching


Finding Names that Start with 'A'
SELECT name
FROM employees
WHERE name LIKE 'J%';

15. Using LIMIT or TOP


Limiting Results
SELECT name
FROM employees
ORDER BY salary DESC
LIMIT 5; -- For MySQL/PostgreSQL
SELECT TOP 5 name
FROM employees
ORDER BY salary DESC; -- For SQL Server
Summary
These examples cover a variety of SQL operations, from basic data retrieval to more complex
queries involving joins, subqueries, and conditional logic. You can adapt and combine these
examples to suit your specific needs when working with SQL databases.
Practical 5
Aim: Use of JOIN in SQL
SQL joins are used to combine rows from two or more tables based on a related column
between them. Here are the most common types of joins, along with examples:

1. INNER JOIN
Returns rows when there is a match in both tables.
SELECT e. name, d.department
FROM employees
INNER JOIN department d ON e.departmentid = d.departmentid;

2. LEFT JOIN (or LEFT OUTER JOIN)


Returns all rows from the left table and the matched rows from the right table. If there is no
match, NULL values are returned for columns from the right table.
SELECT e. name, d.department
FROM employees
LEFT JOIN departments d ON e.departmentid = d.departmentid;

3. RIGHT JOIN (or RIGHT OUTER JOIN)


Returns all rows from the right table and the matched rows from the left table. If there is no
match, NULL values are returned for columns from the left table.
SELECT e.name, d.department
FROM employees
RIGHT JOIN departmentsd ON e.departmentid = d.departmentid;

4. FULL JOIN (or FULL OUTER JOIN)


Returns all rows when there is a match in either the left or right table. If there is no match,
NULL values are returned for the missing side.
SELECT e.name, d.department
FROM employees
FULL JOIN department d ON e.departmentid = d.departmentid;
5. CROSS JOIN
Returns the Cartesian product of the two tables, meaning every row from the first table is
combined with every row from the second table.
SELECT e.name, d.department
FROM employees
CROSS JOIN departments ;

6. SELF JOIN
A self join is a join of a table with itself. It is useful for comparing rows within the same
table.
SELECT a.first_name AS Employee, b.first_name AS Manager
FROM employees a
INNER JOIN employees b ON a.manager_id = b.employee_id;
7. NATURAL JOIN
Automatically joins tables based on columns with the same names in both tables. This is less
commonly used because it can lead to unexpected results if there are many matching
columns.
SELECT *
FROM employees
NATURAL JOIN department;

Summary
SQL joins are essential for querying data across multiple tables. By understanding the
different types of joins, you can effectively retrieve and analyze relational data from your
database.

You might also like