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

1) Define normalization (1) (2)

Normalization is the process of organizing data in a database to eliminate redundancy and improve integrity, with types including First Normal Form (1NF), Second Normal Form (2NF), Third Normal Form (3NF), and Boyce-Codd Normal Form (BCNF). Applications of DBMS span various industries such as banking, healthcare, e-commerce, and education, while SQL supports various data types and string functions. Additionally, the document discusses ACID properties of transactions, DML and DDL commands, PL/SQL block structure, database triggers, and key definitions like candidate and foreign keys.

Uploaded by

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

1) Define normalization (1) (2)

Normalization is the process of organizing data in a database to eliminate redundancy and improve integrity, with types including First Normal Form (1NF), Second Normal Form (2NF), Third Normal Form (3NF), and Boyce-Codd Normal Form (BCNF). Applications of DBMS span various industries such as banking, healthcare, e-commerce, and education, while SQL supports various data types and string functions. Additionally, the document discusses ACID properties of transactions, DML and DDL commands, PL/SQL block structure, database triggers, and key definitions like candidate and foreign keys.

Uploaded by

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

1) Define normalization.

Enlist its types


Ans:-

Normalization is the process of organizing data into a


related table; it also eliminates redundancy and increases
the integrity which improves performance of the query. To
normalize a database, we divide the database into tables
and establish relationships between the tables.

Database normalization can essentially be defined as the


practice of optimizing table structures. Optimization is
accomplished as a result of a thorough investigation of the
various pieces of data that will be stored within the
database, in particular concentrating upon how this data is
interrelated.

types
First Normal Form (1st NF)
 The table cells must be of a single value.
 Eliminate repeating groups in individual tables.
 Create a separate table for each set of related data.
 Identify each set of related data with a primary key.

Definition: An entity is in the first normal form if it contains


no repeating groups. In relational terms, a table is in the
first normal form if it contains no repeating columns.
Repeating columns make your data less flexible, waste disk
space, and makes it more difficult to search for data.

Second Normal Form (2nd NF)


 Remove Partial Dependencies.
 Functional Dependency: The value of one attribute in a
table is determined entirely by the value of another.
 Partial Dependency: A type of functional dependency
where an attribute is functionally dependent on only part
of the primary key (primary key must be a composite
key).
 Create a separate table with the functionally dependent
data and the part of the key on which it depends. The
tables created at this step will usually contain
descriptions of resources.

Definition: A relation is in 2NF if it is in 1NF and every non-


key attribute is fully dependent on each candidate key of the
relation.

Third Normal Form (3rd NF)


 Remove transitive dependencies.
 Transitive Dependency A type of functional dependency
where an attribute is functionally dependent on an
attribute other than the primary key. Thus its value is
only indirectly determined by the primary key.
 Create a separate table containing the attribute and the
fields that are functionally dependent on it. The tables
created at this step will usually contain descriptions of
either resources or agents. Keep a copy of the key
attribute in the original file.

A relation is in third normal form if it is in 2NF and every


non-key attribute of the relation is non-transitively
dependent on each candidate key of the relation.

Boyce-Codd Normal Form (BCNF)


 When a relation has more than one candidate key,
anomalies may result even though the relation is in 3NF.
 3NF does not deal satisfactorily with the case of a relation
with overlapping candidate keys
 i.e. composite candidate keys with at least one attribute
in common.
 BCNF is based on the concept of a determinant.
Definition: A relation is in Boyce-Codd Normal Form (BCNF) if
every determinant is a candidate key. (See the links in the
box at right for definitions of determinant and candidate
key.)

2) List any four applications of DBMS.


Ans-

DBMS applications span various industries and systems. Four examples include:
banking and finance, healthcare, e-commerce, and education.

Banking and Finance:


DBMS manages customer accounts, transactions, loans, and credit card information.
Healthcare:
DBMS stores and manages patient medical records, insurance claims, and
appointment schedules.
E-commerce:
DBMS handles online order tracking, inventory management, customer data, and
sales information.
Education:
DBMS maintains student records, grades, course enrollments, and staff information.

