Shivam Chaudhary DBMS FILE
Shivam Chaudhary DBMS FILE
MEERUT,(U.P.)
ENGINNERING
PRACTICAL FILE
SESSION (2024-2025)
COMPUTER NETWORK
Program
No. Program Name Date Signature
Normalization of a Table
4
Creating the Procedure & Function.
5
Creating the Trigger & Package.
6
Creating the View and explain.
7
T Creating Database and Describe the Join Operation in
8 SQL..
PRACTICAL No: - 01
To install SQL Server on a Windows machine, follow these steps:
Click the Download button and choose the Basic or Custom installation option depending on your
preference.
7. Server Configuration
Set the SQL Server Agent to Automatic or Manual based on your requirements.
Configure the authentication mode:
o Mixed Mode: Allows both Windows Authentication and SQL Server Authentication. You will need
to set a password for the sa (system administrator) account.
Add the SQL Server administrators by clicking Add Current User (or manually adding users).
Click Next.
11. Install
Review all the settings and click Install to begin the installation.
The installer will start installing SQL Server and related components.
Run the installer, and follow the prompts to complete the installation.
o Server Name: (either the default instance or the name of the instance you configured).
PRACTICAL No: - 02
Objective: Creating E-R Diagram Using the Case Tool Draw. in ( Customer –Order-
Shipment )
Explanation:
CUSTOMER_ID: A numeric field for the unique ID of the customer. It is marked as NOT NULL and should be
the primary key for the table (though this is not explicitly stated in the code).
CUST_FIRST_NAME and CUST_LAST_NAME: These are required fields (NOT NULL), each having a
maximum length of 20 characters.
CUST_STREET_ADDRESS1 and CUST_STREET_ADDRESS2: These store the customer's address lines with
a maximum length of 60 characters each.
PHONE_NUMBER1 and PHONE_NUMBER2: Fields for phone numbers with a maximum length of 25
characters.
CREDIT_LIMIT: A numeric field for the customer's credit limit, which allows up to 9 digits with 2 decimal
places.
To create an ORDER table where CUSTOMER_ID is a foreign key (referring to the CUSTOMER109 table) and
ORDER_ID is the primary key,
SQL for the ORDER Table:
Explanation:
ORDER_ID: This is the primary key for the order. It is a numeric value and must be unique for each order.
CUSTOMER_ID: This is the foreign key that references the CUSTOMER_ID in the CUSTOMER109 table,
establishing the relationship between customers and their orders.
ORDER_DATE: The date when the order was placed. It is a required field.
SHIP_ADDRESS: The address where the order is shipped. You can adjust the size (currently 100 characters)
based on your needs.
ORDER_TOTAL: The total amount of the order, defined with two decimal places (e.g., NUMBER(10,2)
allows values up to 99999999.99).
Constraints:
PK_ORDER_ID: This constraint enforces that ORDER_ID is the primary key and unique.
FK_CUSTOMER_ID: This constraint ensures that CUSTOMER_ID is a valid reference to the CUSTOMER_ID
field in the CUSTOMER109 table.
To create a SHIPMENT table that is related to the ORDER109 table, you would typically include fields that describe
the shipment, such as the shipment ID, the ORDER_ID (which will be a foreign key), shipment status, tracking
number, and shipment date, among others.
SQL for the SHIPMENT Table:
Explanation:
SHIPMENT_ID: This is the primary key for the shipment, uniquely identifying each shipment.
ORDER_ID: This is a foreign key that links to the ORDER109 table's ORDER_ID field. It ensures that each
shipment is associated with an order.
TRACKING_NUMBER: A field to store the tracking number for the shipment, which is optional but
commonly used.
SHIP_STATUS: A field that tracks the shipment's current status (e.g., "Shipped", "In Transit", "Delivered").
SHIP_ADDRESS: The address where the shipment is being sent, which may differ from the billing address.
Constraints:
PK_SHIPMENT_ID: This constraint enforces that SHIPMENT_ID is unique and serves as the primary key.
FK_ORDER_ID: This constraint establishes the foreign key relationship, ensuring that each shipment is
linked to an existing order from the ORDER109 table.
E-R Diagram to show the Relationship and Entity
PRACTICAL No: - 03
SQL QUERIES:
1. List the Empname,doj from employeeS table.
SELECT emp_name,doj FROM employeeS;
3. List the name of emp who belong to Bombay and depart nameis Sales.
SELECT emp_name FROM employeeS WHERE address='Mumbai' AND dept_name ='Marketing';
5. List the name of the emp who are getting their salary between 800 and 2500.
6. SELECT emp_name FROM employeeV WHERE salary BETWEEN 800 AND 2500;
7. List the employees who are earning more than 1200 but less than 4000.
SELECT emp_name FROM employeeS WHERE salary>1200 and salary<4000;
PRACTICAL No: - 04
A practical of normalization, we are building a database to store information about students, courses,
and enrollments in a school system. We'll demonstrate how to normalize the database from an
unnormalized state (1NF) to higher forms of normalization (2NF, 3NF).
Initially, we have a simple table that contains all the data about students, their courses, and grades.
The data might look like this:
Student_ID Student_Name Course_1 Grade_1 Course_2 Grade_2
1001 Shivam Math A Science B
1002 Sagar pal Math C History B
This table violates the First Normal Form (1NF), which requires that each field contain only atomic
values (no repeating groups or arrays). Here, the courses and grades for each student are stored in
separate columns, which violate 1NF.
To bring this table into 1NF, we need to remove the repeating groups (i.e., multiple courses and
grades). Each row should contain only atomic values, so we'll separate each course and grade into a
new row:
To bring the table into 2NF, we need to eliminate partial dependencies. A partial dependency
occurs when a non-key column depends only on part of the primary key, rather than the whole key.
In this case, Student_Name depends only on Student_ID, not on Course or Grade. The primary key
is composite (both Student_ID and Course), and Student_Name depends only on Student_ID, so we
need to split the table into two:
Student_ID Student_Name
1001 Shivam
1002 Sagar pal
Now, the database is in 2NF because all non-key attributes depend on the whole primary key
(Student_ID and Course), and there are no partial dependencies.
To bring the database into 3NF, we need to remove transitive dependencies. A transitive
dependency occurs when a non-key column depends on another non-key column.
In the Enrollments table, there is no transitive dependency between Course and Grade, but if we
added a Instructor column, we might see a transitive dependency: the Instructor depends on Course,
and the Course is dependent on the primary key (Student_ID, Course).
Student_ID Student_Name
1001 Shivam
1002 Sagar pal
Now, the Enrollments table no longer contains any redundant information about instructors, and all
attributes are non-transitively dependent on the primary key, so the database is in 3NF.
Summary of Normalization Steps
0NF: Normalized, repeating groups of data.
1NF: Eliminate repeating groups; make fields atomic.
2NF: Eliminate partial dependencies by splitting the table into related entities.
3NF: Eliminate transitive dependencies.
This process reduces redundancy and ensures that the data is organized efficiently. When designing
a database for a real-world application, these normalization steps are critical for maintaining data
integrity and avoiding anomalies when updating or deleting records.
PRACTICAL No: - 05
A PL/SQL procedure is a named block of code that performs a specific task, but it does not return
a value. It can take input parameters, perform operations (such as querying or modifying the
database), and return output through parameters or via side effects (like inserting, updating, or
deleting data).
CREATE PROCEDURE: This creates a new procedure. You can use OR REPLACE if you want to
replace an existing procedure with a new definition.
Parameter List (Optional): You can specify parameters that the procedure can accept,
which can be IN, OUT, or IN OUT.
IS / AS: This indicates the start of the procedure’s declaration part, where you can define
variables, constants, or exceptions.
BEGIN / END: These marks the body of the procedure where the actual processing logic
occurs.
Here is an example of a procedure that adds two numbers and prints the result:
Executing a Procedure:
To execute a procedure in PL/SQL, you simply call it using an anonymous block, or you can use
SQL*Plus or any PL/SQL interface to invoke the procedure.
BEGIN
greetings;
END;
Dropping a Procedure:
PRACTICAL No: - 06
In SQL, a trigger is a special kind of stored procedure that automatically executes or "fires" when
certain events occur in the database, such as after an insert, update, or delete operation on a table.
Triggers are used for enforcing business rules, auditing, validation, and automatic data
modifications. They are particularly useful for maintaining data integrity and consistency.
Let’s walk through a practical example of a trigger that tracks changes to an employee's salary in a
company. We’ll use a simple scenario with the following requirements:
Table Structure:
o employees: Contains employee information.
o salary_audit: A table that logs changes to employees' salaries.
Next, we create a trigger that will automatically log changes made to the salary field in the
employees table. The trigger will be fired before an update on the salary column, so it will capture the
old value before any changes are applied.
FOR EACH ROW: This means the trigger will fire for each row that is updated, not just once for the entire
operation.
:OLD.salary: Refers to the old value of the salary before the update.
:NEW.salary: Refers to the new value of the salary after the update.
PRACTICAL No: - 07
In SQL, a view is a virtual table that is derived from the result of a query. It can represent a
complex query that combines data from one or more tables, or it can simplify repetitive queries by
abstracting them into a single object that can be referenced like a regular table. Views are used for
several purposes, including simplifying complex queries, improving security by restricting access to
certain data, and providing a layer of abstraction.
Scenario:
You are working with an online store database, and you need to generate reports on customer
orders, but you often need to join the customers, orders, and order_items tables. Instead of writing
the same complex query multiple times, you decide to create a view to simplify this.
Create a view that joins the customers, orders, and order_items tables to give us detailed
information about each order, including customer details, order items, and total amounts.
Explanation:
CREATE OR REPLACE VIEW order_details: Creates the view named order_details. If a
view with the same name already exists, it will be replaced.
SELECT statement: The view combines data from the customers, orders, and order_items
tables. It also calculates the total for each item (item_total = quantity * unit_price).
JOIN operations: We join the three tables (customers, orders, order_items) based on their
relationships (i.e., customer_id and order_id).
Step 4: Query the View
Now that the view is created, you can query it as if it were a regular table. This simplifies the
process of fetching detailed order information.
In SQL, a join operation is used to combine rows from two or more tables based on a related
column between them. There are different types of joins, such as INNER JOIN, LEFT JOIN, RIGHT
JOIN, and FULL JOIN.
1. Employees table:
employee_id employee_name department_id
1 Shivam 101
2 Shwetank 102
3 Sunny 101
4 Nitin 103
2. Departments table:
department_id department_name
101 HR
102 IT
103 Marketing
1 Shivam HR
2 Shwetank IT
3 Sunny HR
4 Nitin Marketing
This operation returns all rows from the left table (Employees), and the matched rows from the
right
table (Departments). If there is no match, NULL values are returned for columns from the right
table
Result:
employee_id employee_name department_name
1 Shivam HR
2 Shwetank IT
3 Sunny HR
4 Nitin Marketing
(Note: In this example, all employees have matching departments, so the result is similar to the
INNER JOIN. However, if there were employees without a department, the department_name
would show as NULL.)
This operation returns all rows from the right table (Departments), and the matched rows from the
left table (Employees). If there is no match, NULL values are returned for columns from the left table.
Result:
(Note: If there were departments without any employees, the employee_id and employee_name
would show as NULL.)
PRACTICAL No: - 09
Objective: Creating & implement cursor in SQL.
A cursor in SQL is a database object used to retrieve, manipulate, and navigate through a result set
row by row. Cursors are particularly useful when you need to process each row individually, such as
when performing operations that are difficult or impossible to express in a single SQL query.
Here is a practical example that demonstrates how to create and use a cursor in SQL.
Scenario
1 Shivam 5000
2 Shwetank 6000
3 Sunny 7000
4 Nitin 8000
The goal is to use a cursor to update each employee's salary by increasing it by 10% individually.
1. Declare the cursor – This defines the SQL query that retrieves the rows.
2. Open the cursor – This makes the cursor operational.
3. Fetch the data – This retrieves the rows one by one from the cursor.
4. Process the data – Perform operations like UPDATE or INSERT on each row.
5. Close the cursor – After processing, release the cursor.
Key Notes:
Cursor operations can be resource-intensive, especially for large result sets. It's best to use cursors only
when necessary (e.g., when complex logic requires row-by-row processing).
Alternative approaches: In many cases, set-based operations (such as UPDATE, INSERT, or SELECT with a
JOIN) can be more efficient than using cursors. Cursors should be considered a last resort when set-based
solutions are not feasible.
Performance Considerations:
Cursors can cause performance issues, especially on large result sets, because they process rows one at a
time. When possible, always try to use set-based operations (such as an UPDATE statement that processes
all rows at once) instead of row-by-row cursors.
PRACTICAL No: - 10
Introduction – PL/SQL bridges the gap between database technology and procedural
programming languages. It can be thought of as a development tool that extends the
facilities of Oracles SQL database language. Via PL/SQL you can insert, delete, update
and retrieve table data as well as use procedural techniQuestions such as writing loops or
branching to another block of code.
DECLARE
Declarations of memory variables
used later BEGIN
SQL executable statements for manipulating table
data. EXCEPTIONS
SQL and/or PL.SQL code to handle
errors. END;
Displaying user Messages on the screen – Any programming tool requires a method
through which messages can be displayed to the user.
Example: Write the following code in the PL/SQL block to display message
to user DBMS_OUTPUT.PUT_LINE(‘Display user message’)
The GOTO statement: The goto statement allows you to change the flow of control within a
PL/SQL Block.
PRACTICAL No: - 11
In SQL Server, automatic backups and recovery processes are crucial for maintaining database
integrity and ensuring that data can be restored in case of failure. Below are the steps for setting up
automatic backups and recovery.
SQL Server Agent is a tool that can be used to automate jobs such as backups. Here's how to set up an
automated backup plan:
o Right-click on "SQL Server Agent" and select Start (if it's not running).
o In the New Job window, provide a name for the backup job (e.g., "Automated Full Backup").
Command: Enter the T-SQL command for the backup, such as:
BACKUP DATABASE [YourDatabaseName]
TO DISK = 'C:\Backups\YourDatabaseName_full.bak'
WITH FORMAT, MEDIANAME = 'YourBackupMedia', NAME = 'Full Backup of
YourDatabase';
Click OK to save the step.
o Set the frequency (e.g., daily, weekly) and the time of the backup.
o Under the Notifications tab (optional), you can configure an email notification if the job succeeds or
fails.
Now, your SQL Server will automatically run the backup job as per the schedule you've defined.
If you need a more granular backup strategy, you can also automate differential backups and transaction log
backups in a similar way:
To perform a recovery of a SQL Server database, you need the backup files and the recovery model
configuration (Full, Simple, or Bulk-logged). The following steps outline how to recover a database from a
backup:
o Select the Device option and then choose the backup file.
o If the backup file is located on disk, click Add and locate the .bak file.
If you have a differential backup after the full backup, you will need to restore the full backup first, and then
apply the differential backup.
The WITH NORECOVERY option ensures that the database remains in a restoring state, allowing you to apply
transaction log backups afterward.
If you have transaction log backups, you can restore them to bring the database to the most recent point in time.
6. Finalize the Restore Process: Once all necessary backups have been restored, you can bring the
database online with:
Make sure your database’s recovery model is set correctly based on your backup and recovery strategy:
Full Recovery Model: Supports full, differential, and transaction log backups.
Simple Recovery Model: Only supports full and differential backups; transaction log backups are not available.
Bulk-Logged Recovery Model: Similar to the full recovery model, but allows minimal logging for bulk operations.
SQL Server also provides Maintenance Plans that can help automate backup tasks without the need for SQL
Server Agent jobs. You can create a maintenance plan using the Maintenance Plan Wizard in SSMS:
Conclusion
By following these steps, you can set up automatic backups in SQL Server and also recover your database
when needed. It's important to implement a proper backup strategy (including full, differential, and transaction
log backups) to ensure data integrity and quick recovery in case of failure.