0% found this document useful (0 votes)
19 views22 pages

DBMS File

The document provides an introduction to Database Management Systems (DBMS), Relational Database Management Systems (RDBMS), and Structured Query Language (SQL), outlining their definitions, features, advantages, and disadvantages. It explains the types of DBMS, the functionalities of SQL, and the importance of normalization and ACID properties in RDBMS. Additionally, it covers DDL commands for managing database structures and the applications of these systems in various domains such as banking, healthcare, and e-commerce.

Uploaded by

Rishika Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views22 pages

DBMS File

The document provides an introduction to Database Management Systems (DBMS), Relational Database Management Systems (RDBMS), and Structured Query Language (SQL), outlining their definitions, features, advantages, and disadvantages. It explains the types of DBMS, the functionalities of SQL, and the importance of normalization and ACID properties in RDBMS. Additionally, it covers DDL commands for managing database structures and the applications of these systems in various domains such as banking, healthcare, and e-commerce.

Uploaded by

Rishika Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Experiment-1

Title : Introduction to DBMS, RDBMS and SQL.

Objective:
• To understand the concepts of Database Management Systems (DBMS), Relational
Database Management Systems (RDBMS), and Structured Query Language (SQL).
• To differentiate between DBMS and RDBMS.
• To learn the basic functionalities of SQL for database operations.

Theory:
A Database Management System (DBMS) is software that enables users to store, organize,
retrieve, and manage data efficiently. It acts as an interface between users and a database,
ensuring that data is stored securely, remains consistent, and is easily accessible.
In modern applications, DBMS is essential for handling large volumes of structured and
unstructured data in various domains like banking, healthcare, e-commerce, education,
and social media.

What is a Database?
A database is an organized collection of related data that can be easily accessed, managed,
and updated. Data in a database is usually stored in tables (rows and columns), files, or
objects, depending on the type of database used.
Example:
A university database may store information about students, courses, teachers, and grades
in different tables.

Why Use a DBMS?


Before DBMS, file-based systems were used to store data, but they had several limitations:
• Data Redundancy and Inconsistency: Storing duplicate copies of the same data led
to inconsistency.
• Data Isolation: Data was stored in multiple files, making it difficult to retrieve and
manage.
• Security Issues: There were no proper access control mechanisms.
• Lack of Multi-User Access: If multiple users tried to access data at the same time, it
could lead to conflicts.
DBMS overcomes these challenges by providing an organized, efficient, and secure way to
manage data.

Key Features of DBMS


1. Data Abstraction:
o Hides the complexity of data storage and provides a simple view to users.
2. Data Security:
o Provides authentication (user login) and authorization (access control).

3
3. Data Integrity:
o Ensures data is accurate and consistent through rules and constraints.
4. Concurrency Control:
o Allows multiple users to access and modify data at the same time without
conflicts.
5. Backup and Recovery:
o Protects data by allowing recovery in case of system failure.
6. Query Processing:
o Enables efficient data retrieval using SQL (Structured Query Language).

Types of DBMS
DBMS is categorized into different types based on how data is structured and managed:
1. Hierarchical DBMS
• Organizes data in a tree-like structure (parent-child relationship).
• Each parent can have multiple children, but each child has only one parent.
• Example: IBM’s IMS (Information Management System)
Use Case: Used in banking and telecommunication systems where hierarchical
relationships exist.

2. Network DBMS
• Uses a graph-like structure where multiple relationships can exist between records.
• Unlike hierarchical DBMS, a child record can have multiple parent records.
• Example: Integrated Data Store (IDS)
Use Case: Used in manufacturing and transport systems.

3. Relational DBMS (RDBMS)


• Stores data in tables (rows and columns) with relationships between them.
• Uses SQL (Structured Query Language) for data manipulation.
• Examples: MySQL, PostgreSQL, Oracle, Microsoft SQL Server
Use Case: Used in banking, retail, healthcare, and online applications.

4. Object-Oriented DBMS (OODBMS)


• Stores data in objects (used in object-oriented programming).
• Example: ObjectDB, db4o
Use Case: Used in multimedia, scientific applications, and AI-based systems.

Advantages of DBMS
Reduces Data Redundancy: Avoids duplicate data storage.
Ensures Data Security: Restricts unauthorized access to sensitive data.
Provides Data Consistency: Ensures uniform and accurate data across all users.
Supports Multi-User Access: Multiple users can work on the same database

