0% found this document useful (0 votes)
9 views60 pages

Practical - RDMS

The document outlines a practical file for a course on Relational Database Management Systems, detailing various SQL operations such as creating tables, inserting data, and querying information. It includes specific tasks like creating student and course enrollment tables, truncating data, and using SQL procedures for cursors and triggers. The document serves as a guide for students to understand fundamental database concepts and SQL syntax through hands-on exercises.
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)
9 views60 pages

Practical - RDMS

The document outlines a practical file for a course on Relational Database Management Systems, detailing various SQL operations such as creating tables, inserting data, and querying information. It includes specific tasks like creating student and course enrollment tables, truncating data, and using SQL procedures for cursors and triggers. The document serves as a guide for students to understand fundamental database concepts and SQL syntax through hands-on exercises.
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/ 60

GURU NANAK DEV UNIVERSITY

University Institute of Technology


Department of Electronics Technology

Relational Database Management System


(Practical File)
Course Code: CSL-332

Submitted By:
B.Tech ECM Sem-5
(Batch 2022-26)
LIST OF PRACTICALS
S.No Name of Practical
1 Create a table named as Stu_info with columns
as Roll_No, Name, Ph_no, Email_id.

2 Create a table named as Course_Enrolled with


columns as Roll_No, Department, Name.

3 Truncate the above created tables.

4 Insert 10 rows into the above created tables.

5 Insert 5 rows into the table named as


Course_enrolled with dept value as CSE, 5
rows with dept value as Punjabi and 5 as
Electronics.

6 Select all the rows from table Course_enrolled


in which dept value is CSE.

7 Select Names and Addresses column from table


Stu_info.

8 Select details of students from Stu_info and


order them by their names.

9 Select Roll_no, Name and Email_id from


Stu_info and make a new table named as
Student with them.

10 Update all the rows of Course_enrolled table


having values as CSE with values as DCSE.
11 Add a new column named as Aggr_perc into
Course_enrolled.

12 Delete the column named as Name from table


Course_enrolled.

13 Rename the table and write a sub-query to find


the details of students having second highest
Roll_no from Student table.

14 Drop the Stu_info table if already exists and


then create the new table Stu_info with Roll_no
values as unique and not null.
15 Write a SQL procedure to show the use of
cursors.

16 Write a SQL procedure to show the use of


triggers.

17 Write a SQL procedure to handle use of


triggers.
Aim: Create a table named as Stu_info with
columns as Roll_No, Name, Ph_no, Email_id.

Theory of Practical:
In SQL, creating a table is a fundamental operation used to define the structure of
the data you want to store in a database. To create a table, we use the CREATE
TABLE statement, followed by the table name and the columns with their
respective data types. This structure is essential for defining how data is stored
and accessed in the database.

For our table Stu_info:

 Roll_no: This column will store unique student roll numbers. It is an integer,
as roll numbers are typically numeric.
 Names: This column will store students' names. We'll use a text or character-
based data type to accommodate various names.
 Ph_no: This column will store students' phone numbers. It can also be
represented as a string to accommodate any formatting (like country codes).
 Email_id: This column will store email addresses, so a text or character-
based data type will be used.

SQL Query to Create Table:


CREATE TABLE Stu_info (

Roll_no INT PRIMARY KEY,

Names VARCHAR(50),

Ph_no (INT),

Email_id VARCHAR(50)

);
EXPLANATION:
1.CREATE TABLE Stu_info: This command creates a new table named
Stu_info.

2.Roll_no INT PRIMARY KEY: This column Roll_no is an integer and is set as
the primary key (unique for each student).

3.Names VARCHAR(50): This column Names stores the name of the student.
VARCHAR(100) allows names of up to 50 characters.

4.ph_no : Stores the student‟s phone number as an integer (INT).

5.Email_id VARCHAR(50): The Email_id column stores email addresses, with


up to 100 characters.

Sample Output (if you query to view table structure)


After running the table creation SQL statement, you can use a query like
DESCRIBE Stu_info; to view the structure.

Field Type Null Key Default Extra


Roll_no INT NO PRI NULL
Names VARCHAR(50) YES NULL
Ph_no (int) YES NULL
Email_id VARCHAR(50) YES NULL

Workbench Output:
In this output:
 Field represents the column names.
 Type indicates the data type of each column.
 Null shows whether the column can store NULL values.
 Key displays whether the column is part of any key constraints (e.g., PRI
for primary key).
 Default shows the default value for the column if not specified.
 Extra includes any additional constraints or properties.