3) List any four data types in SQL.


Ans-

 INT – Used to store integer (whole number) values.


 VARCHAR(n) – Used to store variable-length character
strings, with a maximum length of n characters.
 DATE – Used to store calendar dates (year, month,
and day).
 DECIMAL(p, s) – Used to store fixed-point numbers
with p digits in total and s digits after the decimal
point.
 CHAR(n) – Fixed-length character strings
 TEXT – Large blocks of text
 FLOAT – Approximate numeric values (floating-point numbers)
 DECIMAL(p, s) – Exact numeric values with precision (p) and
scale (s)
 TIME – Time values (e.g., 14:30:00)
 DATETIME – Combination of date and time
4) Enlist string function in DBMS
Ans-
LENGTH(string) – Returns the length of the string
 LOWER(string) – Converts the string to lowercase
 UPPER(string) – Converts the string to uppercase
 SUBSTRING(string, start, length) – Extracts a part of the string
 TRIM(string) – Removes leading and trailing spaces
 LTRIM(string) – Removes leading spaces
 RTRIM(string) – Removes trailing spaces
 CONCAT(string1, string2, …) – Joins two or more strings

5) State the components used in E-R diagram.

Ans- 1. Entity

 Represents a real-world object or concept (like Student,


Employee)
 Shown as: Rectangle

2. Attribute

 Describes properties of an entity (like Name, ID, Age)


 Types:
o Key Attribute – Uniquely identifies an entity (underlined)
o Multivalued Attribute – Can have multiple values (double
oval)
o Derived Attribute – Calculated from other attributes
(dashed oval)
🔗 3. Relationship

 Shows how entities are related (like enrolls, works for)


shown as: Diamond
4. Cardinality (or Multiplicity)
 Defines the number of instances in a relationship (1:1, 1:N,
M:N)
 Usually written near the relationship lines

6) List any four advantages of DBMS.

DBMS provides robust security features like user authentication and authorization, ensuring
only authorized users can access and modify data.
Streamlined Data Sharing:
DBMS allows authorized users to share data efficiently, improving collaboration and
reducing redundancy.
Improved Data Integrity:
DBMS enforces data integrity through constraints, ensuring data accuracy and consistency,
preventing invalid or duplicate information.
Efficient Data Retrieval and Management:
DBMS provides powerful tools for querying and manipulating data, making it easier for
users to access and manage information quickly and efficiently.
1) Explain ACID properties of transaction.

A – Atomicity

Atomicity means that an entire transaction either takes place all at once or it
doesn’t occur at all. It means that there’s no midway. The transactions can never
occur partially. Every transaction can be considered as a single unit, and they either
run to completion or do not get executed at all. We have the following two
operations here:

—Commit: In case a transaction commits, the changes made are visible to us. Thus,
atomicity is also called the ‘All or nothing rule’.

—Abort: In case a transaction aborts, the changes made to the database are not
visible to us.

C – Consistency

Consistency means that we have to maintain the integrity constraints so that any
given database stays consistent both before and after a transaction. If we refer to
the example discussed above, then we have to maintain the total amount, both
before and after the transaction.

Total after T occurs = 400 + 300 = 700.

Total before T occurs = 500 + 200 = 700.

Thus, the given database is consistent. Here, an inconsistency would occur when T1
completes, but then the T2 fails. As a result, the T would remain incomplete.

I – Isolation

Isolation ensures the occurrence of multiple transactions concurrently without a


database state leading to a state of inconsistency. A transaction occurs
independently, i.e. without any interference. Any changes that occur in any
particular transaction would NOT be ever visible to the other transactions unless
and until this particular change in this transaction has been committed or written to
the memory.

The property of isolation ensures that when we execute the transactions


concurrently, it will result in such a state that’s equivalent to the achieved state
that was serially executed in a particular order.

D – Durability

The durability property states that once the execution of a transaction is completed,
the modifications and updates on the database gets written on and stored in the
disk. These persist even after the occurrence of a system failure. Such updates
become permanent and get stored in non-volatile memory. Thus, the effects of this
transaction are never lost.