4
simultaneously.
Enables Complex Queries: Users can retrieve data efficiently using SQL.
Backup and Recovery: Automatic data backup in case of system failure.

Disadvantages of DBMS
High Cost: Requires powerful hardware and software.
Complex Setup: Setting up and managing a DBMS requires expertise.
Performance Overhead: Involves additional processing, which can slow down
performance in large
systems.

Popular DBMS Software


Type of DBMS Examples
Relational DBMS (RDBMS) MySQL, PostgreSQL, Oracle, SQL Server, SQLite
NoSQL (Non-relational DBMS) MongoDB, Firebase, Cassandra
Cloud-based DBMS Amazon RDS, Google Cloud SQL, Microsoft Azure SQL
In-Memory DBMS SAP HANA, Redis

Applications of DBMS
Banking Systems: Storing customer accounts, transactions, and loan records.
E-commerce: Managing product catalogs, user information, and orders.
Healthcare: Storing patient records, hospital management, and prescriptions.
Education: Handling student information, courses, and exam results.
Social Media: Managing user profiles, posts, and interactions.
Introduction to RDBMS (Relational Database Management System)
A Relational Database Management System (RDBMS) is a type of DBMS (Database
Management System) that organizes data into tables with rows and columns. It follows the
relational model introduced by E.F. Codd in 1970, where data is stored in relations (tables)
and can be retrieved using SQL (Structured Query Language).
RDBMS is widely used in applications where data consistency, security, and structured
relationships are important, such as banking, e-commerce, healthcare, and enterprise
software.

What is a Relational Database?


A relational database stores data in tables that are linked together based on relationships.
Each table consists of:
Rows (Records) → Represent individual entries
Columns (Attributes) → Define properties of data
Example: Student Database

5
Student_ID Name Age Course
101 John 20 B.Tech
102 Alice 22 MBA
103 Bob 21 B.Sc
Here,
• "Student_ID" is the unique identifier (Primary Key).
• Each row represents a student.
• Columns store different attributes (Student ID, Name, Age, Course).

Key Features of RDBMS


1. Data Stored in Tables – Data is organized in tabular format with relationships.
2. Data Integrity & Accuracy – Ensures data consistency using constraints like
Primary Key, Foreign Key, NOT NULL, UNIQUE.
3. SQL-Based Queries – Uses SQL (Structured Query Language) for data
manipulation.
4. Data Security – Provides authentication and access control.
5. Scalability – Supports large amounts of data and multi-user access.
6. ACID Properties – Ensures Atomicity, Consistency, Isolation, and Durability in
transactions.

Advantages of RDBMS
Eliminates Redundancy – Uses normalization to prevent duplicate data.
Ensures Data Security – Allows role-based access control.
Supports Transactions – Guarantees safe and reliable operations.
Allows Multiple Users – Supports concurrency control.
Easy Data Retrieval – Uses SQL for fast and efficient querying.

Disadvantages of RDBMS
Complex Structure – Requires expert knowledge to design and manage databases.
Performance Overhead – Handling large amounts of data can slow down operations.
Costly Implementation – Requires powerful servers and maintenance.

Popular RDBMS Software


RDBMS Developer Usage
MySQL Oracle Web applications, e-commerce
PostgreSQL Global Dev.
PostgreSQL Data analytics, enterprise apps
Group
Oracle Database Oracle Large enterprise solutions

6
RDBMS Developer Usage
Microsoft SQL
Microsoft Business and corporate applications
Server
Mobile apps, lightweight
SQLite SQLite.org
applications

SQL (Structured Query Language) in RDBMS


SQL is the standard language used to interact with RDBMS.
Basic SQL Commands
Create Table
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Course VARCHAR(30)
);
Insert Data
INSERT INTO Students (Student_ID, Name, Age, Course)
VALUES (101, 'John', 20, 'B.Tech');
Retrieve Data
SELECT * FROM Students;
Update Data
UPDATE Students
SET Age = 21
WHERE Student_ID = 101;
Delete Data
DELETE FROM Students WHERE Student_ID = 101;

ACID Properties in RDBMS


RDBMS follows ACID properties to ensure safe transactions:
1. Atomicity – Ensures all operations in a transaction are completed or none at all.
2. Consistency – Ensures database remains in a valid state before and after a transaction.
3. Isolation – Multiple transactions do not interfere with each other.
4. Durability – Ensures committed transactions are permanently saved.