Aim: Create a table named as Course_Enrolled
with columns as Roll_No, Department, Name.

Theory of Practical
This SQL program demonstrates fundamental database operations such as table
creation, data insertion, and data retrieval.

Table Creation: A table in SQL is a structured set of data that consists of rows
and columns. In this case, the table Course_Enrolled is designed to store
information about students enrolled in various departments.

Roll_No: It is designated as the Primary Key, meaning it must be unique for each
record and cannot be NULL.

Name: A text field representing the name of the student. It is marked as NOT
NULL, meaning that this field must have a value.

Department: A text field representing the department in which the student is


enrolled.

Data Insertion: After defining the table structure, the program proceeds to insert
records into the Course_Enrolled table. Each INSERT INTO statement adds a
new student record with values for Roll_No(which is unique), name, and
Department.

Data Retrieval: Finally, the program includes a SELECT statement to fetch and
display all records in the Course_Enrolled table. This is useful for verifying that
the data was inserted correctly. This command retrieves all columns (*) for each
record in the Course_Enrolled table, displaying the information about each
enrolled student.

This program is a simple demonstration of creating a table, inserting data, and


retrieving it using SQL statements, providing a foundational example of relational
database management.

Creating Table
Inserting Values

Output
Aim: Truncate the above created tables.

Theory of Practical
Structured Query Language is a standard Database language that is used to
create, maintain, and retrieve the relational database. In this article, we will
discuss this in detail about SQL. Following are some interesting facts about
SQL. Let‟s focus on that.

SQL is case insensitive. But it is a recommended practice to use keywords


(like SELECT, UPDATE, CREATE, etc.) in capital letters and use user-
defined things (like table name, column name, etc.) in small letters.

RDMS(Relational database management system):-A relational database


means the data is stored as well as retrieved in the form of relations (tables).

Creating Table 1

Queries used to create the table 1 are :-


 CREATE TABLE student_info: This command creates a new table called
student_info in the database.

 Roll_no BIGINT(147) : Defines a column named Roll_no of type INT


(integer). By setting it as PRIMARY KEY, it ensures each roll number is
unique across the table, and it cannot be NULL.

 Name VARCHAR(255): Creates a column called Name with a data type of


VARCHAR(50), which can store variable-length strings up to 50
characters.
 Email_id VARCHAR(255): Creates a column called Email_id with a data
type of VARCHAR(100), allowing strings up to 100 characters to store
email addresses.

 INSERT INTO: This command inserts new data into a specified table.

Output

Creating Table 2:-

Queries used to create the table 2 are :-


 CREATE TABLE Course_enrolled: This command creates a new table
named Course_enrolled.

 Roll_no INT: Defines a column named Roll_no of type INT, which will
store the roll number of the student.

 Department VARCHAR(50): Creates a column named Department to


store the department name as a string up to 50 characters.
 Name VARCHAR(50): Creates a column named Name to store the name
of the course, also up to 50 characters.

 INSERT INTO: This command inserts new data into a specified table.

Output

TRUNCATING THE TABLES:-

The TRUNCATE TABLE command deletes the data inside a table, but not the
table itself.

The DROP TABLE command deletes a table in the database.

 TRUNCATE TABLE student_info;: This command removes all rows


from the stu_info table without deleting the table itself. It‟s faster than
DELETE because it doesn‟t log individual row deletions.

 TRUNCATE TABLE Course_enrolled;: Similarly, this command


removes all rows from the Course_enrolled table.
Output
Aim: Insert 10 rows into the above created
tables.

Theory of Practical
This experiment focuses on understanding and applying fundamental database
concepts using SQL (Structured Query Language) for data definition and data
manipulation. By working with relational tables, we learn the following core
database principles:

1. Relational Database Model: Relational databases store data in tables,


where each table represents an entity (e.g., students or course enrollments)
and consists of columns (attributes) and rows (records). This model
supports organized data storage and relationships between different data
entities.

2. Primary Key: The primary key is a unique identifier for each record in a
table, ensuring that each row can be referenced individually. In this
experiment, the Roll_No field in the Stu_info table serves as the primary
key, uniquely identifying each student.

3. Foreign Key: A foreign key is a field in one table that uniquely identifies a
row in another table, creating a relationship between the two tables. Here,
the Roll_No in the Course_Enrolled table is a foreign key that references
Roll_No in Stu_info. This foreign key constraint enforces referential
integrity, ensuring that each enrollment record corresponds to a valid
student in Stu_info.

