DBMS File
DBMS File
Practical File
1|Page
INDEX
TASK EXPERIMENT PAGE REMARKS
NO.
2|Page
TASK 1: Introduction to SQL and Installation of SQL Server / Oracle
1. Introduction to SQL (Structured Query Language)
SQL (Structured Query Language) is the standard language used to communicate with
relational databases. It is used for creating, managing, and manipulating databases and their
data. SQL commands are used for tasks such as querying data, updating records, creating
new databases, and setting up permissions.
Key Concepts in SQL:
1. Database: A collection of data that is organized in a structured way.
2. Table: Data in a database is organized into tables, consisting of rows (records) and
columns (fields).
3. Primary Key: A unique identifier for each record in a table.
4. Foreign Key: A column that creates a relationship between two tables.
5. Normalization: Organizing data to reduce redundancy and dependency.
Basic SQL Commands:
1. CREATE DATABASE: Used to create a new database.
3|Page
8. DROP TABLE: Deletes a table and its data permanently.
10. JOIN: Combines rows from two or more tables based on a related column.
4|Page
6. Choose Installation Location:
o Choose the directory where SQL Server will be installed (the default is
typically fine).
o Click Install.
7. Install:
o Click Next and allow the installer to complete the process. This may take
several minutes.
8. Launch SQL Server Management Studio (SSMS):
o Once the installation is complete, download and install SQL Server
Management Studio (SSMS) to manage your SQL Server instances.
o You can download SSMS from here.
5|Page
Example SQL Queries for Practice:
1. Creating a Database:
2. Creating a Table:
3. Inserting Data:
4. Querying Data:
5. Filtering Data:
6. Updating Records:
7. Deleting Records:
6|Page
TASK 2: Data Types, Creating Tables, Retrieval of Row using Select Statement,
conditional retrieval of Row, Alter and Drop statements.
DBMS Practical: Data Types, Creating Tables, Data Retrieval, and Alter/Drop
Statements
In this practical, we will explore several fundamental SQL operations in a Database
Management System (DBMS). These operations include understanding data types,
creating tables, retrieving data, applying conditional filters, and using the ALTER and
DROP statements to modify or remove table structures.
1. Understanding Data Types in SQL
Data types in SQL define the type of data a column can hold. They play an essential
role in ensuring data integrity by defining constraints on what kind of values can be
stored in each column.
Common SQL Data Types:
Numeric Data Types:
o INT: Stores whole numbers.
o DECIMAL(p, s): Stores fixed-point numbers, where p is the precision (total
digits) and s is the scale (number of digits after the decimal point).
o FLOAT or REAL: Stores floating-point numbers.
Character Data Types:
o VARCHAR(n): Variable-length string where n specifies the maximum length.
o CHAR(n): Fixed-length string with a defined length of n.
o TEXT: Stores large text data.
Date and Time Data Types:
o DATE: Stores the date in YYYY-MM-DD format.
o TIME: Stores time in HH:MM:SS format.
o DATETIME: Stores both date and time.
Other Data Types:
o BOOLEAN: Stores TRUE or FALSE.
o BLOB or BINARY: Stores binary data like images or files.
7|Page
Example - Creating a Students Table:
This table Students will store information about students, including their ID, name,
birthdate, and grade level.
8|Page
Example - Retrieving Students Born After January 1, 2005:
Rename a Column:
Drop a Column:
9|Page
6. Dropping Tables using the DROP Statement
The DROP statement is used to permanently remove a table and all of its data from
the database.
Syntax for DROP TABLE:
Be cautious when using DROP because once a table is dropped, all the data is lost
permanently.
7. Practical Exercises
Let's practice some of the SQL commands discussed.
Exercise 1: Create a Books Table
Create a table Books with the following columns:
BookID (Primary Key, INT)
Title (VARCHAR)
Author (VARCHAR)
PublishDate (DATE)
Price (DECIMAL(5, 2))
10 | P a g e
Exercise 3: Retrieve All Books Published After 2022
11 | P a g e
Task 3: Working with Null Values, Matching a Pattern from a Table, Ordering the Result of
a Query, Aggregate Functions, Grouping the Result of a Query, Update and
Delete Statements.
1. Working with Null Values
In SQL, NULL represents unknown or missing data. To work with NULL values, you need to
use specific operators.
IS NULL: To check if a value is NULL.
IS NOT NULL: To check if a value is not NULL.
COALESCE(): To replace NULL with a specified value.
Example:
12 | P a g e
3. Ordering the Result of a Query
To order the results of a query, you use the ORDER BY clause. You can sort results in
ascending (ASC) or descending (DESC) order.
Example:
4. Aggregate Functions
Aggregate functions are used to perform a calculation on a set of values. Common aggregate
functions include COUNT(), SUM(), AVG(), MIN(), and MAX().
Example:
13 | P a g e
5. Grouping the Result of a Query
The GROUP BY clause is used to group rows that have the same values in specified columns.
It is often used with aggregate functions.
Example:
14 | P a g e
Putting It All Together
You can combine multiple operations in a single query. For instance, finding the average
salary per department, excluding inactive employees, and ordering the result.
Example:
Summary:
NULL values: Use IS NULL, IS NOT NULL, and functions like COALESCE().
Pattern matching: Use LIKE with wildcards (%, _).
Ordering: Use ORDER BY for sorting results in ascending or descending order.
Aggregate functions: Use COUNT(), SUM(), AVG(), MIN(), MAX() for summarizing
data.
Grouping: Use GROUP BY to group data and HAVING to filter groups.
Update/Delete: Use UPDATE and DELETE to modify or remove data.
15 | P a g e
Task 4: Set Operators, Nested Queries, Joins, Sequences.
1. Set Operators
Set operators combine the results of two or more queries. The main set operators
are:
UNION: Combines the result of two queries, removing duplicates.
UNION ALL: Combines the result of two queries, including duplicates.
INTERSECT: Returns only the common records from two queries.
EXCEPT (or MINUS in some databases): Returns records from the first query that are
not in the second query.
Example:
16 | P a g e
2. Nested Queries (Subqueries)
A nested query (or subquery) is a query inside another query. Subqueries can be
used in the SELECT, INSERT, UPDATE, or DELETE statements, or in the WHERE clause.
Types of Nested Queries:
1. Subquery in the SELECT clause: Returns a value for each row.
2. Subquery in the WHERE clause: Used to filter results.
3. Correlated subquery: A subquery that depends on the outer query.
Examples:
Subquery in the WHERE clause:
Correlated Subquery (where the subquery references a column from the outer
query):
3. Joins
Joins are used to combine data from two or more tables based on a related column.
The most common types of joins are:
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table, and
matching records from the right table. If no match, NULL values are returned for
columns from the right table.
RIGHT JOIN (or RIGHT OUTER JOIN): Similar to LEFT JOIN but returns all records from
the right table.
FULL OUTER JOIN: Returns records when there is a match in one of the tables.
17 | P a g e
CROSS JOIN: Returns the Cartesian product of two tables (all combinations of rows).
Examples:
INNER JOIN:
LEFT JOIN:
RIGHT JOIN:
CROSS JOIN:
4. Sequences
A sequence is an object in a DBMS that generates a sequence of unique numbers,
often used for generating primary key values.
Example of Sequence Usage:
Creating a Sequence:
18 | P a g e
Using a Sequence to Insert Data:
Summary:
Set Operators: Combine the results of two queries with UNION, INTERSECT, EXCEPT,
etc.
19 | P a g e
Nested Queries: Queries inside other queries, useful for filtering, aggregating, or
checking against other datasets.
Joins: Combine data from multiple tables (e.g., INNER JOIN, LEFT JOIN).
Sequences: Generate unique values (commonly used for primary keys) with CREATE
SEQUENCE and NEXTVAL.
20 | P a g e
Task 5: Views, Indexes, Database Security and Privileges: Grant and Revoke
Commands, Commit and Rollback Commands.
1. Views:
A view is a virtual table based on the result of a SELECT query. It does not store data
but allows users to interact with the data in a simplified or customized way.
Creating a View:
Example:
Dropping a View:
2. Indexes:
An index is used to improve the speed of data retrieval operations on a database
table. It is created on columns that are frequently queried.
Creating an Index:
Example:
Dropping an Index:
21 | P a g e
In a DBMS, privileges determine the operations that a user can perform on database
objects like tables, views, and stored procedures.
Grant Command:
The GRANT command is used to give privileges to users or roles.
Example:
This grants the user john_doe the ability to SELECT and INSERT data into the
employees table.
Revoke Command:
The REVOKE command removes privileges from users or roles.
Example:
This revokes the INSERT privilege on the employees table from the user john_doe.
4. Commit and Rollback Commands (Transaction Control):
These commands are used to manage transactions in a database, ensuring data
integrity.
COMMIT Command:
The COMMIT command is used to save the changes made during the current
transaction to the database permanently.
Example:
ROLLBACK Command:
The ROLLBACK command is used to undo the changes made in the current
transaction, reverting the database to its state before the transaction began.
22 | P a g e
Example:
4. Creating a View: Create a view to display employees with salaries greater than
50,000.
7. Rolling Back a Transaction: Insert a new record and then roll back.
23 | P a g e
8. Committing a Transaction: Insert a new record and commit the changes.
Summary of Commands:
Command Description
24 | P a g e
Task 6: PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL Code,
Referencing Non-SQL parameters.
1. PL/SQL Architecture
PL/SQL is a procedural language extension to SQL, designed for seamless integration with
Oracle databases. The architecture of PL/SQL includes the following major components:
a. PL/SQL Engine
The PL/SQL engine is responsible for executing PL/SQL blocks. When a PL/SQL block is
executed, the engine performs various tasks like parsing, optimization, and execution.
b. PL/SQL Block Structure
A PL/SQL block consists of the following sections:
Declaration Section (optional): This section declares variables, constants, cursors,
and exceptions. It starts with the DECLARE keyword.
Execution Section: This section contains the executable code that performs the
actual operations (SQL queries, loops, conditional logic, etc.).
Exception Handling Section (optional): Used to handle exceptions or errors. It starts
with the EXCEPTION keyword.
Example of a basic PL/SQL block:
25 | P a g e
2. Assignments and Expressions in PL/SQL
a. Assignments
In PL/SQL, assignments are made using the := operator. It assigns the value on the right-hand
side to the variable on the left-hand side.
Example of assignment:
b. Expressions
An expression in PL/SQL is any combination of variables, constants, operators, and function
calls that evaluates to a single value.
Example of an expression:
26 | P a g e
b. Control Structures
PL/SQL supports control structures like IF...THEN...ELSE, LOOP, and FOR loops.
Example of an IF statement:
c. Cursors
PL/SQL uses cursors to fetch and process rows returned by SQL queries.
Example of an explicit cursor:
27 | P a g e
IN (input): Pass values into the procedure.
OUT (output): Return values from the procedure.
IN OUT: Pass and return values.
Example of a procedure with parameters:
28 | P a g e
This will print "Hello, PL/SQL!" to the output console when executed.
Practical File Structure
A practical file would typically include:
Problem Statement: Describe the PL/SQL tasks to be performed.
Code Implementation: Provide PL/SQL code with appropriate comments.
Execution: Demonstrate how to execute the code and the output.
Conclusion: Summarize what was learned or achieved.
Example for a simple assignment:
Problem: Create a PL/SQL block that calculates and prints the bonus of an employee
based on their salary (e.g., 10% of the salary).
Solution:
29 | P a g e
Task 7: Stored Procedures and Exception Handling.
In a Database Management System (DBMS) practical file, a section on Stored Procedures
and Exception Handling is a crucial part of learning how to create, manage, and handle
errors in the database layer. Below is a detailed overview of the topics with practical
examples that you can include in your practical file.
Stored Procedures
1. What is a Stored Procedure?
A Stored Procedure (SP) is a precompiled collection of one or more SQL statements that can
be executed by the database server. Stored procedures are stored within the database itself
and can be executed multiple times. They help in improving the efficiency of queries and
reducing the number of calls made to the database.
2. Advantages of Stored Procedures:
Reusability: Can be called multiple times in the application without rewriting the
same code.
Performance: Precompiled SQL statements improve the speed of execution.
Security: Restricts direct access to the database.
Error Handling: Allows centralized error handling logic.
3. Creating a Stored Procedure:
To create a stored procedure, we use the CREATE PROCEDURE statement. Below is an
example:
30 | P a g e
5. Calling a Stored Procedure:
This will execute the GetEmployeeDetails stored procedure and return the result for the employee
with ID 101.
Exception handling in SQL allows us to capture runtime errors (like division by zero, invalid data
types, etc.) and handle them gracefully rather than letting the database process fail or return
incorrect results. In stored procedures, exceptions can be managed with DECLARE, HANDLER,
RESIGNAL, etc.
You can define exception handling in stored procedures using the DECLARE statement to declare
handlers and then respond with an appropriate action like CONTINUE or EXIT.
Here is an example of how you can use exception handling within a stored procedure in MySQL:
31 | P a g e
4. Explanation of the Example:
DECLARE EXIT HANDLER FOR SQLEXCEPTION: This part of the code specifies that if any SQL
exception occurs, the handler will be triggered.
ROLLBACK: In case of an error, this will undo any changes made during the transaction.
START TRANSACTION and COMMIT: Used to start and commit the transaction.
Objective:
Write a stored procedure to insert an employee into the Employees table and handle
possible exceptions (e.g., duplicate records, constraint violations).
1. Table Setup:
32 | P a g e
3. Calling the Stored Procedure:
Conclusion:
Stored procedures and exception handling play a crucial role in improving the
performance and reliability of database operations. By storing commonly used
queries and encapsulating them into procedures, you can achieve greater
modularity, security, and better error management. Exception handling ensures that
any errors are caught and dealt with before they can disrupt the entire system.
You can now create this content in your practical file, demonstrating both the
creation and usage of stored procedures, as well as handling exceptions effectively.
33 | P a g e
Task 8: Triggers and Cursor Management in PL/ SQL.
In PL/SQL, Triggers and Cursor Management are key components for automating
database tasks and controlling how data is accessed in your programs.
Here’s a brief overview and practical examples for both, which you can use for your
DBMS practical file:
1. Triggers in PL/SQL
A Trigger is a special type of stored procedure in PL/SQL that is automatically
executed (or "triggered") when certain events occur on a table or view.
Types of Triggers:
BEFORE Trigger: Executes before an insert, update, or delete operation.
AFTER Trigger: Executes after an insert, update, or delete operation.
INSTEAD OF Trigger: Executes in place of an insert, update, or delete operation (used
mainly with views).
Common Uses:
Enforcing business rules
Auditing changes
Data validation
Example: Creating a Trigger
Let's create an AFTER INSERT trigger on an employees table to log any new insert
into a separate auditlog table.
Step 1: Create the tables
34 | P a g e
Explanation:
AFTER INSERT ON employees: The trigger fires after an insert is made into the
employees table.
:NEW.emp_id: Refers to the new value of the emp_id column that was inserted.
audit_log_seq.NEXTVAL: Assumes you have a sequence for generating unique log_id
values.
Step 3: Testing the Trigger
35 | P a g e
Explanation:
CURSOR emp_cursor: Declares an explicit cursor to select emp_id, emp_name, and
emp_salary from the employees table.
FETCH emp_cursor INTO v_emp_id, v_emp_name, v_emp_salary: Fetches one row
at a time into the declared variables.
EXIT WHEN emp_cursor%NOTFOUND: Exits the loop when there are no more rows
to fetch.
Step 2: Testing the Cursor Code
You can execute the above block in your SQL*Plus or any PL/SQL environment to see
the output using DBMS_OUTPUT.
36 | P a g e