2) List and explain DML commands with syntax and


example.

DML stands for Data Manipulation Language. Tables and formulas are
helpful when communicating with data stored up to a point in a database
through SQL (Structured Query Language), but a time comes when we
actually want to execute some fairly complicated data interactions. We will
also need the Data Manipulation Language in that situation. DML is a way to
inform a database precisely what we want it to do by conversing in a manner
that it has been built to comprehend from scratch. When it comes to
interacting with existing data, whether adding, moving, or deleting data, it
provides a convenient way to do so.

SELECT Command-

This command is used to get data out of the database. It helps users of the
database to access from an operating system, the significant data they need.
It sends a track result set from one tables or more.

Syntax :
SELECT *
FROM <table_name>;

Example:

SELECT *
FROM students;

OR

SELECT *
FROM students
where due_fees <=20000;

INSERT Command

This command is used to enter the information or values into a row. We can
connect one or more records to a single table within a repository using this
instruction. This is often used to connect an unused tag to the documents.
Syntax:

INSERT INTO <table_name> ('column_name1' <datatype>,


'column_name2' <datatype>)
VALUES ('value1', 'value2');

Example :

INSERT INTO students ('stu_id' int, 'stu_name' varchar(20),


'city' varchar(20))
VALUES ('1', 'Nirmit', 'Gorakhpur');

UPDATE Command

This command is used to alter existing table records. Within a table, it


modifies data from one or more records. This command is used to alter the
data which is already present in a table.
Syntax:
UPDATE <table_name>
SET <column_name = value>
WHERE condition;

Example:

UPDATE students
SET due_fees = 20000
WHERE stu_name = 'Mini';

DELETE Command

It deletes all archives from a table. This command is used to erase some or
all of the previous table’s records. If we do not specify the ‘WHERE’ condition
then all the rows would be erased or deleted.
Syntax:

DELETE FROM <table_name>


WHERE <condition>;

Example:

DELETE FROM students


WHERE stu_id = '001';

3) Explain any two DDL commands along with example.

DDL Commands & Syntax

In this article, we will discuss the overview of DDL commands and will
understand DDL commands like create, alter, truncate, drop. We will cover
each command syntax with the help of an example for better understanding.
Let’s discuss it one by one.
Overview :
Data Definition Language(DDL) is a subset of SQL and a part of
DBMS(Database Management System). DDL consist of Commands to
commands like CREATE, ALTER, TRUNCATE and DROP. These commands are
used to create or modify the tables in SQL.
CREATE :
This command is used to create a new table in SQL. The user has to give
information like table name, column names, and their datatypes.
Syntax –
CREATE TABLE table_name
(
column_1 datatype,
column_2 datatype,
column_3 datatype,
....
);
Example –
We need to create a table for storing Student information of a particular
College. Create syntax would be as below.
CREATE TABLE Student_info
(
College_Id number(2),
College_name varchar(30),
Branch varchar(10)
);
Command-2 :
ALTER :
This command is used to add, delete or change columns in the existing table.
The user needs to know the existing table name and can do add, delete or
modify tasks easily.
Syntax –
Syntax to add a column to an existing table.
ALTER TABLE table_name
ADD column_name datatype;
Example –
In our Student_info table, we want to add a new column for CGPA. The syntax
would be as below as follows.
ALTER TABLE Student_info
ADD CGPA number;
Command-3 :
TRUNCATE :
This command is used to remove all rows from the table, but the structure of
the table still exists.
Syntax –
Syntax to remove an existing table.
TRUNCATE TABLE table_name;
Example –
The College Authority wants to remove the details of all students for new
batches but wants to keep the table structure. The command they can use is
as follows.
TRUNCATE TABLE Student_info;
Command-4 :
DROP :
This command is used to remove an existing table along with its structure
from the Database.
Syntax –
Syntax to drop an existing table.
DROP TABLE table_name;
Example –
If the College Authority wants to change their Database by deleting the
Student_info Table.
DROP TABLE Student_info;