4. Data Insertion: Inserting rows into tables helps populate the database with
sample data. This step simulates real-world data entry, allowing for further
operations like querying and updating.

Procedure
Step 1: Create the Stu_info Table.
Table Name: Stu_info – This table will store basic information about
students.
Columns:

• Roll_No (INT): A unique identifier for each student, acting as the primary
key.
• Name (VARCHAR(50)): The name of the student, with a maximum of 50
characters, and cannot be null.
• Ph_no (VARCHAR(15)): The student's phone number, allowing up to 15
characters to accommodate various formats.

• Email_id (VARCHAR(50)): The email address of the student, with a


maximum length of 50 characters.

Using PRIMARY KEY on Roll_No ensures that each student has a unique roll
number in the Stu_info table.

Step 2: Create the Course_Enrolled Table.


• Table Name: Course_Enrolled – This table holds the department
information for students based on their roll numbers.

• Columns:
o Roll_No (INT): This column links each entry to a specific student in the
Stu_info table using their roll number. o Department (VARCHAR(50)):
The department in which the student is enrolled, allowing up to 50
characters.

o Name (VARCHAR(50)): The student's name for easier reference.


The FOREIGN KEY constraint on Roll_No links Course_Enrolled to
Stu_info, enforcing referential integrity. Each roll number in Course_Enrolled
must already exist in Stu_info.

Step 3: Insert Rows into Stu_info Table.


Step 4: Insert Rows into Course_Enrolled Table.

In this step, 10 entries are added to Course_Enrolled. Each


entry has:
• A Roll_No matching a student in Stu_info.

• A Department specifying the department in which the student is enrolled.

• A Name field matching the student's name in Stu_info for readability.


Aim: Insert 5 rows into the table named as
Course_enrolled with dept value as CSE, 5
rows with dept value as Punjabi and 5 as
Electronics.

Theory of Practical
To insert 15 rows into a table named `course_enrolled` with
the following department (`dept`) values:

- 5 rows with dept = "CSE" (Computer Science and Engineering)


- 5 rows with dept = "Punjabi"
- 5 rows with dept = "Electronics"

Requirements
- A database table named `course_enrolled` with at least one column `dept` to
store department values.
- Basic knowledge of SQL INSERT INTO statements.

Background
The `INSERT INTO` statement in SQL is used to insert data into a table. You
can:
1. Insert a single row using:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2,
...);

2. Insert multiple rows at once using:


INSERT INTO table_name (column1) VALUES (value1), (value2), ...;

In this experiment, we will insert department values into the `course_enrolled`


table to simulate enrollment across different departments.

Steps
1. Connect to the database containing the `course_enrolled` table.
2. Prepare an `INSERT INTO` SQL statement to add rows with the specified
department values.
3. Execute the SQL statements to insert 15 rows:
- Insert 5 rows with dept = "CSE"
- Insert 5 rows with dept = "Punjabi"
- Insert 5 rows with dept = "Electronics"

SQL Queries
To insert the data into the table, use the following SQL statements:

-- Insert rows for the "CSE" department


INSERT INTO course_enrolled (dept) VALUES
('CSE'), ('CSE'), ('CSE'), ('CSE'), ('CSE');

-- Insert rows for the "Punjabi" department


INSERT INTO course_enrolled (dept) VALUES
('Punjabi'), ('Punjabi'), ('Punjabi'), ('Punjabi'), ('Punjabi');

-- Insert rows for the "Electronics" department


INSERT INTO course_enrolled (dept) VALUES
('Electronics'), ('Electronics'), ('Electronics'), ('Electronics'), ('Electronics');

Screenshots
Screenshot of the SQL Query execution in MySQL
Workbench:

Screenshot of the table data after insertion:


Output
The table `course_enrolled` will now contain 15 rows, with `dept` values
distributed as follows:
- 5 rows with "CSE"
- 5 rows with "Punjabi"
- 5 rows with "Electronics"

Conclusion
This experiment demonstrates the use of SQL `INSERT INTO` statements to
populate a table with specific values across multiple rows. This process is
fundamental for database management tasks involving data insertion.
Aim: Select all the rows from table
Course_enrolled in which dept value is CSE.

Theory of Practical
In this experiment, we aim to retrieve specific data from a database using SQL
queries. SQL (Structured Query Language) is used to interact with databases,
enabling the retrieval, insertion, updating, and deletion of data.The focus of this
experiment is to select all rows from the Course_enrolled table where the dept
column equals CSE. This type of query is a basic SELECT statement with a
WHERE clause that filters results based on a specified condition.