Normalization in RDBMS
Normalization is the process of reducing data redundancy and improving efficiency. It
divides large tables into smaller related tables.
Normalization Forms
1. 1NF (First Normal Form) – Ensures each column has atomic (indivisible) values.
2. 2NF (Second Normal Form) – Removes partial dependencies.

7
3. 3NF (Third Normal Form) – Eliminates transitive dependencies.

Applications of RDBMS
Banking Systems – Stores customer transactions, accounts, and loans.
E-commerce – Manages user profiles, products, and orders.
Healthcare – Stores patient records, doctor schedules, and prescriptions.
Education – Handles student data, courses, and grades.
Enterprise Software – Manages HR, sales, and inventory data.
Introduction to SQL (Structured Query Language)
SQL (Structured Query Language) is the standard programming language used to interact
with Relational Database Management Systems (RDBMS). It allows users to store,
retrieve, manipulate, and manage data in a structured and efficient manner.
SQL is widely used in applications such as banking, e-commerce, healthcare, education,
and enterprise systems to handle large amounts of data.

Why Use SQL?


SQL provides a powerful and flexible way to interact with databases:
Easy to Learn and Use – Uses simple English-like commands.
Efficient Data Management – Quickly retrieves and updates large datasets.
Standardized Language – Supported by most RDBMS (MySQL, PostgreSQL, Oracle,
etc.).
Ensures Data Integrity – Uses constraints like Primary Key, Foreign Key, and
Unique.
Supports Transactions – Follows ACID properties for reliability.

Types of SQL Commands


SQL is categorized into five main types based on functionality:
Command Type Description Example Commands
DDL (Data Definition Defines the structure of database CREATE, ALTER, DROP,
Language) objects (tables, indexes, etc.) TRUNCATE
DML (Data INSERT, UPDATE,
Modifies the data inside tables
Manipulation Language) DELETE
DQL (Data Query
Retrieves data from tables SELECT
Language)
DCL (Data Control Controls user access and
GRANT, REVOKE
Language) permissions
TCL (Transaction Manages transactions within a COMMIT, ROLLBACK,
Control Language) database SAVEPOINT

8
1. DDL (Data Definition Language) – Managing Database Structure
DDL commands are used to define and modify database schema (tables, indexes,
constraints, etc.).
CREATE TABLE – Creates a new table.
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Course VARCHAR(30)
);
ALTER TABLE – Modifies an existing table (adding/removing columns).
ALTER TABLE Students ADD Email VARCHAR(100);
DROP TABLE – Deletes a table permanently.
DROP TABLE Students;
TRUNCATE TABLE – Removes all records from a table but keeps the structure.
TRUNCATE TABLE Students;

2. DML (Data Manipulation Language) – Modifying Data


DML commands are used to insert, update, and delete data in tables.
INSERT INTO – Adds new records.
INSERT INTO Students (Student_ID, Name, Age, Course)
VALUES (101, 'John', 20, 'B.Tech');
UPDATE – Modifies existing records.
UPDATE Students
SET Age = 21
WHERE Student_ID = 101;
DELETE – Removes records based on a condition.
DELETE FROM Students WHERE Student_ID = 101;

3. DQL (Data Query Language) – Retrieving Data


DQL commands are used to fetch data from a database.
SELECT – Retrieves records from a table.
SELECT * FROM Students;
SELECT with WHERE – Filters results based on conditions.
SELECT * FROM Students WHERE Age > 20;
SELECT with ORDER BY – Sorts results in ascending (ASC) or descending (DESC)
order.
SELECT * FROM Students ORDER BY Age DESC;
SELECT with GROUP BY – Groups records based on a specific column.
SELECT Course, COUNT(*) FROM Students GROUP BY Course;
SELECT with JOIN – Combines data from multiple tables.
SELECT Students.Name, Courses.Course_Name

9
FROM Students
INNER JOIN Courses ON Students.Course = Courses.Course_ID;

4. DCL (Data Control Language) – Managing User Access


DCL commands control user permissions on database objects.
GRANT – Gives a user specific privileges.
GRANT SELECT, INSERT ON Students TO user1;
REVOKE – Removes assigned privileges.
REVOKE INSERT ON Students FROM user1;

5. TCL (Transaction Control Language) – Managing Transactions


TCL commands manage transactions in a database to ensure data integrity.
COMMIT – Saves changes permanently.
COMMIT;
ROLLBACK – Undoes uncommitted changes.
ROLLBACK;
SAVEPOINT – Creates checkpoints within a transaction.
SAVEPOINT sp1;

SQL Constraints – Ensuring Data Integrity