RENAME:
It is possible to change name of table with or without data in it using simple
RENAME command.
We can rename any table object at any point of time.
Syntax –RENAME TABLE <Table Name> To <New_Table_Name>;
Example: If you want to change the name of the table from Employee to Emp
we can use rename command as
RENAME TABLE Employee To EMP;

4) Explain PL/SQL block structure with example.


In PL/SQL, All statements are classified into units that is called Blocks. PL/SQL
blocks can include variables, SQL statements, loops, constants, conditional
statements and exception handling. Blocks can also build a function or a

procedure or a package.
The Declaration section: Code block start with a declaration section, in
which memory variables, constants, cursors and other oracle objects can be
declared and if required initialized.
The Begin section: Consist of set of SQL and PL/SQL statements, which
describe processes that have to be applied to table data. Actual data
manipulation, retrieval, looping and branching constructs are specified in this
section.
The Exception section: This section deals with handling errors that arise
during execution data manipulation statements, which make up PL/SQL code
block. Errors can arise due to syntax, logic and/or validation rule.
The End section: This marks the end of a PL/SQL block.
Broadly, PL/SQL blocks are two types: Anonymous blocks and Named blocks
are as follows:
1. Anonymous blocks: In PL/SQL, That’s blocks which is not have header
are known as anonymous blocks. These blocks do not form the body of a
function or triggers or procedure. Example: Here a code example of find
greatest number with Anonymous blocks.
2. Named blocks: That’s PL/SQL blocks which having header or labels are
known as Named blocks. These blocks can either be subprograms like
functions, procedures, packages or Triggers. Example: Here a code example
of find greatest number with Named blocks means using function.
5) State the use of database trigger and also list types of
trigger.

A database trigger is a stored procedure in a database that is


automatically executed or fired when certain events occur on a particular
table or view.

✅ Uses of Database Triggers:

1. Enforcing business rules: Triggers can ensure that certain


conditions are met before or after data modification.
2. Automatic auditing: Automatically log changes to a table (like who
modified a record and when).
3. Data validation: Validate data before inserting or updating it.
4. Cascading actions: Automatically update or delete related data in
other tables (like enforcing referential integrity).
5. Preventing invalid transactions: You can stop an
insert/update/delete if it violates certain logic.
Types of Database Triggers:

Types of triggers:-

DML Triggers:
These are activated by events that modify data in a table, such as INSERT, UPDATE,
or DELETE operations.
DDL Triggers:
These are triggered by DDL events that alter the structure of the database, such as
CREATE, ALTER, or DROP statements.
Logon Triggers:
These are activated when a user logs into the database.
BEFORE and AFTER Triggers:
These triggers execute before or after the event that triggered them, respectively.
Statement-level and Row-level Triggers:
Statement-level triggers execute once per SQL statement, while row-level triggers
execute once for each row affected by the statement.

6. Explain. i) Candidate key ii) Foreign key


i) Candidate Key

✅ Definition:

A Candidate Key is a column or a set of columns in a table that can uniquely identify
each record in that table.
There can be multiple candidate keys in a table, but only one of them is chosen as
the Primary Key.

✅ Characteristics:

 Must be unique (no duplicate values).


 Must not contain NULL values.
 Each table can have more than one candidate key.
 One candidate key is selected as the primary key.

✅ Example:

Student Nam
Email Phone
ID e
[email protected] 12345678
101 Alice
om 90
[email protected] 98765432
102 Bob
om 10

In this table:

 StudentID, Email, and Phone can all uniquely identify a student.


 So they are all Candidate Keys.
 We can choose StudentID as the Primary Key.

ii) Foreign Key

✅ Definition:

A Foreign Key is a column (or group of columns) that creates a relationship between
two tables.
It refers to the primary key in another table to enforce referential integrity.
✅ Purpose:

 Ensures the value in one table matches a valid value in another table.
 Maintains consistency across related tables.

✅ Example:

Students Table:

Student Nam ClassI


ID e D
1 Alice 10
2 Bob 20

Classes Table:

ClassI ClassNam
D e
Computer
10
Sci.
Mathematic
20
s

 In this case, ClassID in the Students table is a Foreign Key that refers to