Key Concepts:
1)SELECT Statement: Used to fetch data from a database.

2)WHERE Clause: Filters records to only include rows that meet the specified
condition.

3)Table Structure: For this experiment, the table Course_enrolled includes


columns such as student_id, course_id, dept, and other relevant information.

SQL Query:
Here's the SQL query to select all rows from Course_enrolled where the dept is
CSE:

• SELECT * FROM Course_enrolledWHERE dept = 'CSE';

Example Result: Imagine the Course_enrolled table has the following sample
data

Output Of the Query :


The above output table would be the result of the SQL query SELECT * FROM
Course_enrolled WHEREdept = 'CSE';
Aim: Select Names and Addresses column
from table Stu_info.

Theory of Practical
This practical is designed to demonstrate the process of retrieving specific data
from a table in a relational database using SQL (Structured Query Language).
SQL is the standard language used for managing and manipulating relational
databases. In this case, we are performing a simple *SELECT* operation to fetch
specific columns (name and address) from a table called stu_info.

The experiment aims to help understand the process of querying specific data
from a table, focusing on:

1. *Relational Database Management System (RDBMS)*: An RDBMS organizes


data into tables with rows and columns. Each row represents a record, and each
column represents a specific attribute of the data.

2. *SQL SELECT Statement: The **SELECT* statement is the most commonly


used SQL command to retrieve data from a table. In this experiment, the SELECT
statement is used to specify the columns to retrieve, which are name and address
in this case.

3. *Understanding SQL Query Syntax*: Writing and executing a valid SQL query
helps understand the interaction between the query and the RDBMS.

SQL Query:

1. *SELECT*: This keyword tells the RDBMS which columns to fetch. In this
case, it specifies two columns: name and address.
2. *name, address*: These are the names of the columns you wish to retrieve from
the stu_info table.

3. *FROM stu_info*: This specifies the table from which to retrieve the data, i.e.,
stu_info. When you run this query, it will return all the rows from the Stu_info
table but only show the Names and Addresses columns. This is useful when you
only need specific information rather than all the data in the table.

Sample Input:

To select the address and name from a database using SQL, you would typically
use a query like this:

SELECT name, address FROM your_table_name; Here's a breakdown of the


query:

1. SELECT: This keyword is used to specify which columns you want to retrieve
from the database.

2. name, address: These are the specific columns you want to retrieve. You can
list multiple columns separated by commas.

3. FROM: This keyword indicates the table from which you want to select the
data.

4. your_table_name: This is a placeholder for the actual name of the table where
the data is stored. You should replace this with the actual table name in your
database.
When you run this query, it will return all the rows from the specified table but
only show the name and address columns. This is useful for retrieving specific
information without pulling in all the data from the table.

Sample Output

This output shows the names and addresses of all records in the table, allowing
you to see just the information you requested without any other irrelevant data.
Aim: Select details of students from Stu_info and order
them by their names.

Theory of Practical
ORDER BY clause is a useful statement in SQL that sorts the output of a query in
a specific order. This makes it more accessible to analyze and view the data in an
ordered manner.

Main Features of ORDER BY clause:


Direction of Sorting:
Ascending (ASC): This is the default sort order. When sorted in ascending order,
the smallest numbers will come first while increasing in amount (1, 2, 3), and the
text data will be sorted alphabetically from A to Z.

Descending (DESC): The inverted sequence, in which numbers are arranged from
highest to lowest (9, 8, 7) and text data are arranged in reverse alphabetical order
(Z-A).

The ORDER BY Clause in SQL:


The ORDER BY clause is a powerful tool in SQL that allows you to organize the
results of a query in a specific sequence. This makes it easier to analyze and view
data in an orderly fashion.

● Retrieving all rows of stu_info without order by clause


The default method of sorting by the clause is in ascending order.

● Retrieving all rows in the default order.

To retrieve data in descending order, DESC is used along with ORDER BY


clause.

● Descending order

The scenario of null values,

In case of null values,

- They are displayed at the first if the order is DEFAULT or ASCENDING.


- And the last if the order is DESCENDING.
SUMMARY:
The ORDER BY clause in SQL allows you to sort query results in ascending or
descending order, providing flexibility for organizing and analyzing data. It also
accommodates NULL values in sorting, placing them at the start or end,
depending on the order specified. This makes ORDER BY an essential tool for
clear and customized data presentation.
Aim: Select Roll_no, Name and Email_id from
Stu_info and make a new table named as
Student with them.