Constraints enforce rules on data to maintain accuracy and consistency.
Constraint Description Example
PRIMARY
Ensures uniqueness of a record Student_ID INT PRIMARY KEY
KEY
FOREIGN Course_ID INT REFERENCES
Enforces referential integrity
KEY Courses(Course_ID)
NOT NULL Prevents empty values Name VARCHAR(50) NOT NULL
Ensures all values in a column
UNIQUE Email VARCHAR(100) UNIQUE
are different
Validates values based on
CHECK Age INT CHECK (Age >= 18)
conditions
Assigns a default value if none Status VARCHAR(10) DEFAULT
DEFAULT
is provided 'Active'

Joins in SQL – Combining Data from Multiple Tables


Joins are used to fetch related data from multiple tables based on common columns.

10
Join
Description Example
Type
SELECT * FROM Students INNER JOIN
INNER Returns matching records from
Courses ON Students.Course_ID =
JOIN both tables
Courses.Course_ID;
Returns all records from the left SELECT * FROM Students LEFT JOIN
LEFT
table, with matching records from Courses ON Students.Course_ID =
JOIN
the right Courses.Course_ID;
Returns all records from the right SELECT * FROM Students RIGHT JOIN
RIGHT
table, with matching records from Courses ON Students.Course_ID =
JOIN
the left Courses.Course_ID;
Returns all records from both SELECT * FROM Students FULL JOIN
FULL
tables, with NULL for unmatched Courses ON Students.Course_ID =
JOIN
rows Courses.Course_ID;

Normalization in SQL – Reducing Data Redundancy


Normalization divides a database into multiple related tables to eliminate duplicate data.
Normal Form Description
1NF (First Normal
Ensures each column has atomic values (no repeating groups).
Form)
2NF (Second Normal Removes partial dependencies (no non-key attributes should depend
Form) on part of a composite key).
3NF (Third Normal Eliminates transitive dependencies (no column should depend on
Form) another non-key column).

SQL in Real-Life Applications


E-commerce – Manages products, customers, and orders.
Banking Systems – Handles transactions, accounts, and customers.
Healthcare – Stores patient records, doctor schedules, and prescriptions.
Social Media – Manages user profiles, posts, and interactions.
Educational Institutes – Stores student data, courses, and results.

11
Experiment-2
Title : Experiments based on DDL commands – CREATE, ALTER, DROP and TRUNCATE.

Objective:
• To understand and perform DDL (Data Definition Language) commands in
SQL.
• To learn how to create, modify, delete, and manage database structures
using CREATE, ALTER, DROP, and TRUNCATE commands.
• To analyze the impact of these commands on database schemas and data
storage.
• To understand the differences between DROP and TRUNCATE in terms of
data removal and table structure persistence.

Theory:
What is DDL (Data Definition Language)?
DDL (Data Definition Language) is a category of SQL commands used to define, modify,
and delete database structures such as tables, schemas, indexes, and constraints. DDL
commands do not modify actual data inside tables; instead, they affect the structure of the
database.
List of DDL Commands
Command Description
CREATE Creates new database objects (tables, views, indexes, etc.).
Modifies existing database objects (adding/removing columns, constraints,
ALTER
etc.).
Deletes an existing database object (removes table, view, or index
DROP
permanently).
TRUNCATE Deletes all records from a table but retains its structure.
COMMENT Adds comments to database objects for documentation.
RENAME Renames database objects (table, column, etc.).

1. CREATE Command – Creating Database Objects


The CREATE command is used to create databases, tables, indexes, and views.
1.1 Creating a Database
CREATE DATABASE SchoolDB;
This command creates a new database named SchoolDB.
1.2 Creating a Table
CREATE TABLE Students (

12
Student_ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT CHECK (Age >= 18),
Email VARCHAR(100) UNIQUE,
Course VARCHAR(50) DEFAULT 'Undeclared'
);
1.3 Creating an Index (for Faster Searching)
CREATE INDEX idx_student_name ON Students(Name);
This command creates an index on the Name column for faster searching.

2. ALTER Command – Modifying Table Structure


