ANNAMACHARAYA INSTITUTE OF TECHNOLOGY AND SCIENCES
PIGLIPUR, BATASINGRAM, HYDERABAD
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
DATA BASE MANAGEMENT SYSTEM
LAB MANUAL
FACULTY: [Link]
FOR
B TECH CSE/CSM
2ND YEAR- SEM-II(R22)
NAME OF THE FACULTY HOD-CSE
CONTENTS
P
[Link]
Week-No List Of Experiments No
1 Week-1 Concept design with E-R Model
2 Week-2 Relational Model
3 Week-3 Normalization
4 Week-4 Practicing DDL commands
5 Week-5 Practicing DML commands
Week-6 A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
6
B. Nested, , Correlated sub queries
Week-7 Queries using Aggregate functions, GROUP BY, HAVING and Creation and
7
dropping of Views.
8 Week-8 Triggers (Creation of insert trigger, delete trigger, update trigger)
9 Week-9 Procedures
10 Week-10 Usage of Cursors
Instructions to Students
Before Entering the Lab (Mandatory)
Students must carry the following:
1. College-issued Identity Card
2. Class Notes
3. Lab Observation Book
4. Lab Manual
5. Lab Record
During the Lab Session
Sign in and sign out in the register without fail.
Arrive on time; students who are more than 15 minutes late will not be allowed to attend the
lab.
Maintain 100% attendance; strict action will be taken otherwise.
Follow the prescribed dress code while in the lab.
Food and drinks are strictly prohibited inside the lab.
Leave all bags at the designated place.
Seek assistance from the lab staff if help is needed with equipment or procedures.
Respect the laboratory environment and other users.
Keep your workspace clean and tidy after completing the experiment.
Read the lab manual carefully before coming to the lab and be prepared.
Perform experiments strictly according to the instructions in the manual.
Copy all class-taught programs into the observation book before the lab session.
Do not use floppy disks or pen drives without permission from the lab in-charge.
Submit the lab record on or before the specified due date.
WEEK-1: CONCEPT DESIGN WITH E-R MODEL
An Entity-Relationship (ER) Model is a graphical representation of entities, attributes, and
relationships.
The Entity-Relationship Model, or simply ER Model, is a high-level data model diagram.
In this model, real-world problems are represented pictorially, making them easier for
stakeholders to understand. It also helps developers understand the system by just looking at
the ER diagram.
It is used to develop a conceptual design for the database and provides a simple and easy-to-
understand view of data.
In ER modeling, the database structure is represented as a diagram called an Entity-
Relationship Diagram (ERD).
Example: Suppose we are designing a school database. In this database, Student will be an entity
with attributes like Name, ID, Age, and Address. The Address itself can be another entity with
attributes like City, Street Name, and Pin Code. There will be a relationship between Student and
Address
ER diagram has the following three components:
Entities:
An entity represents a real-world object or concept that can be identified and distinguished from
other objects. It is depicted as a rectangle in an ER diagram. Example: In a university database,
entities could include Student, Course, Professor, and Department
Weak Entity
An entity that depends on another entity is called a weak entity. A weak entity does not have a
key attribute of its own and relies on a strong entity for its identification. In an ER diagram, a
weak entity is represented by a double rectangle.
strong entity
A strong entity is complete by itself and does not depend on any other entity. It possesses a
primary key that uniquely identifies each instance in the entity set. This means any element in the
strong entity set can be uniquely identified.
In an ER diagram, a strong entity is represented by a rectangle with a single line, unlike a weak
entity, which is represented by a double rectangle.
Attributes
Attributes are the properties or characteristics of entities. They describe the details or qualities
of an entity.
In an ER diagram, attributes are represented by ovals connected to their respective entity
rectangles.
Example: For a Student entity, possible attributes could include StudentID, Name,
DateOfBirth, etc.
Types of Attributes: There are different types of attributes, as discussed below:
Simple Attribute
Composite Attribute
Single-Valued Attribute
Multi-Valued Attribute
Derived Attribute
Complex Attribute
Stored Attribute
Key Attribute
Null Attribute
Descriptive Attribute
[Link] Attribute
A simple attribute is an attribute that cannot be further subdivided into components.
Example: The roll number of a student, the ID number of an employee, gender, etc.
2. Composite Attribute
A composite attribute is an attribute that can be split into smaller components.
Example:
Address can be divided into House Number, Street, City, State, Country, and Pin
Code.
Name can be divided into First Name, Middle Name, and Last Name.
3. Single-Valued Attribute
A single-valued attribute takes only one value for each entity instance.
Example: Age of a student, Aadhar card number.
4. Multi-Valued Attribute
A multi-valued attribute can take multiple values for each entity instance and is represented by
a double oval in ER diagrams.
Example: A student’s phone numbers: Landline and Mobile.
5. Stored Attribute
A stored attribute is an attribute whose value is physically stored in the database and does not
require further computation.
Example: Date of Birth (DOB) of a student.
6. Derived Attribute
A derived attribute is an attribute whose value can be derived from other attributes. It is
represented by a dotted oval in ER diagrams.
Example:
Total and average marks of a student.
Age of an employee derived from Date of Birth.
7. Complex Attribute
A complex attribute is formed by nesting composite and multi-valued attributes. These are
rarely used in DBMS.
Example:
Address can be a complex attribute because it is composite (Street, City, State, PIN
Code) and can be multi-valued (one person may have multiple addresses).
Representation:
Components of a complex attribute are grouped using parentheses ( ).
Multi-valued components are represented using curly braces { }.
Components are separated by commas ,.
8. Key Attribute
A key attribute uniquely identifies an entity in an entity set.
Example: Roll Number uniquely identifies a student.
9. Null Attribute
A null attribute is an attribute that may have a NULL value when the entity does not have a value
for it.
Example: Net Banking Active in a customer table may be NULL for customers who have not
activated net banking.
10. Descriptive Attribute
AN attribute of a relationship is called a descriptive attribute. For example, consider the
relationship between Employee and Department: an employee works for a department. Here,
works for is the relationship between the Employee and Department entities. The relationship
works for can have an attribute, such as DATE_OF_JOIN, which is a descriptive attribute of the
relationship.
Relationships and Relationship Sets
Relationship
A relationship is used to describe the association between entities. A diamond (or rhombus) is used to
represent a relationship in an ER diagram.
Types of Relationships are as follows:
In a one-to-one relationship, each record in the first entity (A) is associated with exactly one
record in the second entity (B), and vice versa.
It is represented in an ER diagram by a line connecting the two entities, with the
cardinality notation “1” on both ends of the line.
Example: A Student entity may be associated with exactly one Address entity, and each
Address belongs to exactly one Student.
One-to-Many Relationship
In a one-to-many relationship, each record in the first entity (A) can be associated with many
records in the second entity (B), but each record in the second entity (B) is associated with at
most one record in the first entity (A).
It is represented in an ER diagram by a line connecting the two entities, with the
cardinality notation “1” on the first entity’s side and “N” (or “M”) on the second entity’s
side.
Example: A Department entity may have many Employees, but each Employee is
associated with only one Department.
Many-to-One Relationship
In a many-to-one relationship, many records in the first entity (A) can be associated with one
record in the second entity (B), but each record in the second entity (B) is associated with at
most one record in the first entity (A).
It is represented in an ER diagram by a line connecting the two entities, with the
cardinality notation “N” (or “M”) on the first entity’s side and “1” on the second entity’s
side.
Example: Many Orders can be placed by one Customer, but each Order is associated
with only one Customer.
Many-to-Many Relationship
In a many-to-many relationship, each record in the first entity (A) can be associated with many
records in the second entity (B), and vice versa.
It is represented in an ER diagram by a line connecting the two entities, with the
cardinality notation “N” (or “M”) on both sides of the line.
Example: Many Students can enroll in many Courses, and each Course can have many
Students.
Relationship Sets
Formally, a relationship is a mathematical relation defined on n ≥ 2 (possibly non-distinct) entity
sets.
If E₁, E₂, …, Eₙ are entity sets, then a relationship set R is a subset of
E₁ × E₂ × … × Eₙ,
where each element of R represents a relationship among the participating entities.
Degree of a Relationship Set
The degree of a relationship set is defined as the number of entity sets that participate in the
relationship set.
Degree of a relationship set=Number of participating entity set
s
Types of Relationship Sets
On the basis of the degree of a relationship set, relationship sets can be classified into different
types.
1. Unary Relationship Set
A unary relationship set is a relationship set in which only one entity set participates.
It is also known as a recursive relationship.
Example:
A Person is married to another Person.
2. Binary Relationship Set
A binary relationship set is a relationship set in which two entity sets participate.
Example:
A Student is enrolled in a Course.
3. Ternary Relationship Set
A ternary relationship set is a relationship set in which three entity sets participate.
Example:
A Supplier supplies a Part to a Project.
4. N-ary Relationship Set
An n-ary relationship set is a relationship set in which ‘n’ entity sets participate, where n > 3.
Example:
A relationship among Doctor, Patient, Medicine, and Hospital.
Additional Features of the ER Model / Extended Features of the ER Model
As the complexity of data increased, it became more difficult to use the traditional ER Model for
database modeling. Hence, some additional features were added to the existing ER Model to
handle complex applications more effectively.
Six new concepts (the first three are the most important) were added to the existing ER Model:
1. Generalization
2. Specialization
3. Aggregation
4. Key constraints
5. Participation constraints
6. Weak entity
Generalization
Generalization is the process of identifying common attributes from multiple entities and
creating a higher-level generalized entity. It follows a bottom-up approach, where two or more
entities are combined into one general entity if they share common attributes.
For example, the entities STUDENT and FACULTY can be generalized into a higher-level
entity called PERSON. Common attributes such as P_NAME and P_ADD are included in the
PERSON entity, while specific attributes like S_FEE remain in the STUDENT entity.
Specialization
Specialization is the process of dividing a higher-level entity into two or more lower-level
entities based on specific characteristics. It follows a top-down approach.
For example, the EMPLOYEE entity can be specialized into DEVELOPER, TESTER, etc.
Common attributes such as E_NAME and E_SAL remain in the EMPLOYEE entity, while
specialized attributes like TES_TYPE belong to the TESTER entity.
Aggregation
Aggregation is the process of combining two or more entities and their relationship into a single
higher-level entity. This is done when individual entities do not convey complete meaning on
their own. Aggregation helps represent complex relationships in a clear and meaningful way.
EXPERIMENT – 2: RELATIONAL MODEL (STUDENT MANAGEMENT)
AIM:
To represent all entities (strong and weak) in tabular format and their relationships in a tabular
form. Implement tables in MySQL and demonstrate sample data with outputs.
1. STUDENT ENTITY
Description: Stores personal information of students.
Column Name Data Type Constraint Type of Attribute
StudentID varchar(10) Primary Key Single-valued
Name varchar(50) - Composite
Age int - Single-valued
Gender char(2) - Simple
ContactNo varchar(15) Must be 10-digit Multi-valued
Address varchar(50) - Composite
MySQL Query:
CREATE TABLE Student (
StudentID varchar(10) PRIMARY KEY,
Name varchar(50),
Age int,
Gender char(2),
ContactNo varchar(15),
Address varchar(50)
);
DESC Student;
Sample Data:
StudentID Name Age Gender ContactNo Address
S001 Alekhya 20 F 9492500000 Hyd
S002 Krupani 22 F 9492511111 Sec
S003 Rohit 21 M 9492522222 Mumbai
Explanation:
StudentID is the primary key. Each student has personal information including name, age,
gender, contact, and address.
2. COURSE ENTITY
Description: Stores information about courses.
Column Name Data Type Constraint Type of Attribute
CourseID varchar(10) Primary Key Single-valued
CourseName varchar(50) - Simple
Credits int - Single-valued
MySQL Query:
CREATE TABLE Course (
CourseID varchar(10) PRIMARY KEY,
CourseName varchar(50),
Credits int
);
DESC Course;
Sample Data:
CourseID CourseName Credits
C101 Database Systems 4
C102 Operating Systems 3
CourseID CourseName Credits
C103 Mathematics 3
Explanation:
CourseID uniquely identifies a course. Each course has a name and credit value.
3. ENROLLMENT ENTITY (WEAK ENTITY)
Description: Stores which student is enrolled in which course.
Column Name Data Type Constraint Type of Attribute
StudentID varchar(10) Foreign Key Single-valued
CourseID varchar(10) Foreign Key Single-valued
Semester varchar(10) - Simple
Grade varchar(2) - Simple
MySQL Query:
CREATE TABLE Enrollment (
StudentID varchar(10),
CourseID varchar(10),
Semester varchar(10),
Grade varchar(2),
PRIMARY KEY(StudentID, CourseID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID),
FOREIGN KEY(CourseID) REFERENCES Course(CourseID)
);
DESC Enrollment;
Sample Data:
StudentID CourseID Semester Grade
S001 C101 Sem1 A
S001 C103 Sem1 B+
S002 C101 Sem1 B
S003 C102 Sem1 A
Explanation:
Enrollment is a weak entity depending on both Student and Course. It shows which students are
taking which courses, in which semester, and their grades.
4. DEPARTMENT ENTITY
Description: Stores department information.
Column Name Data Type Constraint Type of Attribute
DeptID varchar(10) Primary Key Single-valued
DeptName varchar(50) - Simple
HOD varchar(50) - Single-valued
MySQL Query:
CREATE TABLE Department (
DeptID varchar(10) PRIMARY KEY,
DeptName varchar(50),
HOD varchar(50)
);
DESC Department;
Sample Data:
DeptID DeptName HOD
D01 CSE Prof. Rao
D02 ECE Prof. Kumar
Explanation:
Departments are strong entities with unique IDs, names, and head of department info.
5. STUDENT-DEPARTMENT RELATIONSHIP
Description: Each student belongs to a department.
Column Name Data Type Constraint Type of Attribute
StudentID varchar(10) Primary Key, FK Single-valued
DeptID varchar(10) Foreign Key Single-valued
MySQL Query:
CREATE TABLE StudentDepartment (
StudentID varchar(10),
DeptID varchar(10),
PRIMARY KEY(StudentID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID),
FOREIGN KEY(DeptID) REFERENCES Department(DeptID)
);
DESC StudentDepartment;
Sample Data:
StudentID DeptID
S001 D01
S002 D01
S003 D02
Explanation:
Shows which student belongs to which department. StudentID is primary and foreign key.
Sample Queries and Outputs
1. View all students in a department:
SELECT [Link], [Link], [Link], [Link]
FROM Student s
JOIN StudentDepartment sd ON [Link] = [Link]
JOIN Department d ON [Link] = [Link]
WHERE [Link]='CSE';
Output:
Name Age Gender DeptName
Alekhya 20 F CSE
Name Age Gender DeptName
Krupani 22 F CSE
2. View all courses a student is enrolled in:
SELECT [Link], [Link], [Link], [Link]
FROM Enrollment e
JOIN Student s ON [Link] = [Link]
JOIN Course c ON [Link] = [Link]
WHERE [Link]='S001';
Output:
Name CourseName Semester Grade
Alekhya Database Systems Sem1 A
Alekhya Mathematics Sem1 B+
3. Count total students:
SELECT COUNT(*) AS TotalStudents FROM Student;
Output: TotalStudents = 3
Do you want me to do that next?
EXPERIMENT – 3
NORMALIZATION (STUDENT EXAMPLE)
AIM
To apply database normalization techniques (1NF, 2NF, 3NF, BCNF) for designing relational
database tables for student management, minimizing redundancy and avoiding anomalies.
INTRODUCTION
Normalization is the process of organizing data in a database to:
Reduce redundancy
Improve data integrity
Avoid insertion, update, and deletion anomalies
It involves decomposing larger tables into smaller, well-structured tables.
STEP-BY-STEP NORMALIZATION
1️FIRST NORMAL FORM (1NF)
Definition
A table is in 1NF if:
All attributes are atomic (single-valued)
No multi-valued attributes are allowed
Example (Not in 1NF)
Student Table (Unnormalized)
StudentID Name Courses ContactNo
101 Ramesh Math, Physics 9999900001, 9999900002
102 Sita Chemistry 9999900003
❌ Courses and ContactNo have multiple values
Conversion to 1NF
Student Table (1NF)
StudentID Name Course ContactNo
101 Ramesh Math 9999900001
101 Ramesh Physics 9999900002
102 Sita Chemistry 9999900003
✅ Atomic values achieved
✅ Table is now in 1NF
2️SECOND NORMAL FORM (2NF)
Definition
A table is in 2NF if:
It is in 1NF
All non-key attributes are fully dependent on the primary key
No partial dependency exists
Example (Partial Dependency)
Student Table with Composite Key (StudentID, Course)
StudentID Course Instructor Dept
101 Math Mr. Rao Science
101 Physics Mrs. Mehta Science
102 Chemistry Mr. Sharma Science
Primary Key: (StudentID, Course)
Partial Dependencies:
Course → Instructor, Dept
❌ Violates 2NF
Conversion to 2NF
StudentInfo Table
StudentID Name
101 Ramesh
102 Sita
Course Table
Course Instructor Dept
Math Mr. Rao Science
Physics Mrs. Mehta Science
Chemistry Mr. Sharma Science
StudentCourse Table (Linking)
StudentID Course
101 Math
101 Physics
102 Chemistry
✅ Partial dependencies removed
✅ Tables in 2NF
[Link] NORMAL FORM (3NF)
Definition
A table is in 3NF if:
It is in 2NF
No transitive dependency exists
Every non-key attribute depends only on the primary key
Example (Transitive Dependency)
Student Table
StudentID Name DeptID DeptName
101 Ramesh D01 Science
102 Sita D01 Science
Transitive Dependency:
StudentID → DeptID → DeptName
❌ Violates 3NF
Conversion to 3NF
StudentInfo Table
StudentID Name DeptID
101 Ramesh D01
102 Sita D01
Department Table
DeptID DeptName
D01 Science
✅ Transitive dependency removed
✅ Tables in 3NF
4️BOYCE-CODD NORMAL FORM (BCNF)
Definition
A table is in BCNF if for every functional dependency (X → Y):
X is a super key
✅ Stronger than 3NF
In our example:
StudentID is the primary key in StudentInfo → satisfies BCNF
Course is the primary key in Course → satisfies BCNF
SQL IMPLEMENTATION (STUDENT DATABASE)
CREATE TABLE Department(
DeptID VARCHAR(5) PRIMARY KEY,
DeptName VARCHAR(20)
);
CREATE TABLE StudentInfo(
StudentID INT PRIMARY KEY,
Name VARCHAR(20),
DeptID VARCHAR(5),
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
CREATE TABLE Course(
Course VARCHAR(20) PRIMARY KEY,
Instructor VARCHAR(20),
DeptID VARCHAR(5),
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
CREATE TABLE StudentCourse(
StudentID INT,
Course VARCHAR(20),
PRIMARY KEY(StudentID, Course),
FOREIGN KEY (StudentID) REFERENCES StudentInfo(StudentID),
FOREIGN KEY (Course) REFERENCES Course(Course)
);
SAMPLE OUTPUT
Department Table
DeptID DeptName
D01 Science
StudentInfo Table
StudentID Name DeptID
101 Ramesh D01
102 Sita D01
Course Table
Course Instructor DeptID
Math Mr. Rao D01
Physics Mrs. Mehta D01
Chemistry Mr. Sharma D01
StudentCourse Table
StudentID Course
101 Math
101 Physics
102 Chemistry
EXPLANATION
By applying Normalization (1NF → BCNF) in the Student database:
Redundancy minimized
Data consistency maintained
Anomalies avoided
Efficient and scalable design achieved
✅ Database now follows 3NF/BCNF, ensuring high data integrity.
EXPERIMENT – 4
PRACTICING DDL COMMANDS
AIM
To study and execute DDL (Data Definition Language) commands for creating and altering
tables in Roadway Travels database.
DDL (Data Definition Language) is used to define, modify and remove database objects
such as tables.
DDL commands affect the structure of tables, not the data inside them.
DDL COMMANDS
CREATE TABLE – Creates a new table
ALTER TABLE – Modifies table structure
TRUNCATE TABLE – Deletes all records but keeps structure
DROP TABLE – Deletes table permanently
RENAME TABLE – Renames an existing table
1. CREATE TABLE COMMAND
Definition
The CREATE TABLE command is used to create a new table with specified columns, data
types and constraints.
Syntax
CREATE TABLE table_name (
column_name data_type constraints,
...
);
Example 1: BUS Table
CREATE TABLE Bus (
Bus_No VARCHAR(5),
Source VARCHAR(20),
Destination VARCHAR(20),
DaysPerWeek INT
);
Output
Query OK, 0 rows affected
View Structure
DESC Bus;
Table Structure
Field Type Null Key
Bus_No varchar(5) YES
Source varchar(20) YES
Destination varchar(20) YES
DaysPerWeek int YES
Example 2: PASSENGER Table
CREATE TABLE Passenger (
PNRNo INT,
TicketNo INT,
Name VARCHAR(20),
Age INT,
Sex CHAR(1),
PPNo INT
);
DESC Passenger;
Structure
Field Type
PNRNo int
TicketNo int
Name varchar(20)
Age int
Sex char(1)
PPNo int
Example 3: RESERVATION Table
CREATE TABLE Reservation (
PNR_NO INT(9),
No_of_Seats INT(8),
Address VARCHAR(50),
Contact_No BIGINT(12),
Status VARCHAR(10)
);
DESC Reservation;
Example 4: CANCELLATION Table
CREATE TABLE Cancellation (
PNR_NO INT(9),
No_of_Seats INT(8),
Address VARCHAR(50),
Contact_No BIGINT(12),
Status CHAR(3)
);
DESC Cancellation;
Example 5: TICKET Table (Primary Key & NOT NULL)
CREATE TABLE Ticket (
Ticket_No INT(9) PRIMARY KEY,
Age INT,
Sex CHAR(4) NOT NULL,
Source VARCHAR(20),
Destination VARCHAR(20),
Dep_Time VARCHAR(4)
);
DESC Ticket;
2. ALTER TABLE COMMAND
Definition
The ALTER TABLE command is used to add, modify or delete columns and constraints in
an existing table.
a) Add Column
ALTER TABLE Reservation
ADD Fare INT;
Output
Query OK, 0 rows affected
DESC Reservation;
b) Drop Column
ALTER TABLE Reservation
DROP COLUMN Fare;
c) Modify Column
ALTER TABLE Reservation
MODIFY COLUMN Status VARCHAR(10);
d) Add Foreign Key
ALTER TABLE Passenger
ADD FOREIGN KEY (PNRNo) REFERENCES Reservation(PNR_NO);
ALTER TABLE Cancellation
ADD FOREIGN KEY (PNR_NO) REFERENCES Reservation(PNR_NO);
Extra ALTER Examples
Create Passenger2 Table
CREATE TABLE Passenger2 (
PassportId INT PRIMARY KEY,
Name VARCHAR(10) NOT NULL,
Age INT NOT NULL,
Sex CHAR,
Address VARCHAR(20) NOT NULL
);
DESC Passenger2;
Add Column
ALTER TABLE Passenger3
ADD COLUMN TicketNo VARCHAR(10);
Modify Column Size
ALTER TABLE Passenger3
MODIFY COLUMN Name VARCHAR(20);
Drop Foreign Key
ALTER TABLE Passenger
DROP FOREIGN KEY fk1;
Drop Column
ALTER TABLE Passenger2
DROP COLUMN TicketNo;
3. TRUNCATE TABLE
Definition
The TRUNCATE TABLE command deletes all rows from a table but retains its structure.
TRUNCATE TABLE Reservation;
Output
Query OK, 0 rows affected
4. RENAME TABLE
Definition
The RENAME TABLE command is used to change the name of a table.
RENAME TABLE Passenger TO PassengerInfo;
Output
Query OK, 0 rows affected
SUMMARY TABLE
Command Usage
CREATE TABLE Creates a new table
ALTER TABLE ADD Adds new column
ALTER TABLE DROP Deletes a column
ALTER TABLE MODIFY Changes column datatype
ADD FOREIGN KEY Adds relationship
TRUNCATE TABLE Deletes all records
RENAME TABLE Renames a table
WEEK – 5
PRACTICING DML COMMANDS ON ROADWAY TRAVELS TABLES
AIM
To study and practice DML (Data Manipulation Language) commands such as INSERT,
UPDATE, DELETE and SELECT on Roadway Travels database tables like Bus, Passenger
and Reservation.
DML COMMANDS
DML commands are used to insert, update, delete and retrieve data from database tables.
1. INSERT COMMAND
Description
The INSERT command is used to add new rows (records) into a table.
Syntax
INSERT INTO table_name VALUES(value1, value2, ...);
OR
INSERT INTO table_name(column1, column2, ...)
VALUES(value1, value2, ...);
Example Tables
BUS Table
BusNo Source Destination Seats
Inserting Data into BUS Table
INSERT INTO Bus VALUES('w1234','Hyderabad','Tirupathi',4);
INSERT INTO Bus VALUES('p2345','Hyderabad','Banglore',3);
INSERT INTO Bus VALUES('9w01','Hyderabad','Kolkata',4);
Output
Query OK, 1 row affected
BUS Table After Insertion
BusNo Source Destination Seats
w1234 Hyderabad Tirupathi 4
p2345 Hyderabad Banglore 3
9w01 Hyderabad Kolkata 4
PASSENGER Table
PNRNo BusNo Name Age Sex TicketNo
Inserting Data into PASSENGER Table
INSERT INTO Passenger VALUES(1,1,'Sachin',12,'M',1234);
INSERT INTO Passenger VALUES(2,2,'Rahul',34,'M',3456);
INSERT INTO Passenger VALUES(3,3,'Swetha',24,'F',8734);
INSERT INTO Passenger VALUES(4,3,'Rohith',24,'M',734);
PASSENGER Table After Insertion
PNRNo BusNo Name Age Sex TicketNo
1 1 Sachin 12 M 1234
2 2 Rahul 34 M 3456
3 3 Swetha 24 F 8734
4 3 Rohith 24 M 734
2. UPDATE COMMAND
Description
The UPDATE command is used to modify existing records in a table.
Syntax
UPDATE table_name
SET column_name = new_value
WHERE condition;
⚠ If WHERE clause is omitted, all rows will be updated.
Example
Update passenger age where PNRNo = 2.
UPDATE Passenger
SET Age = 43
WHERE PNRNo = 2;
Output
Query OK, 1 row affected
PASSENGER Table After Update
PNRNo Name Age
2 Rahul 43
UPDATE on BUS Table
UPDATE Bus2
SET Source = 'Secundrabad'
WHERE BusNo = 1234;
3. DELETE COMMAND
Description
The DELETE command removes one or more rows from a table.
Syntax
DELETE FROM table_name WHERE condition;
Example
Delete passenger with PNRNo = 3.
DELETE FROM Passenger
WHERE PNRNo = 3;
Output
1 row deleted
Passenger Table After Delete
PNRNo Name
1 Sachin
2 Rahul
4 Rohith
Delete from BUS Table
DELETE FROM Bus2 WHERE BusNo = 1234;
4. SELECT COMMAND
Description
The SELECT command retrieves data from a table.
a) Display All Records
SELECT * FROM Passenger;
Output
Displays all rows and columns of Passenger table.
b) Elimination of Duplicates (DISTINCT)
SELECT DISTINCT Age FROM Passenger;
Output
Age
12
24
43
c) Retrieve Specific Columns
SELECT Name, Age, Sex FROM Passenger;
Output
Name Age Sex
Sachin 12 M
Rahul 43 M
Rohith 24 M
5. EXPERIMENT – BUS2 & PASSENGER2
BUS2 Table After Insert
BusNo Source Destination
1234 Hyderabad Tirupathi
2345 Hyderabad Banglore
23 Hyderabad Kolkata
45 Tirupathi Banglore
BusNo Source Destination
34 Hyderabad Chennai
PASSENGER2 Table
PNRNo Name Age Sex TicketNo
145 Ramesh 45 M abc123
278 Geetha 36 F abc124
4590 Ram 30 M abc12
6789 Ravi 50 M abc14
5622 Seetha 32 F abc55
WEEK-6
To study and practice SQL querying using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNION, INTERSECT, JOINS, Constraints, Nested and Correlated
Subqueries with suitable examples.
TABLE STRUCTURE USED
SAILORS
sid sname rating age
22 Dustin 7 45
31 Lubber 8 55
32 Andy 8 25
58 Rusty 10 35
RESERVES
sid bid
22 103
sid bid
31 103
32 104
BOATS
bid bname color
101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red
1. UNION
Definition
UNION combines the results of two SELECT queries into a single result set and removes
duplicate rows.
Query
Find sailor IDs who have rating ≥ 8 OR reserved boat 103
SELECT sid FROM sailors WHERE rating >= 8
UNION
SELECT sid FROM reserves WHERE bid = 103;
Output
sid
22
31
32
58
2. INTERSECT
Definition
INTERSECT returns only common rows from two queries.
Query
Find sailor IDs who have rating ≥ 8 AND reserved boat 103
SELECT sid FROM sailors WHERE rating >= 8
INTERSECT
SELECT sid FROM reserves WHERE bid = 103;
Output
sid
31
3. IN Operator
Definition
IN checks whether a value exists in a subquery result.
Query
Find names of sailors who reserved boat 103
SELECT sname
FROM sailors
WHERE sid IN (SELECT sid FROM reserves WHERE bid = 103);
Output
sname
Dustin
Lubber
4. NOT IN Operator
Definition
NOT IN checks whether a value does NOT exist in a subquery.
Query
Find sailors who never reserved boat 103
SELECT sname
FROM sailors
WHERE sid NOT IN (SELECT sid FROM reserves WHERE bid = 103);
Output
sname
Andy
Rusty
5. ANY Operator
Definition
ANY compares a value with any one value returned by the subquery.
Query
Find sailors whose rating is better than some sailor named Horatio
SELECT sid
FROM sailors
WHERE rating > ANY
(SELECT rating FROM sailors WHERE sname='Horatio');
Output
sid
31
58
6. ALL Operator
Definition
ALL compares a value with all values returned by a subquery.
Query
Find sailors with the highest rating
SELECT sid
FROM sailors
WHERE rating >= ALL (SELECT rating FROM sailors);
Output
sid
58
7. EXISTS
Definition
EXISTS returns TRUE if the subquery returns at least one row.
Query
Find sailors who reserved boat 103
SELECT sname
FROM sailors s
WHERE EXISTS
(SELECT * FROM reserves r WHERE [Link]=103 AND [Link]=[Link]);
Output
sname
Dustin
Lubber
8. JOINS
Definition
JOIN is used to retrieve data from multiple tables based on a common attribute.
Query
Find sailors who reserved red boats
SELECT [Link]
FROM sailors s, boats b, reserves r
WHERE [Link]=[Link]
AND [Link]=[Link]
AND [Link]='red';
Output
sname
Dustin
Lubber
9. Nested Subquery
Definition
A subquery written inside another SQL query.
Query
SELECT sname
FROM sailors
WHERE sid IN
(SELECT sid FROM reserves WHERE bid=103);
Output
sname
Dustin
Lubber
10. Correlated Subquery
Definition
A correlated subquery depends on the outer query and executes once for each row.
Query
SELECT sname
FROM sailors s
WHERE EXISTS
(SELECT * FROM reserves r
WHERE [Link]=103 AND [Link]=[Link]);
Output
sname
Dustin
Lubber
11. Constraints
Definition
Constraints enforce rules to maintain data integrity.
Example
CREATE TABLE Sailors(
sid INT PRIMARY KEY,
sname VARCHAR(30) NOT NULL,
rating INT,
age DOUBLE
);
Passenger Database Queries
Passenger Table
passportid name age sex
82306 Ramu 40 M
82308 Aakash 40 M
82403 Avinash 42 M
1. Unique PNR Numbers
SELECT DISTINCT pnr_no FROM reservation;
Output
pnr_no
10201
10202
10203
2. Male Passengers
SELECT name FROM passenger WHERE sex='M';
Output
name
Ramu
Aakash
Avinash
3. Ticket Numbers and Names
SELECT ticketno, name FROM passenger;
Output
ticketno name
82306 Ramu
82308 Aakash
4. Names start with R and end with H
SELECT name FROM passenger WHERE name LIKE 'R%H';
Output
name
Ramesh
Rajesh
5. Age between 30 and 45
SELECT name FROM passenger WHERE age BETWEEN 30 AND 45;
Output
name
Ramu
Aakash
Avinash
6. Names starting with A
SELECT name FROM passenger WHERE name LIKE 'A%';
Output
name
Aakash
Avinash
7. Sorted Passenger Names
SELECT name FROM passenger ORDER BY name;
Output
name
Aakash
Avinash
Ramu
WEEK-7: QUERIES USING AGGREGATE FUNCTIONS, GROUP BY, HAVING AND
CREATION AND DROPPING OF VIEWS.
To practice MySQL queries using:
1. Aggregate functions (SUM, AVG, MIN, MAX, COUNT)
2. GROUP BY and HAVING clauses
3. Creating and dropping Views
AGGREGATE FUNCTIONS SUMMARY
Function Description
COUNT() Counts rows (including NULLs if specified)
SUM() Returns total sum of a column (ignores NULL)
AVG() Returns average of a column
MIN() Returns minimum value
MAX() Returns maximum value
1. Display information from passenger and cancellation tables
Query:
SELECT * FROM passenger
UNION
SELECT * FROM cancellation;
Explanation:
Combines data from both tables into a single result.
UNION removes duplicates; use UNION ALL if you want to keep duplicates.
Example Output:
PNR_NO Name Age No_of_Seats Status
10201 Ramesh 25 2 CONFIRM
10202 Sita 30 2 CONFIRM
10203 Amit 22 2 CONFIRM
2. Display the minimum age of the passenger
Query:
SELECT MIN(age) AS min_age FROM passenger;
Explanation:
MIN() finds the smallest value in the column.
Example Output:
min_age
22
3. Find number of tickets booked for each PNR_NO using GROUP BY
Query:
SELECT PNR_NO, SUM(No_of_Seats) AS total_seats
FROM reservation2
GROUP BY PNR_NO;
Explanation:
Groups the reservation table by PNR_NO.
SUM(No_of_Seats) calculates total seats booked for each PNR.
Example Output:
PNR_NO total_seats
10201 2
10202 2
10203 3
4. Find distinct PNR_NO
Query:
SELECT DISTINCT PNR_NO
FROM reservation2;
Explanation:
Returns only unique PNR_NO values.
Example Output:
PNR_NO
10201
10202
10203
5. Find total number of cancelled seats
Query:
SELECT SUM(No_of_Seats) AS cancelled_seats
FROM cancellation2;
Example Output:
cancelled_seats
6
6. Find maximum age of a passenger
Query:
SELECT MAX(age) AS max_age FROM passenger;
Example Output:
max_age
30
7. Find minimum age of a passenger
Query:
SELECT MIN(age) AS min_age FROM passenger;
Example Output:
min_age
22
GROUP BY and HAVING Example
Find PNR_NO and total tickets booked where seats > 1
Query:
SELECT PNR_NO, SUM(No_of_Seats) AS total_seats
FROM reservation2
GROUP BY PNR_NO
HAVING SUM(No_of_Seats) > 1;
Explanation:
GROUP BY groups records by PNR_NO.
HAVING filters groups after aggregation.
Example Output:
PNR_NO total_seats
10201 2
10202 2
10203 3
8. Display number of days a bus is available
Query:
SELECT days_per_week
FROM bus
WHERE Bus_No = '9W01';
Example Output:
days_per_week
VIEWS
What is a View?
A view is a virtual table based on another table or combination of tables.
Does not store data itself.
Changes in base tables reflect in the view.
Used for security and reducing redundancy.
Creating a View
Example:
CREATE VIEW BStudents AS
SELECT [Link], [Link], [Link]
FROM students s
JOIN enrolled e ON [Link] = [Link]
WHERE [Link] = 'B';
Query the view:
SELECT * FROM BStudents;
Example Output:
name sid cid
Ramesh 101 1
Sita 102 2
Updatable Views
Create an updatable view:
CREATE VIEW Emp_vw AS
SELECT Empno, Ename, Deptno FROM Employee;
Insert into view:
INSERT INTO Emp_vw VALUES (1126, 'Brijesh', 20);
Update through view:
UPDATE Emp_vw SET Deptno = 30 WHERE Empno = 1125;
Delete through view:
DELETE FROM Emp_vw WHERE Empno = 1122;
Dropping a View
Syntax:
DROP VIEW view_name;
Example:
DROP VIEW BStudents;
WEEK 8: MYSQL TRIGGERS
Aim
Creation of INSERT, DELETE, and UPDATE triggers in MySQL.
1. What is a Trigger?
A trigger is a set of SQL statements that execute automatically in response to changes in a table
(INSERT, UPDATE, DELETE).
Purpose:
Maintain data integrity
Automate auditing
Enforce business rules
Types of Triggers:
1. Row-Level Trigger: Fires once for each row affected.
2. Statement-Level Trigger: Fires once per SQL statement, regardless of affected rows.
2. Trigger Events
A trigger can be fired by:
1. DML Statements: INSERT, UPDATE, DELETE
2. DDL Statements: e.g., CREATE, ALTER, DROP
3. System Events: Startup, shutdown, error
4. User Events: Login, logoff
MySQL supports: DML triggers (INSERT, UPDATE, DELETE) only.
3. Trigger Timing
BEFORE: Executes before the data is modified.
AFTER: Executes after the data is modified.
4. Types of Triggers in MySQL
Trigger Type When it fires
BEFORE INSERT Before inserting data
AFTER INSERT After inserting data
BEFORE UPDATE Before updating data
Trigger Type When it fires
AFTER UPDATE After updating data
BEFORE DELETE Before deleting data
AFTER DELETE After deleting data
5. Trigger Syntax
CREATE TRIGGER trigger_name
trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic here
END;
trigger_time = BEFORE / AFTER
trigger_event = INSERT / UPDATE / DELETE
table_name = table associated with the trigger
FOR EACH ROW specifies a row-level trigger
6. Example Triggers
6.1 INSERT Trigger
Goal: Maintain a running sum of amounts inserted into account table.
CREATE TABLE account (
acct_num INT,
amount DECIMAL(10,2)
);
SET @sum = 0;
CREATE TRIGGER ins_sum
BEFORE INSERT ON account
FOR EACH ROW
SET @sum = @sum + [Link];
INSERT INTO account VALUES (1, 14.98), (2, 1937.50), (3, -100.00);
SELECT @sum AS 'Total amount inserted';
-- Output: 1852.48
6.2 UPDATE Trigger
Goal: Validate values before updating.
CREATE TRIGGER updcheck1
BEFORE UPDATE ON passengerticket
FOR EACH ROW
BEGIN
IF [Link] > 60 THEN
SET [Link] = [Link];
ELSE
SET [Link] = 0;
END IF;
END;
Example Use:
UPDATE passengerticket SET TicketNo = 70 WHERE id = 1;
-- Ensures TicketNo > 60; otherwise sets it to 0
6.3 DELETE Trigger
Goal: Log deleted rows into an audit table.
CREATE TABLE bus_audit1 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
source VARCHAR(10),
changedon DATETIME,
action VARCHAR(10)
);
CREATE TRIGGER before_bus_delete
BEFORE DELETE ON bus
FOR EACH ROW
BEGIN
INSERT INTO bus_audit1 SET action = 'Delete', source = [Link], changedon = NOW();
END;
6.4 Multiple Table Trigger Example (Audit Trail)
CREATE TABLE employees (
empid INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
hire_date DATE
);
CREATE TABLE employees_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
empno INT,
lastname VARCHAR(30),
updated_name VARCHAR(30),
changedate DATETIME,
action VARCHAR(30)
);
CREATE TRIGGER be_up
BEFORE UPDATE ON employees
FOR EACH ROW
INSERT INTO employees_audit
SET action='Update', empno=[Link], lastname=OLD.last_name,
updated_name=NEW.last_name, changedate=NOW();
Testing Trigger:
UPDATE employees SET last_name='Sharma' WHERE empid=2;
SELECT * FROM employees_audit;
Output: Shows the audit of the change.
6.5 Conditional Trigger Example
Goal: Send reminders if birthdate is NULL.
CREATE TABLE members (
id INT,
name VARCHAR(40),
email VARCHAR(40),
birthdate DATE
);
CREATE TABLE reminders (
id INT AUTO_INCREMENT PRIMARY KEY,
memberid INT,
message VARCHAR(40)
);
DELIMITER //
CREATE TRIGGER af_in
AFTER INSERT ON members
FOR EACH ROW
BEGIN
IF [Link] IS NULL THEN
INSERT INTO reminders(memberid, message)
VALUES ([Link], CONCAT('Hi ', [Link], ' Pl. Update your date of birth.'));
END IF;
END;
//
DELIMITER ;
7. Useful Commands
Show triggers:
SHOW TRIGGERS;
Drop trigger:
DROP TRIGGER trigger_name;
WEEK-9 (PROCEDURES)
Aim
To create, execute, and understand stored procedures using IN, OUT, and INOUT
parameters in MySQL.
Stored Procedures
A stored procedure is a collection of pre-compiled SQL statements stored in the database and
executed as a single unit.
It works like a subprogram and can accept parameters and return values.
Stored procedures were introduced in MySQL 5 and are supported by most relational database
systems.
Advantages of Stored Procedures
Code reusability
Faster execution
Reduced network traffic
Improved security
Easy maintenance
Syntax to Create a Stored Procedure
DELIMITER &&
CREATE PROCEDURE procedure_name
([IN | OUT | INOUT] parameter_name datatype, ...)
BEGIN
SQL statements;
END &&
DELIMITER ;
Types of Procedure Parameters
1. IN Parameter
Default parameter
Used to pass values into the procedure
Value cannot be modified inside the procedure
2. OUT Parameter
Used to return values from the procedure
Value is set inside the procedure
3. INOUT Parameter
Works as both input and output
Value passed in can be modified and returned
Calling a Stored Procedure
CALL procedure_name(parameter(s));
Assume Table: student_info
stud_id stud_code name marks
1 101 Ravi 85
2 102 Anu 65
3 103 Kiran 90
4 104 Meena 72
1. Procedure without Parameters
Aim:To display students scoring more than 70 marks and count total students.
DELIMITER &&
CREATE PROCEDURE get_merit_student()
BEGIN
SELECT * FROM student_info WHERE marks > 70;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END &&
DELIMITER ;
Execution
CALL get_merit_student();
2. Procedure with IN Parameter
Aim:To display records based on user-given limit.
DELIMITER &&
CREATE PROCEDURE get_student(IN var1 INT)
BEGIN
SELECT * FROM student_info LIMIT var1;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END &&
DELIMITER ;
Execution
CALL get_student(4);
3. Procedure with OUT Parameter
Aim:To find the highest marks in the table.
DELIMITER &&
CREATE PROCEDURE display_max_mark(OUT highestmark INT)
BEGIN
SELECT MAX(marks) INTO highestmark FROM student_info;
END &&
DELIMITER ;
Execution
CALL display_max_mark(@M);
SELECT @M;
4. Procedure with INOUT Parameter
Aim:To retrieve marks of a student using student ID.
DELIMITER &&
CREATE PROCEDURE display_marks(INOUT var1 INT)
BEGIN
SELECT marks INTO var1
FROM student_info
WHERE stud_id = var1;
END &&
DELIMITER ;
Execution
SET @M = 3;
CALL display_marks(@M);
SELECT @M;
Difference Between Triggers and Procedures
Feature Triggers Procedures
Execution Automatic User-called
Parameters Not allowed Allowed
Return values No Yes
WEEK-10 (USAGE OF CURSOR)
To declare a cursor that defines a result set, open the cursor to establish the result set, fetch the
data into local variables one row at a time, and close the cursor after processing.
Cursors
In MySQL, a cursor is used to process the rows returned by a query one row at a time.
Normally, SQL statements work on the entire result set at once, but when individual row
processing is required, cursors are used.
A cursor allows us to:
Iterate through a result set
Perform operations on each row separately
Handle complex logic inside stored procedures
Cursors are mainly used inside stored procedures.
Steps to Use a Cursor
1. Declare a cursor
2. Open the cursor
3. Fetch rows from the cursor
4. Close the cursor
1. Declaration of Cursor
A cursor is declared using the DECLARE [Link] must be declared after variables and
before executable statements.
Each cursor must have a unique name and be associated with a SELECT statement.
Syntax
DECLARE cursor_name CURSOR FOR select_statement;
2. Open Cursor Statement
The OPEN statement executes the cursor’s SELECT query and prepares the result set for
fetching.
Syntax
OPEN cursor_name;
3. Fetch Cursor Statement
The FETCH statement retrieves the next row from the cursor and stores it into variables.
Syntax
FETCH cursor_name INTO variable1, variable2;
If a row exists, the cursor pointer moves to the next row.
4. Close Cursor Statement
The CLOSE statement releases the cursor and frees memory.
Syntax
CLOSE cursor_name;
If not closed explicitly, the cursor is automatically closed at the end of the procedure.
Neat Example Using Cursor in MySQL
Table: students
sid sname
1 Ravi
2 Anu
3 Kiran
Stored Procedure Using Cursor
DELIMITER $$
CREATE PROCEDURE p1 (IN in_customer_id INT)
BEGIN
DECLARE v_id INT;
DECLARE v_name VARCHAR(20);
DECLARE v_finished INT DEFAULT 0;
-- Declare cursor
DECLARE c1 CURSOR FOR
SELECT sid, sname FROM students WHERE sid = in_customer_id;
-- Handler to detect end of result set
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
-- Open cursor
OPEN c1;
-- Loop to fetch rows
std: LOOP
FETCH c1 INTO v_id, v_name;
IF v_finished = 1 THEN
LEAVE std;
END IF;
-- Display fetched data
SELECT CONCAT(v_id, ' ', v_name) AS Student_Details;
END LOOP std;
-- Close cursor
CLOSE c1;
END$$
DELIMITER ;
Calling the Procedure
CALL p1(1);
Output
1 Ravi
Explanation of the Example
Cursor c1 selects student details based on student ID
OPEN executes the SELECT query
FETCH retrieves one row at a time
Loop continues until no rows are left
Handler detects end of cursor
Cursor is closed after execution
EXTRA-FOR THE PURPOSE OF PRACTICING
SQL COMMANDS
Definition: SQL commands that define, modify, or delete the structure of database objects
(tables, schemas, indexes).
Purpose: To create or change the database structure.
1. DDL – Data Definition Language
Common Commands:
CREATE – Create a table, database, or other object.
ALTER – Modify an existing table (add, drop, or change columns).
DROP – Delete a table or database permanently.
TRUNCATE – Remove all rows from a table but keep the table structure.
RENAME – Rename a table or column.
2. DML – Data Manipulation Language
Definition: SQL commands that manipulate the data inside database tables.
Purpose: To insert, update, or delete data records.
Common Commands:
INSERT – Add new records to a table.
UPDATE – Modify existing records.
DELETE – Remove specific records.
3. DCL – Data Control Language
Definition: SQL commands that control access and permissions for database users.
Purpose: To manage who can view or manipulate data.
Common Commands:
GRANT – Give privileges to a user.
REVOKE – Remove privileges from a user.
4. TCL – Transaction Control Language
Definition: SQL commands that manage transactions to maintain database integrity.
Purpose: To ensure changes are applied correctly or undone if needed.
Common Commands:
COMMIT – Save all changes permanently.
ROLLBACK – Undo changes that are not yet saved.
SAVEPOINT – Set a point to rollback to within a transaction.
5. DQL – Data Query Language
Definition: SQL commands that retrieve or query data from database tables.
Purpose: To read data from one or more tables.
Common Command:
SELECT – Retrieve data, with optional filters (WHERE), sorting (ORDER BY), or
aggregations (COUNT, SUM).
💡 Quick Tip:
Command Type Works On Example Purpose
DDL Structure Create table, drop table
DML Data Insert, update, delete records
DCL Access Grant or revoke permissions
TCL Transactions Commit or rollback changes
DQL Data Select and query records
Step 1: Create Database (Optional)
CREATE DATABASE SchoolDB;
USE SchoolDB;
Output:
Database SchoolDB is created and selected.
Step 2: DDL Commands (Table Structure)
a) CREATE TABLE
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Grade VARCHAR(5)
);
Execution Steps:
1. Open SQL environment.
2. Run the CREATE TABLE command.
Output:
Table Students is created. No rows yet.
Check Table Structure:
DESCRIBE Students;
Field Type Null Key Default Extra
StudentID INT NO PRI NULL
Name VARCHAR(50) YES NULL
Age INT YES NULL
Grade VARCHAR(5) YES NULL
b) ALTER TABLE (Add Column)
ALTER TABLE Students
ADD Email VARCHAR(100);
Output:
Email column added.
Check Table Structure Again:
DESCRIBE Students;
Field Type Null Key Default Extra
StudentID INT NO PRI NULL
Name VARCHAR(50) YES NULL
Age INT YES NULL
Grade VARCHAR(5) YES NULL
Email VARCHAR(100) YES NULL
c) DROP TABLE (Optional Test)
-- DROP TABLE Students;
Be careful: This deletes the table completely.
Usually we don’t run it until the lab ends.
Step 3: DML Commands (Manipulate Data)
a) INSERT Rows
INSERT INTO Students (StudentID, Name, Age, Grade, Email)
VALUES
(1, 'Alice', 15, 'A', 'alice@[Link]'),
(2, 'Bob', 16, 'B', 'bob@[Link]'),
(3, 'Charlie', 17, 'C', 'charlie@[Link]');
Output:
StudentID Name Age Grade Email
1 Alice 15 A alice@[Link]
2 Bob 16 B bob@[Link]
3 Charlie 17 C charlie@[Link]
b) UPDATE Data
UPDATE Students
SET Grade = 'A+'
WHERE Name = 'Alice';
Output:
StudentID Name Age Grade Email
1 Alice 15 A+ alice@[Link]
2 Bob 16 B bob@[Link]
3 Charlie 17 C charlie@[Link]
c) DELETE Row
DELETE FROM Students
WHERE StudentID = 3;
Output:
StudentID Name Age Grade Email
1 Alice 15 A+ alice@[Link]
2 Bob 16 B bob@[Link]
Step 4: DCL Commands (Permissions)
a) GRANT
GRANT SELECT, INSERT ON Students TO 'user1';
Gives user1 the right to view and insert data in the Students table.
b) REVOKE
REVOKE INSERT ON Students FROM 'user1';
user1 can now only view, not insert.
Step 5: TCL Commands (Transactions)
a) COMMIT
INSERT INTO Students (StudentID, Name, Age, Grade, Email)
VALUES (4, 'David', 15, 'B+', 'david@[Link]');
COMMIT;
Saves changes permanently.
b) ROLLBACK
INSERT INTO Students (StudentID, Name, Age, Grade, Email)
VALUES (5, 'Eve', 16, 'A', 'eve@[Link]');
ROLLBACK;
Row Eve is not saved.
c) SAVEPOINT
SAVEPOINT BeforeFrank;
INSERT INTO Students (StudentID, Name, Age, Grade, Email)
VALUES (6, 'Frank', 17, 'B', 'frank@[Link]');
ROLLBACK TO BeforeFrank;
Row for Frank is removed.
Other committed rows remain.
Step 6: DQL Commands (Query Data)
a) Select All
SELECT * FROM Students;
Output:
StudentID Name Age Grade Email
1 Alice 15 A+ alice@[Link]
2 Bob 16 B bob@[Link]
4 David 15 B+ david@[Link]
b) Conditional SELECT
SELECT Name, Grade FROM Students WHERE Age > 15;
Name Grade
Bob B
c) Aggregate SELECT
SELECT COUNT(*) AS TotalStudents FROM Students;
TotalStudents
3
TotalStudents
Command Type Example Command Output / Effect
DDL CREATE TABLE Students (...) Creates table structure
DDL ALTER TABLE Students ADD Email Adds new column
DML INSERT INTO Students ... Adds rows to table
DML UPDATE Students SET ... Modifies existing rows
DML DELETE FROM Students ... Deletes specific rows
DCL GRANT SELECT, INSERT ... Gives user access
DCL REVOKE INSERT ... Removes specific permissions
TCL COMMIT Saves transaction permanently
TCL ROLLBACK Reverts changes before commit
TCL SAVEPOINT ... ROLLBACK TO ... Rollback to a specific point
DQL SELECT * FROM Students Retrieves table data
DQL SELECT COUNT(*) ... Retrieves aggregate data
SQL Command Types – Definitions
Command Type Definition Purpose / Use
Commands that define or modify the To create, alter, or delete
DDL (Data Definition
structure of database objects like tables, tables, databases, or other
Language)
schemas, and indexes. objects.
DML (Data
Commands that manipulate the data inside To insert, update, or delete
Manipulation
tables. records.
Language)
DCL (Data Control Commands that control user access and To grant or revoke privileges
Language) permissions in the database. to users.
Command Type Definition Purpose / Use
TCL (Transaction Commands that manage database To commit, rollback, or
Control Language) transactions to maintain consistency. savepoints for transactions.
To select and query data,
DQL (Data Query Commands that retrieve data from
including conditions and
Language) database tables.
aggregates.
Short Explanation with Examples
1. DDL – Data Definition Language
o CREATE: Makes a new table or database.
o ALTER: Changes table structure (add/remove columns).
o DROP: Deletes a table or database.
o TRUNCATE: Deletes all rows but keeps the table.
o RENAME: Changes the name of a table.
2. DML – Data Manipulation Language
o INSERT: Adds new rows.
o UPDATE: Changes existing rows.
o DELETE: Removes rows from the table.
3. DCL – Data Control Language
o GRANT: Gives permissions (e.g., SELECT, INSERT).
o REVOKE: Removes permissions.
4. TCL – Transaction Control Language
o COMMIT: Saves changes permanently.
o ROLLBACK: Undoes uncommitted changes.
o SAVEPOINT: Marks a point to rollback to within a transaction.
5. DQL – Data Query Language
o SELECT: Retrieves data from tables.
o Can use conditions (WHERE), aggregates (COUNT, SUM), and sorting (ORDER
BY).
THE END