Theory of Practical
We will start by creating a table called stu_info with columns for Roll_no, Name
and Email_id. Then ,we will select these columns to create a new table named
Student with the same structure and data.

SQL Query
To achieve this,we can write the SQL Query as following:

STEP 1: Create a table stu_info and add the required data into it as :

--create table stu_info(roll_no int primary key,name varchar(50),email


varchar(50));

describe stu_info;

STEP 2: Create a table named as student and insert the values i.e roll_no,name
and email by selecting from stu_info table

--create table student(roll_no int , name varchar(50), email_id varchar(50));

describe student;
--insert into student (roll_no, name,email_id ) select roll_no, name, email_id from
stu_info

NOW , we get the final table as shown :

The above query does the following:


1. Create table stu_info with columns as roll_no, name and email_id .
2. Create the student table using data selected from stu_info
3. Inserts the data into newly created student table.
Aim: Update all the rows of course_enrolled
table having values as CSE with values as
DCSE

Theory of Practical
The UPDATE statement is used to modify the values in one or more columns of
an existing row in a table. To update rows in a table based on a specific condition,
we use the UPDATE SQL command. In this case, we want to update all rows in
the course_enrolled table where the Course_name column has the value 'CSE',
changing it to 'DCSE'.

Procedure
Step 1: Create the Course_Enrolled Table.

 CREATE TABLE: This command creates a new table in the projectdb


database.
course_enrolled: The name of the table being created. This table will store
information about students and their enrolled courses.

 Column definitions:

o Student_id INT PRIMARY KEY: Defines a column Student_id


of data type INT (integer). The PRIMARY KEY constraint
ensures that each Student_id is unique within the table, meaning
no two students can have the same Student_id.

o Student_name VARCHAR(50): Defines a column Student_name


of data type VARCHAR(50), which can store variable-length text
up to 50 characters. This column stores the name of each student.

o Course_name VARCHAR(50): Defines a column Course_name


of data type VARCHAR(50), which can store up to 50 characters.
This column stores the name of the course that each student is
enrolled in.
Step 2: Insert values into course_enrolled table

 SELECT * FROM course_enrolled; : This command retrieves all

columns (* means all) and rows from the course_enrolled table.


The output will show the current data in course_enrolled before the
updation as follows:

Step 3: UPDATE the values in course_enrolled table.

 UPDATE course_enrolled: This command modifies existing rows in the


course_enrolled table.

 SET Course_name = 'DCSE': Specifies the change to be made: it updates


the Course_name column to 'DCSE'.
 WHERE Course_name = 'CSE': The WHERE clause filters the rows to
be updated. Only rows where the Course_name is currently 'CSE' are
affected. This prevents all rows in the table from being updated.

After updation select * from course_enrolled; command retrieves all the data of
table after the changes.

The rows where course_name was 'CSE' have been updated to 'DCSE'.
Other rows, such as those with MECH and ECE, remain unchanged.
This output demonstrates how the UPDATE statement changes only the rows that
meet the WHERE condition.
Aim: Add a new column named as Aggr_perc
into Course_enrolled.

Theory of Practical
Structured Query Language(SQL) is a standard language for database
creation and manupilation. MySQL is a relational database program that uses SQL
queries.

In SQL the CREATE TABLE statement is used to define and create a new table
within the relational database . Tables are the fundamental components of a
database , used to store structured data in rows and columns .

Using UPDATE statement in the tables can modify the table such as we can add ,
delete , update the rows and columns of the table .

SQL Query:
_ _ create

CREATE TABLE course_enrolled(

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL

);

_ _ insert

INSERT INTO course_enrolled values(0001, „Clark‟, „Sales‟);

INSERT INTO course_enrolled values(0002, „Dave‟, „Accounting‟);


INSERT INTO course_enrolled values(0003, „Ava‟, „Sales‟);

_ _ fetching

ALTER TABLE course_enrolled ADD Aggr_perc varchar(60);

SELECT*FROM course_enrolled;

OUTPUT:
Aim: Delete the column named as Name from
table Course_enrolled.

Theory of Practical
In SQL, the ALTER TABLE statement allows modifications to the structure of an
existing table, which includes adding, modifying, or deleting columns. This
experiment specifically demonstrates the use of the ALTER TABLE command to
remove an unnecessary column, effectively cleaning up the database structure.

- *ALTER TABLE Statement*:


This command is used to change the structure of an existing table. When we use
the DROP COLUMN clause, we permanently delete the specified column from the
table, along with all data stored in that column.