The ALTER command allows us to add, modify, or delete columns and constraints in an
existing table.
2.1 Adding a New Column
ALTER TABLE Students ADD Address VARCHAR(255);
Adds a new column Address to the Students table.
2.2 Modifying a Column Data Type
ALTER TABLE Students MODIFY Age INT NOT NULL;
Changes the Age column to NOT NULL, meaning it cannot contain empty values.
2.3 Renaming a Column
ALTER TABLE Students RENAME COLUMN Course TO Course_Name;
Renames the Course column to Course_Name.
2.4 Dropping a Column
ALTER TABLE Students DROP COLUMN Address;
Removes the Address column from the Students table.
2.5 Adding a Constraint
ALTER TABLE Students ADD CONSTRAINT chk_age CHECK (Age >= 18);
Adds a CHECK constraint to ensure Age is 18 or above.

3. DROP Command – Deleting Database Objects


The DROP command is used to permanently remove databases, tables, indexes, or views.

3.1 Dropping a Table


DROP TABLE Students;
Deletes the Students table permanently along with all its data.
3.2 Dropping a Database
DROP DATABASE SchoolDB;
Deletes the SchoolDB database permanently.
3.3 Dropping an Index
DROP INDEX idx_student_name ON Students;
Deletes the idx_student_name index.

13
4. TRUNCATE Command – Deleting All Records from a Table
The TRUNCATE command removes all rows from a table but keeps the table structure
TRUNCATE TABLE Students;
This deletes all student records but keeps the table for future use.
Difference Between DELETE and TRUNCATE
Feature DELETE TRUNCATE
Removes Data? Yes, based on condition Yes, all records
Keeps Table
Yes Yes
Structure?
Can Be Rolled Yes (if inside a
No (cannot be undone)
Back? transaction)
Faster No (slow for large Yes (fast because it does not log
Performance? tables) individual row deletions)

5. COMMENT Command – Adding Descriptions


The COMMENT command allows adding documentation to database objects.
COMMENT ON COLUMN Students.Name IS 'Stores the full name of the student';
This comment will help developers understand the purpose of the Name column.

6. RENAME Command – Changing Object Names


The RENAME command renames a database object, such as tables or columns.
6.1 Renaming a Table
ALTER TABLE Students RENAME TO Student_Info;
Changes the table name from Students to Student_Info.

14
Lab Assignment 1
Q.1 Create a table student which contain attributes like roll no.,dob,gender,class,college,city
and marks.

Q.2 Insert any 5 records

Q.3 Display the information of all the students

Q.4 Display detailed structure of student table

15
Q.5 Display rollno and class of Noida students

Q.6 Display all the information in descending of marks

Q.7 Change the marks of roll no 5 to 89

Q.8 Change the name and city of roll no 3

Q.9 Delete the names of Noida students

Q.10 Delete the records of students where marks is less than 80.

16
EXPERIMENT 3
Title: Apply the integrity constraints like Primary Key, Foreign key, Check, NOT NULL,
etc. to the tables.

Objective:
• To understand and implement integrity constraints in SQL to ensure data accuracy
and consistency.
• To apply Primary Key constraint to uniquely identify records in a table.
• To enforce Foreign Key constraints for maintaining referential integrity between
tables.
• To use NOT NULL constraint to prevent null values in essential fields.
• To apply the CHECK constraint to enforce specific conditions on column values.
• To implement the DEFAULT constraint to assign a default value when no value is
provided.
• To gain practical experience in designing robust and reliable relational databases.

Theory:
Integrity constraints are rules enforced on a database to maintain accuracy, consistency, and
reliability of data. These constraints ensure that only valid data is stored in the database by
defining specific conditions that must be met by the data. The most commonly used integrity
constraints in SQL are:

1. Primary Key Constraint


• A Primary Key (PK) is a unique identifier for each record in a table.
• It ensures that the column values are unique and not NULL.
• A table can have only one primary key, which may consist of a single column or
multiple columns (Composite Key).
Example:
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary INT
);

2. Foreign Key Constraint


• A Foreign Key (FK) establishes a relationship between two tables.
• It ensures referential integrity, meaning the foreign key in one table must reference a
valid primary key in another table.
• Prevents deletion or modification of referenced records that are being used in another
table.
Example:
CREATE TABLE Department (
dept_id INT PRIMARY KEY,

17
dept_name VARCHAR(50),
emp_id INT,
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);

3. NOT NULL Constraint


• The NOT NULL constraint ensures that a column cannot have NULL values.
• It is used when a column must always contain a value (e.g., Name, Age, Email).
Example:
CREATE TABLE Student (
student_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL
);

4. CHECK Constraint
• The CHECK constraint ensures that column values meet a specified condition.
• It is used to enforce domain integrity (e.g., age should be above 18).
Example:
ALTER TABLE Student
ADD CONSTRAINT chk_age CHECK (age >= 18);