ClassID in the Classes table.

SQL Aggregate Functions are used to perform calculations on a


set of rows and return a single value. These functions are
particularly useful when we

7) Explain aggregate function with example.

need to summarize, analyze, or group large datasets in SQL databases.


Whether you’re working with sales data, employee records, or product
inventories, aggregate functions help us derive meaningful insights.
They are often used with the GROUP BY clause in SQL to summarize data
for each group. Commonly used aggregate functions include COUNT(),
SUM(), AVG(), MIN(), and MAX(). In this article, we will explain the most
commonly used SQL aggregate functions, their syntax, practical examples,
and how to make the best use of them in your queries
What Are SQL Aggregate Functions?
SQL Aggregate Functions are used to perform calculations on multiple
rows of data and return a single summarized result. These functions are
typically used with theGROUP BY clause to organize data into groups, where
we can then perform calculations like summing, averaging, or counting.
Aggregate functions allow you to make sense of large datasets by collapsing
them into meaningful summaries.

*Commonly Used SQL Aggregate Functions

1. Count()

The COUNT() function returns the number of rows that match a given
condition or are present in a column.
 COUNT(*): Counts all rows.
 COUNT(column_name): Counts non-NULL values in the specified
column.
 COUNT(DISTINCT column_name): Counts unique non-NULL values in
the column.
Examples:
-- Total number of records in the table
SELECT COUNT(*) AS TotalRecords FROM Employee;

-- Count of non-NULL salaries


SELECT COUNT(Salary) AS NonNullSalaries FROM Employee;

-- Count of unique non-NULL salaries


SELECT COUNT(DISTINCT Salary) AS UniqueSalaries FROM Employee;

2. SUM()

The SUM() function calculates the total sum of a numeric column.


 SUM(column_name): Returns the total sum of all non-NULL values in a
column.
Examples:
-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;
-- Calculate the sum of unique salaries
SELECT SUM(DISTINCT Salary) AS DistinctSalarySum FROM Employee;

3. AVG()

The AVG() function calculates the average of a numeric column. It divides


the sum of the column by the number of non-NULL rows.
AVG(column_name): Returns the average of the non-NULL values in the
column.
Examples:
-- Calculate the average salary
SELECT AVG(Salary) AS AverageSalary FROM Employee;

-- Average of distinct salaries


SELECT AVG(DISTINCT Salary) AS DistinctAvgSalary FROM Employee;

4. MIN() and MAX()

The MIN() and MAX() functions return the smallest and largest values,
respectively, from a column.
 MIN(column_name): Returns the minimum value.
 MAX(column_name): Returns the maximum value.
Examples:
-- Find the highest salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;

-- Find the lowest salary


SELECT MIN(Salary) AS LowestSalary FROM Employee;

8) Explain joins in SQL with examples.

SQL joins are fundamental tools for combining data from multiple tables in
relational databases. Joins allow efficient data retrieval, which is essential
for generating meaningful observations and solving complex business
queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN,
RIGHT JOIN, FULL JOIN, and NATURAL JOIN, is critical for working with
relational databases.
In this article, we will cover the different types of SQL joins, including
INNER JOIN, LEFT OUTER JOIN, RIGHT JOIN, FULL JOIN, and NATURAL
JOIN. Each join type will be explained with examples, syntax, and practical
use cases to help us understand when and how to use these joins effectively.
SQL INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining
all rows from both the tables where the condition satisfies i.e value of the
common field will be the same.
Syntax
SELECT table1.column1,table1.column2,table2.column1,…. FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.

Example of INNER JOIN

Consider the two tables, Student and StudentCourse, which share a


common column ROLL_NO. Using SQL JOINS, we can combine data from these
tables based on their relationship, allowing us to retrieve meaningful
information like student details along with their enrolled courses.
Student Table

StudentCours
e Table

Let’s look at the example of INNER JOIN clause, and understand it’s
working. This query will show the names and age of students enrolled in
different courses.
Query:

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM


Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Output
2. SQL LEFT JOIN
A LEFT JOIN returns all rows from the left table, along with matching rows
from the right table. If there is no match, NULL values are returned for
columns from the right table. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax
SELECT table1.column1,table1.column2,table2.column1,….
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