- *Deleting Columns in SQL*:


Removing a column (e.g., name) is helpful for keeping the database lean and
relevant, ensuring that only the necessary data is stored. In this case, deleting the
name column may be necessary if the student‟s name information is no longer
required in the course_enrolled table. This reduces storage and avoids clutter,
especially when the information becomes obsolete or irrelevant to the purpose of
the table.

CREATING TABLE AND INSERTING VALUES


OUTPUT

DELETING COLUMN

OUTPUT AFTER DELETION OF COLUMN


Aim: Rename the table and write a sub-query
to find the details of students having second
highest Roll_no from Student table.

Theory of Practical
In this experiment, you will perform several operations that are fundamental to
SQL database management. The main aim is to retrieve the details of the student
with the second-highest Roll_No.

1.Table Creation: Creating a table is essential to store data in a structured format.


In SQL, a table is defined with columns that represent data attributes.

2.Table Renaming: Renaming a table can be useful for standardising table names,
improving readability, or adapting to new requirements. The ALTER TABLE
command in SQL allows you to rename an existing table.

3. Subquery: A subquery (nested query) is an SQL query embedded within another


SQL query. In this experiment, the subquery is used to find the student with the
second-highest Roll_No.

4. Finding the Second Highest Value: To retrieve the second-highest Roll_No, we


use nested subqueries. This technique is common in rank-based queries where you
need data in order, like “top N” or “second highest” values.

Steps of the Experiment:


1.First, create a new database called STUDENT to store the required tables.

2.Create a table named Stu_info.

3.Insert sample data into Stu_info to create records of students with unique
Roll_Nos.
4.Use the ALTER TABLE command to rename Stu_info to Student.

5.To find the second highest Roll_No, use a subquery to identify the maximum
Roll_No that is less than the absolute maximum Roll_No in the table.

SQL QUERY:

Conclusion:
This experiment demonstrates how to create and manipulate a table, rename it, and
retrieve specific data using subqueries in SQL. Finding the second-highest value is
a common use case in databases, and this experiment showcases the importance of
subqueries and aggregate functions in data retrieval tasks.
Aim: Drop the Stu_info table if already exists
and then create the new table Stu_info with
Roll_no values as unique and not null.

Theory of Practical

Step 1: Dropping the Table if it Already Exists


DROP TABLE IF EXISTS Stu_info;

 Command: DROP TABLE


o DROP TABLE is a SQL command used to delete a table from the
database entirely. When a table is dropped, all of its data and structure
(columns, constraints, indexes, etc.) are permanently removed.
 Condition: IF EXISTS
o Adding IF EXISTS checks whether the table Stu_info is already in the
database. If the table does not exist, using IF EXISTS prevents an
error message and allows the script to continue running smoothly.
 Purpose: The purpose of this line is to ensure there are no previous versions
of the Stu_info table left in the database. This is useful when we want to
create a fresh table with a potentially different structure or modified
constraints without having old data or settings interfere.

In summary: This line makes sure the Stu_info table is removed if it exists, so we
can create it from scratch.

Step 2: Creating the New Table Stu_info


CREATE TABLE Stu_info (
roll_no INT UNIQUE NOT NULL,
name VARCHAR(50),
age INT,
class VARCHAR(10)
);

Now, let‟s break down each part of the CREATE TABLE statement:

 Command: CREATE TABLE


o CREATE TABLE is a SQL command used to create a new table in
the database with specified columns and constraints.
 Table Name: Stu_info
o We are naming our new table Stu_info. This table will store
information about students, such as their roll numbers, names, ages,
and classes.
 Column Definitions:

Each column in a SQL table is defined with a name, a data type, and optional
constraints. Let‟s go through each column in Stu_info:

o roll_no INT UNIQUE NOT NULL


 Column Name: roll_no
 Data Type: INT
 INT (integer) means this column will store whole
numbers. Here, roll_no will represent each student‟s roll
number.
 Constraints:
 UNIQUE: Ensures that every roll_no value is unique in
the table. This means no two students can have the same
roll number.
 NOT NULL: Ensures that each roll_no value must have
a value; it cannot be left empty. This helps maintain data
integrity, as every student must have a roll number.

Why use UNIQUE and NOT NULL for roll_no?


 roll_no is used as a unique identifier for students. In many