5. DEFAULT Constraint
• The DEFAULT constraint assigns a default value to a column when no value is
provided during insertion.
Example:
ALTER TABLE Student
ADD COLUMN city VARCHAR(50) DEFAULT 'Delhi';

18
Lab assignment 2
Q1:Create table emp having primary key as, emp(emp_id primary
key,emp_name,emp_salary)

Q2: Create table dept with foreign key (dept_id primary key,dept_name,emp_id foreign
key(emp_id) references emp(emp_id))

Q.3 Create table emp having one unique column as(emp_id unique,emp_name)

Q.4 Create table student with not null constraint

Q5: Apply check constraint in student table Q6: Apply default constraint in student table

19
EXPERIMENT 4
Title: Experiments based on basic DML commands – SELECT, INSERT, UPDATE and
DELETE

Objective:
To understand and perform basic Data Manipulation Language (DML) operations, including
SELECT, INSERT, UPDATE, and DELETE commands in SQL. These commands help in
retrieving, modifying, and managing data within a database table.

Theory:
Data Manipulation Language (DML) is a subset of SQL used for managing data within
database tables. The key DML commands include:
1. SELECT – Retrieves data from one or more tables.
SELECT * FROM employees;
SELECT name, age FROM students WHERE age > 18;
2. INSERT – Adds new records into a table.
INSERT INTO employees (id, name, salary) VALUES (1, 'John Doe', 50000);
3. UPDATE – Modifies existing records in a table.
UPDATE employees SET salary = 60000 WHERE id = 1;
4. DELETE – Removes records from a table.
DELETE FROM employees WHERE id = 1;
These operations are essential for maintaining and manipulating the data stored in relational
databases efficiently.

20
Lab Assignment 3
Q.1 Create a table employee(emp no., emp name, job, hire_date, salary, commission,
department no., age ).

Q.2 Insert any 5 records

Q.3 Display the info of all employee

Q.4 Display total salary paid to clerk

Q.5 Display max salary of employee who belongs to department no.=10

21
Q.6 Display max, min, average salary of department no.=30

Q.7 Count no. of employee where job is salesman

Q.8 What is the difference between maximum and minimum salary of employee in
organization ?

Q.9 How many jobs are available in organization?

Q.10 How many job titles are available?

22
EXPERIMENT 5
Title: Write the queries for implementing Built-in functions, GROUP BY, HAVING and
ORDER BY.

Objective:
To learn and implement SQL queries using Built-in functions, GROUP BY, HAVING, and
ORDER BY to perform data aggregation, filtering, and sorting operations in a relational
database.

Theory:
SQL provides various functionalities to manipulate and analyze data efficiently. Some of the
key concepts include:
1. Built-in Functions:
SQL provides several built-in functions that help in performing operations on data:
1. Aggregate Functions: SUM(), AVG(), MAX(), MIN(), COUNT()
2. String Functions: UPPER(), LOWER(), LENGTH(), CONCAT()
3. Date Functions: NOW(), CURDATE(), YEAR(), MONTH()
SELECT MAX(salary) FROM employee;
SELECT UPPER(emp_name) FROM employee;

2. GROUP BY Clause:
The GROUP BY clause is used to group rows that have the same values in specified
columns and perform aggregate functions on them.
SELECT department_no, AVG(salary)
FROM employee
GROUP BY department_no;

3. HAVING Clause:
The HAVING clause is used to filter groups after aggregation. It works with GROUP
BY, unlike WHERE, which filters individual rows.
SELECT department_no, COUNT(*)
FROM employee
GROUP BY department_no
HAVING COUNT(*) > 5;

4. ORDER BY Clause:
The ORDER BY clause is used to sort the result set in ascending (ASC) or
descending (DESC) order.
SELECT emp_name, salary
FROM employee
ORDER BY salary DESC;

23
Lab Assignment 4
Question 1: Create a table with the following structure:
SaleID (Product , Category , Amount , SaleDate)
(1 , Laptop , Electronics , 50000 , 2024-01-15)
(2 , TV , Electronics , 40000 , 2024-01-18)
(3 , Shirt , Clothing , 2000 , 2024-01-20)
(4 , Laptop , Electronics , 55000 , 2024-02-05)
(5 , Shirt , Clothing , 2500 , 2024-02-10 )

Question 2: Find products that have been sold more than once.

Question 3: Find the average sale amount per category, but only for categories with
more than one sale.

24

You might also like