LEFT JOIN Example

In this example, the LEFT JOIN retrieves all rows from the Student table
and the matching rows from the StudentCourse table based on the
ROLL_NO column.
Query:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output

3. SQL RIGHT JOIN


RIGHT JOIN returns all the rows of the table on the right side of the join
and matching rows for the table on the left side of the join. It is very similar
to LEFT JOIN for the rows for which there is no matching row on the left
side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.
Syntax

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
RIGHT JOIN Example

In this example, the RIGHT JOIN retrieves all rows from the StudentCourse
table and the matching rows from the Student table based on the ROLL_NO
column.
Query:

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output

4. SQL FULL JOIN


FULL JOIN creates the result-set by combining results of both LEFT JOIN
and RIGHT JOIN. The result-set will contain all the rows from both tables.
For the rows for which there is no matching, the result-set will contain NULL
values.
Syntax

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
9) List and explain advantages of DBMS over file
processing system

Advantages of DBMS over File system


File System: A File Management system is a DBMS that allows access to
single files or tables at a time. In a File System, data is directly stored in a
set of files. It contains flat files that have no relation to other files
DBMS: A Database Management System (DBMS) is application software that
allows users to efficiently define, create, maintain and share databases.
Defining a database involves specifying the data types, structures and
constraints of the data to be stored in the database. Creating a database
involves storing the data on some storage medium that is controlled by
DBMS. Maintaining a database involves updating the database whenever
required to evolve and reflect changes in the miniworld and also generating
reports for each change
Data redundancy and inconsistency: Redundancy is the concept of
repetition of data i.e. each data may have more than a single copy. The file
system cannot control the redundancy of data as each user defines and
maintains the needed files for a specific application to run. There may be a
possibility that two users are maintaining the data of the same file for
different applications. Hence changes made by one user do not reflect in files
used by second users, which leads to inconsistency of data. Whereas DBMS
controls redundancy by maintaining a single repository of data that is
defined once and is accessed by many users. As there is no or less
redundancy, data remains consistent.
Data sharing: The file system does not allow sharing of data or sharing is
too complex. Whereas in DBMS, data can be shared easily due to a
centralized system.
Data concurrency: Concurrent access to data means more than one user is
accessing the same data at the same time. Anomalies occur when changes
made by one user get lost because of changes made by another user. The
file system does not provide any procedure to stop anomalies. Whereas
DBMS provides a locking system to stop anomalies to occur.
Data searching: For every search operation performed on the file system, a
different application program has to be written. While DBMS provides inbuilt
searching operations. The user only has to write a small query to retrieve
data from the database.
Data integrity: There may be cases when some constraints need to be
applied to the data before inserting it into the database. The file system does
not provide any procedure to check these constraints automatically.
Whereas DBMS maintains data integrity by enforcing user-defined
constraints on data by itself.
10) Explain exception handling in PL/SQL with example.
Exception Handling in PL/SQL

In PL/SQL (Procedural Language/Structured Query Language),


exception handling is used to handle errors or unexpected situations
that occur during the execution of a block of code.

Types of Exceptions in PL/SQL

1. Predefined Exceptions – Errors that are automatically defined by


Oracle.
Example: NO_DATA_FOUND, ZERO_DIVIDE, TOO_MANY_ROWS
2. User-defined Exceptions – Custom exceptions declared by the user
using EXCEPTION.

Structure of PL/SQL Block with Exception Handling


sql
CopyEdit
BEGIN
-- Executable statements
EXCEPTION
WHEN exception_name1 THEN
-- Error handling code
WHEN exception_name2 THEN
-- Error handling code
WHEN OTHERS THEN
-- Default error handling
END;

Example: Handling Division by Zero


sql
CopyEdit
DECLARE
num1 NUMBER := 10;
num2 NUMBER := 0;
result NUMBER;
BEGIN
result := num1 / num2;
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Cannot divide by zero!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred.');
END;

Example: User-Defined Exception