cases, it acts like a primary key (though we‟re not explicitly
setting it as a primary key here). By setting it to UNIQUE and
NOT NULL, we make sure each student has a unique roll
number and that it cannot be left blank.
o name VARCHAR(50)
 Column Name: name
 Data Type: VARCHAR(50)
 VARCHAR is a variable-length character data type that
can store text. VARCHAR(50) means that the name can
be up to 50 characters long. If a name has fewer than 50
characters, only the required space is used.
 Purpose: This column will store each student‟s name.
o age INT
 Column Name: age
 Data Type: INT
 INT (integer) is used to store whole numbers. This
column will store each student‟s age.
 Purpose: We‟ll use this column to keep track of how old each
student is. There are no specific constraints on this column, so it
can contain NULL values if the age is unknown.
o class VARCHAR(10)
 Column Name: class
 Data Type: VARCHAR(10)
 VARCHAR(10) is a text data type allowing for up to 10
characters.
 Purpose: This column stores information about the student‟s
class or section, such as "10A" or "9B". It‟s useful for
organizing students within different classes.

Summary of Constraints and Data Integrity


 UNIQUE Constraint on roll_no:
o The UNIQUE constraint on roll_no ensures that no two students can
share the same roll number. This is essential for identifying students
individually and avoids duplication in the database.
 NOT NULL Constraint on roll_no:
o The NOT NULL constraint requires that every student must have a
roll number entered in the table. This prevents entries where a roll
number is accidentally left blank.

These constraints help to enforce data integrity, meaning they ensure the data
stored in the Stu_info table is accurate and consistent. This setup prevents
duplicate or incomplete entries for roll numbers, which are crucial for identifying
students uniquely.

In summary, this SQL script:


1. Ensures any previous version of Stu_info is removed.
2. Creates a new Stu_info table with four columns:
a. roll_no: A unique, non-null identifier for each student.
b. name: The student's name, with a maximum of 50 characters.
c. age: The student's age.
d. class: The student‟s class or section, up to 10 characters long.

The constraints on roll_no guarantee that each student has a unique, non-empty roll
number, ensuring data consistency in the database.
Aim: Write a SQL procedure to show the use of
cursors.

Theory of Practical
Cursors in SQL:
A cursor in SQL is a database object used to retrieve, manipulate, and process
rows from a result set one at a time. It provides a way to work with individual rows
returned by a query, which is especially useful when operations cannot be
efficiently handled with a single SQL statement (i.e., when row-by-row processing
is required).

When to Use Cursors in SQL\


Cursors are typically used in situations where:
1. Row-by-Row Processing is Required: Unlike regular SQL statements that
operate on sets of data (set-based operations), cursors allow you to work on
individual rows one at a time. This is useful when you need to perform
complex operations or business logic that can't be achieved through set-
based operations.
2. Iterative Processing: Sometimes, you need to iterate over each row, apply a
specific business rule or operation, and store results accordingly. This might
involve conditional logic, complex calculations, or transformations that
require each row to be processed sequentially.
3. Transaction Control: Cursors can be helpful when you need to explicitly
manage transactions row by row, though this is usually discouraged in favor
of set-based operations, which are more efficient.

SQL QUERY:
Step 1: Create Sample Tables
First, we need to create some sample tables. For this demonstration, let's use a
table for Employees.

Step 2: Declare the Cursor


Now that we have the tables and data, we can declare a cursor. This cursor will
loop through all employees, retrieve their salary, and update it based on certain
conditions (for example, increasing the salary by 10%).
Step 3: Open the Cursor and Fetch Data
Now, we will open the cursor, fetch data row-by-row, and use it to update each
employee‟s salary.

Step 4: Close and Deallocate the Cursor


After processing all the records, it's important to close and deallocate the cursor to
free up system resources.

Step 5: Verify the Changes


Finally, you can verify the changes made to the employee salaries by querying the
Employees table.
OUTPUT:
Emp ID | Emp Name | Salary

------|----------------|--------

1 | John Doe | 55000.00

2 | Jane Smith | 60000.00

3 | Alice Brown | 75000.00

4 | Bob Johnson | 49500.00

5 | Charlie White | 60500.00

Explanation:
1. Cursor Declaration: The cursor employee_cursor is declared to select
employees with a salary less than 60,000.
2. Looping Through Records: The cursor fetches each record (employee) one
by one. The salary is updated for each employee inside the loop.
3. Deallocating Resources: Once the cursor finishes processing all the rows, it
is closed and deallocated to release system resources.
Aim: Write a SQL procedure to show the use of
triggers.

