DBDM Unit Ii
DBDM Unit Ii
UNIT II
Syllabus:
Relational Model Concepts and Integrity Constraints - Mapping ER and EER Models to
Relational Schema - SQL: Data Definition Language (DDL) and Data Manipulation Language
(DML) - Views and Indexes in SQL - SQL Programming (Stored Procedures, Triggers, Cursors)
Definitions:
Relational Database:
A type of database that organizes data into tables (known as relations), where each table
contains rows and columns. Relationships can be established between tables using keys.
Eg. A library database where one table stores book details and another stores member
information.
Table:
A table is a collection of data organized in rows and columns. Each table represents one
entity type (like students, courses, employees, etc.).
Student_ID Name Department Marks
101 John CSE 92
102 Asha IT 88
Attribute:
An attribute is a column in a table. It represents a specific property of the entity. Each
attribute has a name and a data type.
Eg) In the above table, Name, Department, and Marks are attributes.
Tuple:
A tuple is a row in a table. It represents a single, complete record or entry in the relation.
Eg) Row | 101 | John | CSE | 92 | is a tuple representing one student.
Schema:
A schema defines the structure of a table or an entire database. It includes table names,
attribute names, and their data types.
Example:
For the student table:
Student(Student_ID: INT, Name: VARCHAR, Department: VARCHAR, Marks: INT)
2.1 RELATIONAL MODEL CONCEPTS AND INTEGRITY CONSTRAINTS
1
24AD3391-Database Design and Management
INTEGRITY CONSTRAINTS
Integrity constraints are a set of rules used in DBMS to ensure that the data in a
database is accurate, consistent and reliable. These rules helps in maintaining the quality of
data by ensuring that the processes like adding, updating or deleting information do not harm
the integrity of the database. Integrity constraints also define how different parts of the
database are connected and ensure that these relationships remain valid. They act like a set of
guidelines that ensure all the information stored in the database follows specific standards.
2
24AD3391-Database Design and Management
Integrity Constraint
Domain Constraint:
Domain constraints can be defined as the definition of a valid set of values for an
attribute.
The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain.
Example
The entity integrity constraint states that primary key value can't be null.
This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
A table can contain a null value other than the primary key field.
Example:
EMP_ID EMP_NAME SALARY
Not allowed, as 123 Tom 30000
primary Key cannot be 142 John 60000
NULL value Leonardo 20000
3
24AD3391-Database Design and Management
Relationships
Key constraints:
Keys are the entity set that is used to identify an entity within its entity set uniquely.
An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.
Example:
4
24AD3391-Database Design and Management
weak entities, and specialization/generalization - into relational tables with appropriate primary
keys, foreign keys, and constraints. Understanding this mapping ensures that the logical design
preserves the integrity, constraints, and semantics of the original ER model while making it
ready for practical SQL-based implementation.
2.2.1 Mapping of Entity Set to Relationship
An entity set is mapped to a relation in a straightforward way.
Each attribute of entity set becomes an attribute of the table.
The primary key attribute of entity set becomes an entity of the table.
For example - Consider following ER diagram.
EName
Emp_Id
Salary
Employee
5
24AD3391-Database Design and Management
Declare foreign key constraints for all these fields from the entity sets. For example -
Consider following ER model
6
24AD3391-Database Design and Management
By this approach the relationship associated with more than one entities is separately
represented using a table. For example - Consider following ER diagram. Each Dept has
at most one manager, according to the key constraint on Manages.
Here the constraint is each department has at the most one manager to manage it.
Hence no two tuples can have same DeptID. Hence there can be a separate table named Manages
with DeptID as Primary Key. The table can be defined using following SQL statement.
Department table
DeptID DName Budget
1 HR 500000
2 IT 1000000
3 Finance 800000
Employee Table
EmpID EName Salary
E101 Alice 70000
E102 Bob 90000
E103 Carol 75000
Manages
DeptID (PK) EmpID Since
10 E101 2020-04-10
20 E105 2019-07-01
Approach 2:
In this approach, it is preferred to translate a relationship set with key constraints.
It is a superior approach because; it avoids creating a distinct table for the relationship
set.
The idea is to include the information about the relationship set in the table corresponding
to the entity set with the key, taking advantage of the key constraint.
This approach eliminates the need for a separate Manages relation, and queries asking for
a department's manager can be answered without combining information from two
relations.
The only drawback to this approach is that space could be wasted if several departments
have no managers.
7
24AD3391-Database Design and Management
The following SQL statement, defining a Dep_Mgr relation that captures the information
in both Departments and Manages, illustrates the second approach to translating
relationship sets with key constraints :
Dep_Mgr
Buildings table
Bldg_No Address
101 Main Campus Road
102 Science Block St
Department table
Bldg_No DeptID DeptName
101 1 HR
101 2 Finance
102 1 Physics
8
24AD3391-Database Design and Management
One table is created for the superclass with its own attributes.
One table is created for each subclass with only the attributes specific to that subclass.
A foreign key links each subclass table to the superclass table.
1. Super class Table: (Inventory Item)
ID Price
101 500
102 300
103 200
2. Subclass table for Book
9
24AD3391-Database Design and Management
ID Publisher
101 Penguin Books
103 HarperCollins
3. Subclass table for DVD
ID Manufacturer
102 Sony Pictures
DVD Table
ID Price Manufacturer
D01 800 Sony Pictures
D02 600 Warner Bros
10
24AD3391-Database Design and Management
e) TRUNCATE
DDL has pre-defined syntax for describing the data.
CREATE COMMAND
CREATE command is used for creating objects in the database. It creates a new table.
Syntax: CREATE TABLE <table_name> ( column_name1 datatype, column_name2 datatype, . .
column_name_n datatype );
Example:
CREATE TABLE employee
(
empid INT,
ename CHAR,
age INT,
city CHAR(25),
phone_no VARCHAR(20) );
DROP COMMAND
DROP command allows removing entire database objects from the database.
It removes entire data structure from the database.
It deletes a table, index or view.
Syntax:
DROP TABLE <table_name>;
Or
DROP DATABASE <database_name>;
Example:
DROP TABLE employee;
Or
DROP DATABASE employees;
ALTER COMMAND
An ALTER command allows to alter or modify the structure of the database.
It modifies an existing database object.
Using this command, you can add additional column, drop existing column and even
change the data type of columns.
Syntax:
ALTER TABLE <table_name> ADD <column_name datatype>;
Or
ALTER TABLE <table_name> CHANGE <old_column_name> <new_column_name>;
Or
ALTER TABLE <table_name> DROP COLUMN <column_name>;
Example
ALTER TABLE employee ADD (address varchar2(50));
Or
11
24AD3391-Database Design and Management
12
24AD3391-Database Design and Management
13
24AD3391-Database Design and Management
INDEXES in SQL
An index is like a book’s index - it helps SQL find rows faster without scanning the
entire table. Indexes improve read performance but can slightly slow down inserts/updates
because they must also update the index.
Example with Student Details table
Creating an index on CGPA
CREATE INDEX idx_cgpa
ON Student_Details(CGPA);
2.6 SQL PROGRAMMING (STORED PROCEDURES, TRIGGERS, CURSORS)
2.6.1 Stored Procedures
A stored procedure is a collection of one or more SQL statements stored and compiled
inside the database for repeated use.
Instead of writing the same query or logic again and again, we can create it once as a
procedure and call it whenever needed.
Stored procedures can accept input parameters, return output parameters, and include
control-flow statements such as loops and conditions. Because they are precompiled, they
typically run faster than sending raw SQL from an application each time.
They also improve security by allowing restricted database access - users can run the
procedure without having direct permission on the underlying tables.
a) Creating stored procedure with and without parameters
b) Altering stored procedures
c) View the stored procedure
d) Dropping the stored procedure
14
24AD3391-Database Design and Management
Execution:
EXEC ShowAllEmployees;
Output:
EMP_ID Emp_Firstname Emp_Lastname Emp_Gender Emp_Salary
15
24AD3391-Database Design and Management
Example
CREATE PROCEDURE employeedata
@EMP_ID INT,
@EMP_GENDER VARCHAR(50)
AS
BEGIN
SELECT Emp_Firstname, Emp_Lastname, Emp_Gender
FROM Employee
WHERE EMP_ID = @EMP_ID AND Emp_Gender = @EMP_GENDER;
END;
Execution:
EXEC employeedata 1, 'Male';
Emp_Firstname Emp_Lastname Emp_Gender
Raj Darji Male
Kamav Sonavane Male
Altering stored procedures
Syntax:
ALTER PROCEDURE ProcedureName
AS
BEGIN
-- Modified SQL statements
END;
Example:
ALTER PROCEDURE SMCE
AS
BEGIN
SELECT Emp_Firstname, Emp_Lastname, Emp_Gender
16
24AD3391-Database Design and Management
FROM Employee
ORDER BY Emp_Firstname;
END
To Execute:
EXEC SMCE;
Emp_Firstname Emp_Lastname Emp_Gender
Ajay Chariya Male
Asif Hussain Male
Gourav Gupta Male
Kamav Sonavane Male
Krupali Raj Female
Raj Darji Male
Rincy Patel Female
View the stored procedure
Syntax:
sp_helptext 'ProcedureName';
Example:
sp_helptext 'employeedata';
Dropping the stored procedure
Syntax:
DROP PROCEDURE ProcedureName;
Example:
DROP PROCEDURE smce;
2.6.2 Triggers
A trigger is a special stored program in the database that is executed automatically when
a specific event occurs on a table or view.
The event can be an INSERT, UPDATE, or DELETE operation. Triggers can run either
before or after the event, allowing you to enforce business rules, validate data, or
maintain audit logs without manual intervention.
Types of triggers
o DML Trigger (Insert, Update, Delete)
o DDL Trigger (Create, Alter, Drop)
o LOGON Trigger (User Session)
Virtual Tables
Inserted
Deleted
Inserted Deleted
Stores new
Insert -
inserted records
17
24AD3391-Database Design and Management
Stores old
Stores new
Update values for
updated records
updated records
Stores deleted
Delete -
records
SELECT * FROM employees
Employee_ID FIRYST_NAME LAST_NAME SALARY MANAGER_ID DEPARTMENT_ID
100 Shan King 24000 100 90
101 Nareen Karthik 17000 101 90
102 Lee Ann 18000 102 90
103 Alex Herald 6000 103 60
104 Bruce lee 4800 103 60
105 Diana Raj 4200 103 60
106 David Austin 8000 102 80
107 Louis Lamp 9000 102 80
The employees table is the main table, and the employees_audit table is used to record
changes whenever an update or delete operation happens on it. The audit table has three fields:
Employee_ID to store the affected employee, Operation to indicate whether it was an UPDATE
or DELETE, and Updated_Date to record the exact time of the change. By creating triggers on
the employees table, any modification or deletion will automatically insert a record into the
employees_audit table, ensuring that all changes are tracked for auditing purposes.
CREATE TABLE employees_audit
(
Employee_ID int,
Operation varchar(10),
UpdatedDate Datetime,
);
Trigger
CREATE TRIGGER trg_emp_audit
ON employees
AFTER INSERT
AS
BEGIN
INSERT INTO employees_audit
SELECT EMPLOYEE_ID,’INS’, GETDATE()
FROM inserted // Virtual table
END
// after creating this trigger lets insert a new value in the employees table.
INSERT INTO employees
VALUES(207,’sam’ , ‘Nichol’ , 2500,122,50);
18
24AD3391-Database Design and Management
Execution:
SELECT * FROM employees_audit;
Alter
ALTER TRIGGER trg_emp_audit
ON employees
AFTER INSERT , DELETE
AS
BEGIN
INSERT INTO employees_audit
SELECT EMPLOYEE_ID,’INS’, GETDATE()
FROM inserted // Virtual table
UNION ALL
SELECT EMPLOYEE_ID,’DEL’,GETDATE()
FROM deleted //Virtual table
END
19
24AD3391-Database Design and Management
INSTEAD OF DELETE
AS
BEGIN
UPDATE employee_copy
SET Active = 0,
EndDate = GETDATE()
WHERE Employee_ID IN (SELECT Employee_ID FROM deleted);
END;
// Delete one record for employee_copy table
DELETE FROM employee_copy WHERE EMPLOYEE_ID = 107
SELECT * FROM employees_copy;
Employee_ID FIRST_NAME LAST_NAME SALARY MANAGER_ID DEPARTMENT_ID EndDate Active
100 Shan King 24000 100 90 NULL 1
101 Nareen Karthik 17000 101 90 NULL 1
102 Lee Ann 18000 102 90 NULL 1
103 Alex Herald 6000 103 60 NULL 1
104 Bruce Lee 4800 103 60 NULL 1
105 Diana Raj 4200 103 60 NULL 1
106 David Austin 8000 102 80 NULL 1
2025-08-17
107 Louis Lamp 9000 102 80 0
11:55:00
Advantages:
Triggers are just like stored procedures and easy to code.
Automate tasks and reduce manual effort.
Ensures data integrity.
Virtual tables like inserted and deleted are very useful.
Can invoke stored procedure and functions inside a trigger
Disadvantages:
Triggers add complexity and cause additional overhead.
Impacts performance
Difficult to locate and invisible to client.
Disabling triggers may cause inconsistency.
2.6.3 Cursors
A cursor is a database object that lets you retrieve and process query results row-by-row
rather than all at once.
This is useful when you need to perform operations on each row individually using
procedural logic.
A cursor works like a pointer to the result set of a query—you can open it, fetch rows into
variables, process them, and then close it.
20
24AD3391-Database Design and Management
While they offer precise control, cursors are generally slower than set-based SQL
operations, so they are used only when row-by-row processing is necessary.
Syntax
DECLARE cursor_name CURSOR FOR
SELECT_statement;
OPEN cursor_name;
CLOSE cursor_name;
Example
Let the table name be ‘SalesData’
Here we are going to write the cursor for calculating the running total
Running Total column just grows row by row by adding the current row’s value to everything
that came before it.
ID Value Running Total
1 10 NULL
2 20 NULL
3 15 NULL
4 25 NULL
5 30 NULL
WHILE @@FETCH_STATUS = 0
BEGIN
-- Add the value to cumulative total
21
24AD3391-Database Design and Management
Advantages:
Row level processing
Data Navigation (Fetch Next, Prior, First, Last)
Complex Query handling.
Disadvantages:
Performance issue
Resource Consumption
Complexity of code
Locking of data
22
24AD3391-Database Design and Management
QUESTION BANK
2 Marks
23
24AD3391-Database Design and Management
Salary INT
);
11. What does the TRUNCATE command do in SQL?
Removes all rows from a table but keeps its structure for future use.
12. Write the SQL syntax to rename a table in a database.
ALTER TABLE old_name RENAME TO new_name;
13. What is a view in SQL?
A virtual table based on the result of a SQL query, which doesn’t store data itself.
14. Give one advantage of using indexes in SQL.
Improves the speed of data retrieval operations.
15. Define a stored procedure.
A precompiled set of SQL statements stored in the database and executed on
demand.
16. What is the difference between a trigger and a stored procedure?
Trigger: Executes automatically on specific events.
Stored Procedure: Executes only when explicitly called.
17. What is a cursor in SQL programming?
A database object that allows row-by-row processing of query results.
18. Give an example of mapping a weak entity set to a relational table.
For a weak entity Dependent, include owner key:
CREATE TABLE Dependent (
EmpID INT,
DepName VARCHAR(30),
PRIMARY KEY(EmpID, DepName),
FOREIGN KEY(EmpID) REFERENCES Employee
);
19. Name the three methods for mapping specialization/generalization to relational
schema.
Multiple tables for all entities.
Tables for only subclasses (duplicate superclass attributes).
Single table for the superclass (nulls for unused attributes).
24
24AD3391-Database Design and Management
*********
25