sql
CopyEdit
DECLARE
salary NUMBER := 800;
low salary EXCEPTION;
BEGIN
IF salary < 1000 THEN
RAISE low_salary;
END IF;
DBMS_OUTPUT.PUT_LINE('Salary is acceptable.');
EXCEPTION
WHEN low_salary THEN
DBMS_OUTPUT.PUT_LINE('Error: Salary is too low.');
END;

Benefits of Exception Handling in PL/SQL:

 Keeps the program from crashing.


 Allows handling of expected and unexpected errors.
 Makes code cleaner and more reliable.
11) Explain overall structure of DBMS with the help of
diagram.
DBMS means Database Management System, which is a tool or software
used to create the database or delete or manipulate the database. A
software programme created to store, retrieve, query, and manage data is
known as a Database Management System (DBMS). Data can be generated,
read, updated, and destroyed by authorized entities thanks to user interfaces
(UIs).

Because they give programmers, Database Managers, and end users a


consolidated view of the data, Database Management Systems are crucial
because they relieve applications and end users of the need t
o comprehend the physical location of the data.

1. Query Processor
The query processing is handled by the query processor, as the name
implies. It executes the user's query, to put it simply. In this way, the query
processor aids the database system in making data access simple and easy.
The query processor's primary duty is to successfully execute the query.
Components of the Query Processor

DDL Interpreter:
Data Definition Language is what DDL stands for. As implied by the name,
the DDL Interpreter interprets DDL statements like those used in schema
definitions (such as create, remove, etc.). This interpretation yields a set of
tables that include the meta-data (data of data) that is kept in the data
dictionary.

DML Compiler:

Compiler for DML Data Manipulation Language is what DML stands for. In
keeping with its name, the DML Compiler converts DML statements like
select, update, and delete into low-level instructions or simply machine-
readable object code, to enable execution. The optimization of queries is
another function of the DML compiler.

2. Storage Manager:
An application called Storage Manager acts as a conduit between the queries
made and the data kept in the database. Another name for it is Database
Control System. By applying the restrictions and running the DCL
instructions, it keeps the database's consistency and integrity.

Components of Storage Manager

Integrity Manager:
Whenever there is any change in the database, the Integrity manager will
manage the integrity constraints.

Authorization Manager:
Authorization manager verifies the user that he is valid and authenticated for
the specific query or request.

File Manager:
All the files and data structure of the database are managed by this
component.

Transaction Manager:
It is responsible for making the database consistent before and after the
transactions. Concurrent processes are generally controlled by this
component.

Buffer Manager:
The transfer of data between primary and main memory and managing the
cache memory is done by the buffer manager.
3. Disk Storage
A DBMS can use various kinds of Data Structures as a part of physical system
implementation in the form of disk storage.

Components of Disk Storage


Following are the components of Disk Manager:

Data Dictionary:
It contains the metadata (data of data), which means each object of the
database has some information about its structure. So, it creates a
repository which contains the details about the structure of the database
object.

The data dictionary contains the following information:

 It includes the name of tables, properties, length of properties and


number of rows in each table.
 Data dictionary contains association between database transactions
and data items that belong to them.
 It contains various relationships between database transactions and
their associated data items.
 If certain data definitions are changed it is useful in predicting which
transactions are changed.

12) Explain cursor with example.


A cursor in SQL is a database object used to retrieve, process, and
manipulate data one row at a time. While SQL is designed to handle
large data sets in bulk (set-based processing), sometimes we just need to
focus on one row at a time. A cursor in SQL is a temporary memory or
workspace allocated by the database server to process DML (Data
Manipulation Language) operations.
It allows processing query results row-by-row instead of applying operations
to the entire set. They give us more control over result sets and are
especially useful in complex logic, conditional updates, or procedural
programming in SQL-based languages like PL/SQL or T-SQL.
Types of Cursors in SQL

1. Implicit Cursors

In PL/SQL, when we perform INSERT, UPDATE or DELETE operations, an


implicit cursor is automatically created. This cursor holds the data to be
inserted or identifies the rows to be updated or deleted. We can refer to this
cursor as the SQL cursor in our code.