Theory of Practical
This assignment demonstrates the usage of SQL triggers in a MySQL database
environment. The example provided here explains a procedure where triggers
automatically log changes to a user‟s table by recording modifications in a
user_changes table. This is particularly useful for auditing or tracking changes
within the database system.

Step 1: Create users and user_changes Tables

CREATE TABLE users (

id INT PRIMARY KEY AUTO_INCREMENT,

username VARCHAR(100),

email VARCHAR(100),

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

CREATE TABLE user_changes (

change_id INT PRIMARY KEY AUTO_INCREMENT,

user_id INT,

old_email VARCHAR(100),

new_email VARCHAR(100),

change_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP


);

Step 2: Create a trigger for after update

DELIMITER $$

CREATE TRIGGER after_user_update

AFTER UPDATE ON users

FOR EACH ROW

BEGIN

IF OLD.email != NEW.email THEN

INSERT INTO user_changes (user_id, old_email, new_email, change_time)

VALUES (OLD.id, OLD.email, NEW.email, NOW());

END IF;

END$$
DELIMITER ;

Explanation

 Trigger Name: after_user_update is triggered after an update on the users


table.
 Trigger Condition: Checks if the email has changed by comparing OLD.email
and NEW.email.
 Action: If the email has changed, the trigger inserts relevant information (old
email, new email, and the change time) into the user_changes table.

STEP 3: EXAMPLE OF USING THE TRIGGER


To see how the trigger works, we can update a user’s email:

-- Insert a user

INSERT INTO users (username, email) VALUES ('john_doe',


'[email protected]');

-- Update the user's email


UPDATE users SET email = '[email protected]' WHERE id = 1;

-- Check the changes logged

SELECT * FROM user_changes;

OUTPUT
The user_changes table will log the email change as follows:

Change_id User_id Old_email New_email Change_time

1 1 [email protected] [email protected] 2024-11-10


12:00:00

This demonstrates how triggers can automatically log changes whenever an


event occurs on a table.
AIM: Write a SQL procedure to handle use of
triggers.

Theory of Practical
In relational database management systems (RDBMS), triggers are special stored
procedures that are automatically executed, or "triggered," by events such as
INSERT, UPDATE, or DELETE on a specific table. Triggers are powerful tools in
SQL that help automate certain actions or enforce rules, ensuring data consistency
and integrity.

Types of Triggers
1. BEFORE Trigger: Executes before the event (INSERT, UPDATE,
DELETE) is applied. Useful for validation.
2. AFTER Trigger: Executes after the event has been applied. Useful for
logging, auditing, or performing secondary actions.

Example Scenario: AFTER INSERT Trigger


Let‟s create a simple use case where a trigger automatically logs entries into an
audit table whenever a new record is inserted into an employee table.

Steps:
1. Create two tables: employees and employee_audit.
2. Create a trigger that fires after a new employee is inserted, logging
information into employee_audit.

SQL Query
-- Step 1: Create the employees table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50),
position VARCHAR(50),
salary DECIMAL(10, 2)
);

-- Step 2: Create the employee_audit table


CREATE TABLE employee_audit (
audit_id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
action VARCHAR(50),
action_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Step 3: Create an AFTER INSERT trigger on employees table
DELIMITER //
CREATE TRIGGER after_employee_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (employee_id, action)
VALUES (NEW.employee_id, 'INSERT');
END;
//
DELIMITER ;
Explanation of the Query
1. Create employees table: This table stores employee details like
employee_id, name, position, and salary.
2. Create employee_audit table: This table logs actions with fields for
audit_id, employee_id, action, and action_date.
3. Trigger Creation:
o The after_employee_insert trigger is an AFTER INSERT trigger on
the employees table.
o When a new employee record is added to the employees table, this
trigger will execute.
o The trigger inserts a record into the employee_audit table, storing the
employee_id of the new employee and an INSERT action label.

Example Usage and Output


1. Inserting a Record into employees:

INSERT INTO employees (employee_id, name, position, salary)


VALUES (1, 'John Doe', 'Software Engineer', 75000.00);
2. Output in employee_audit:

After the insertion, the employee_audit table will have a new row
automatically added by the trigger:

SELECT * FROM employee_audit;

Output:

Here, a new audit entry has been created with the employee_id and action as
INSERT, along with the current timestamp.
Summary
 Theory: Triggers automate actions based on events in RDBMS tables,
enhancing data integrity and logging capabilities.
 Query: Created a trigger to log INSERT actions in an audit table.
 Output: Verified the automated audit entry after an INSERT into the
employees table.

You might also like