Usage: Managed entirely by the SQL engine without explicit declaration.


Useful Attributes:
 %FOUND: True if the SQL operation affects at least one row.
 %NOTFOUND: True if no rows are affected.
 %ROWCOUNT: Returns the number of rows affected.
 %ISOPEN: Checks if the cursor is open.
2. Explicit Cursors
These are user-defined cursors created explicitly by users for custom
operations. They provide complete control over every part of their lifecycle:
declaration, opening, fetching, closing, and deallocating.
Usage: Used for fetching data row-by-row with complete control over the
cursor lifecycle.
 Explicit cursors are useful when:
 We need to loop through results manually
 Each row needs to be handled with custom logic
1) Draw ER diagram of Railway Management System
3. Draw ER diagram for library management system
considering issue and return, fine collection facility.
Consider appropriate entities.
4. Consider the following schema. Student (Name, Mark,
Age, Place, Phone, Birthdate) Write SQL queries for
following: i) To list name of student who do not have
phone number. ii) To list student from Nashik and
Pune. iii) To change mark of Monika to 88 instead of
80. iv) To list student from Anit’s age group.
Concepts:
Sql, Database queries
Explanation:
The following SQL queries address the requirements based on the
given schema of the Student table.
Step by Step Solution:
Step 1
To list the names of students who do not have a phone number,
use the following SQL query: SELECT Name FROM Student WHERE
Phone IS NULL;
Step 2
To list students from Nashik and Pune, use the following SQL
query: SELECT * FROM Student WHERE Place IN ('Nashik',
'Pune');
Step 3
To change the mark of Monika to 88 instead of 80, use the
following SQL query: UPDATE Student SET Mark = 88 WHERE
Name = 'Monika';
Step 4
To list students from Anita's age group, first find Anita's age and
then use it in the query: SELECT * FROM Student WHERE Age =
(SELECT Age FROM Student WHERE Name = 'Anita');
Final Answer:
The SQL queries provided will fulfill the requirements stated in the
question.
4) Write a PL/SQL program to calculate factorial of
a given number.
declare -- it gives the final answer after computation fac number :=1;

-- given number n -- taking input from user n number := &1;

-- start block begin

-- start while loop

while n > 0 loop

-- multiple with n and decrease n's value fac:=n*fac;

n:=n-1;

end loop;

-- end loop

-- print result of fac dbms_output.put_line(fac);

-- end the begin block end;

5) Write SQL command for following : (i) Create user (ii)


Grant privileges to user (iii) Remove privileges f
4. GRANT CREATE, SELECT ON * . * TO
'user_name'@'localhost';

5. In order to grant all privileges of the


database for a newly created user, execute the
following command:GRANT ALL PRIVILEGES ON * . * TO
'new_user'@'localhost';

Sometimes, you might come across a situation where you need to revoke

given privileges from a user. You can do so by entering:

REVOKE PERMISSION_TYPE ON database_name.table_name FROM


‘user_name’@‘localhost’;

For example, to withdraw all privileges for our non-root user we should use:

REVOKE ALL PRIVILEGES ON * . * FROM


'user_name'@'localhost';

Finally, you can entirely delete an existing user account by using the

following command:

DROP USER ‘user_name’@‘localhost’;


6)Write a PL/SQL program which accept the customer ID
from the user if user enters an invalid ID then the
exception invalid_id is raised using exception handling

DECLARE customer_id NUMBER; exception_invalid_id EXCEPTION;

BEGIN /* Get customer ID from user */

customer_id := &customer_id;

/* Validate customer ID */
IF customer_id <= 0 THEN
RAISE exception_invalid_id;
END IF;

/* Process valid customer ID (example: display a message) */


DBMS_OUTPUT.PUT_LINE('Customer ID: ' || customer_id || ' is
valid.');

EXCEPTION

WHEN exception_invalid_id THEN

DBMS_OUTPUT.PUT_LINE('Invalid customer ID. Customer ID must be greater


than zero.'); WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('An unexpected error occurred.'); END; /

You might also like