Database
Database
01
Key Points:
Data is stored systematically in tables.
Designed for fast retrieval and updating.
Works with a Database Management System (DBMS) for better control.
Examples of DBMS:
Relational DBMS: MySQL, Oracle, PostgreSQL, MS SQL Server.
Non-relational DBMS: MongoDB, Cassandra.
Analogy:
Think of DBMS as a librarian:
The bookshelves are the database (storage).
The librarian (DBMS) knows where each book is, ensures you return it, and protects
the library’s order.
3.Overview of DBMS:
A DBMS is not just about storing data — it ensures that data is stored securely,
remains consistent, and is accessible to multiple users without conflicts.
Main Functions of a DBMS
Data Definition – Creating tables, structures, and relationships.
Data Storage – Saving data efficiently on disk.
Data Retrieval – Fetching the required information quickly.
Data Manipulation – Adding, modifying, and deleting data.
Data Security – Protecting data from unauthorized access.
Transaction Management – Handling operations so that the database always
remains in a consistent state.
4. Characteristics of DBMS
a. Data Integrity
Meaning: Data integrity ensures that the stored data is accurate, consistent, and
reliable over its entire lifecycle.
Example: If a student’s roll number is 101, DBMS ensures that this roll number will
not mistakenly be assigned to another student.
How DBMS ensures it:
Using constraints like PRIMARY KEY, UNIQUE, CHECK.
b. Data Security
Meaning: DBMS protects data from unauthorized access and malicious threats.
Example: In a hospital database, only doctors can see patients’ medical history, but
receptionists may only see appointment schedules.
c. Data Independence
Meaning: Changes in the database structure should not affect the way applications
access data.
Example: If we change the name of a table column in the database, the application
can still work without rewriting the entire program (with minimal adjustments).
Types:
Physical Data Independence – Changing how data is stored physically does not
affect logical access.
Logical Data Independence – Changing the logical schema does not affect the
applications.
Commands:
ROLLBACK – Undo the last transaction.
COMMIT – Save the transaction permanently.
e. Concurrency Control
Meaning: Concurrency control ensures that multiple users can access and modify
the database at the same time without causing conflicts.
Example: Two employees trying to update the same customer’s address at the same
time should not cause incorrect results.
Example:
If a company database crashes due to hardware failure, the latest backup can be
restored to minimize data loss.
DBMS Solution:
DBMS uses a centralized database where each piece of information is stored only
once. This avoids data redundancy.
Example:
Student’s address stored only once in a “Student” table. Other tables like “Exam
Results” or “Library Loans” just reference the Student ID.
Advantage: Saves storage space and ensures faster updates.
Example:
If a student changes their phone number, it is updated once in the DBMS, and all
applications use the updated number.
Advantage: Improves data reliability.
Example:
In a banking system, multiple tellers can access a customer’s account data at the
same time without corrupting the data.
Advantage: Improves collaboration and productivity.
d. Centralized Control of Data
File System Problem:
Each application maintains its own files, making management scattered and difficult.
DBMS Solution:
Data is centrally stored and managed by the Database Administrator (DBA), who
controls updates, backups, and access permissions.
Example:
In a university DBMS, the DBA manages student, course, and exam data centrally,
rather than each department keeping separate files.
Advantage: Easier maintenance and better consistency.
e. Standards Enforcement
File System Problem:
No guarantee that the data follows a certain format or structure.
DBMS Solution:
DBMS enforces data standards like naming conventions, formats (e.g., date format),
and validation rules.
Example:
Ensuring that a phone number is always stored in +91-XXXXXXX format.
Advantage: Improves data quality and interoperability.
f. Security Restrictions
File System Problem:
Limited or no control over who can view or edit specific parts of data.
DBMS Solution:
DBMS provides role-based security where users are given permissions (read, write,
update) based on their role.
Example: In a hospital DBMS, doctors can see patient history, but only the admin
can delete records.
Advantage: Protects sensitive information.
g. Integrity
Example:
Preventing a student from registering for a course that doesn’t exist.
Advantage: Prevents entry of incorrect data.
h. Data Independence
File System Problem:
Changes in file structure require changes in all applications using it.
DBMS Solution:
DBMS separates logical data structure from the physical storage. Applications can
work without being affected by changes in how data is stored.
Example:
Moving a database from HDD to SSD doesn’t affect applications using the data.
Advantage: Flexibility in data management.
DBMS Solution:
With centralized and well-structured data, new applications can be developed quickly
using existing data.
Example:
Adding a mobile app for an e-commerce site using the same product and customer
database.
Advantage: Reduces development time and cost.
Definition: Describes how data is physically stored in storage devices (hard disks,
SSDs).
User: Database administrators and system programmers.
Details Covered: File organization, indexing, compression.
Example: Storing student records as blocks on a disk with a B+ tree index.
Analogy: Like the engine of a car — you don’t need to know how it works to drive it.
7. Database Architecture
Database architecture defines the structure and interaction of the database
components. The most common type is Three-Tier Architecture.
1. Single-Tier Architecture
Definition: The database and application both run on the same system.
Example: MS Access where both DB and UI are in one application.
Advantage: Simple and fast for small applications.
2. Two-Tier Architecture
Structure:
Tier 1: Client application (UI + business logic)
Tier 2: Database server
Example: Client program (Java, Python) connecting directly to MySQL.
Advantage: Better performance than single-tier.
Limitation: Difficult to scale.
3. Three-Tier Architecture
Structure:
Tier 1: Client (User Interface)
Tier 2: Application Server (Business Logic)
Tier 3: Database Server
Example: Web application with HTML/CSS (UI), PHP/Java (logic), and MySQL
(database).
Advantage:
Security: Database hidden behind application layer
Scalability: Easy to add more clients or servers
Maintainability: Business logic is separate
Summary Table:
1. DDL Interpreter
Definition: The DDL (Data Definition Language) interpreter handles statements like
CREATE TABLE, ALTER TABLE, and DROP TABLE.
Function: It parses and interprets these commands and sends the results to the data
dictionary (metadata storage) to update database structure definitions.
Example:
CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
Marks INT
);
The DDL interpreter reads this command and updates the metadata to store the
definition of Students table.
2. DML Compiler
Definition: The DML (Data Manipulation Language) compiler translates high-level
data manipulation commands (INSERT, UPDATE, DELETE, SELECT) into low-level
instructions.
Function: It converts SQL statements into an execution plan (a step-by-step
approach for accessing data).
Example:
SELECT Name FROM Students WHERE Marks > 80;
The DML compiler converts this into an internal plan:
Access the Students table.
Filter rows with Marks > 80.
Retrieve only the Name field.
Definition: This is the execution unit that follows the compiled execution plan to
actually retrieve or modify data.
Function: Interacts with storage and buffer managers to fetch data blocks, apply
conditions, and return results.
Example: In the above SELECT query, the query evaluation engine physically reads
relevant disk blocks, filters them, and sends the list of student names to the user.
Working:
Security Management: Create user accounts, assign privileges, and protect against
unauthorized access.
Backup and Recovery: Schedule regular backups and plan disaster recovery.
Capacity Planning: Forecast storage needs and prepare for future growth.
Example: In a hospital system, the DBA ensures that only doctors can update patient
records, backups are taken daily, and the system can handle thousands of patients
without slowing down.
Chapter no. 02
1. Client-Server Architecture:
Client-server architecture is a computing model where the client (usually a user
device or software) requests a service, and the server (a powerful machine or
software) provides that service. The two communicate over a network (like the
internet or a local network) using a specific protocol (e.g., HTTP, FTP, SMTP).
Working:
Client Side – The client is the requester.
It could be:
-A web browser requesting a webpage from a web server.
-A mobile banking app requesting account details from the bank’s server.
Server Side – The server processes the request and returns a response.It:
-Receives the request.
-Processes it (possibly by fetching data from a database).
-Sends back the requested information or service.
Communication – This happens via a network using protocols (e.g., TCP/IP for
general communication, HTTP for web pages).
Example:
Google Search
Client: Your web browser.
Server: Google’s data servers.
Process: You type a query → request goes to Google server → server searches data
→ sends results to your browser.
Advantages:
Centralized control of data.
Easy to update and maintain on the server side.
Multiple clients can use the same service.
Disadvantages:
If the server goes down, clients can’t access the service.
Heavy load on the server if too many requests come at once.
a. Single-tier Architecture
In single-tier architecture, client and server functions are performed on the same
machine.
There’s no network communication – everything happens locally.
Example:
Microsoft Excel on your computer (both application logic and data storage are on the
same PC).
Advantages:
Fast execution (no network delay).
Easy to manage.
Disadvantages:
Limited scalability (only one machine).
Not suitable for multiple users.
b. Two-tier Architecture
Here, the client is on one machine and the server (usually a database) is on another
machine. The application logic might be on the client.
Example:
A college result software where:
Client: Frontend application installed on staff computers.
Server: Database server storing all student records.
Advantages:
Better data security on the server.
Supports multiple clients.
Disadvantages:
Performance may degrade if many clients connect at once.
c. Three-tier Architecture
Separates the system into three layers:
Example:
Online shopping website:
Presentation Layer: Web browser showing the site.
Application Layer: Server application processing orders.
Data Layer: Database storing products and orders.
Advantages:
Easier maintenance.
Better scalability and security.
Disadvantages:
Slightly more complex than two-tier.
d. N-tier Architecture
Extension of three-tier where there are more than three layers (e.g., extra layers for
authentication, caching, API gateways, etc.).
Example:
Large-scale apps like Amazon:
Client Layer (browser or app).
Web Server Layer.
Application Server Layer.
Database Layer.
Additional layers like caching servers, analytics servers.
Advantages:
Highly scalable.
Easier to add new features.
Disadvantages:
Higher complexity.
More infrastructure cost.
a. Robust
The architecture should handle failures without crashing.
Example: If one server fails, load balancing should redirect requests to another.
i. Delivered on Time
Good architecture helps teams work in parallel, making timely delivery easier.
Example: Frontend and backend teams working independently and integrating later.
Instead of just storing values like numbers or strings, these models store objects that
have:
Explanation
In object-based logical models:
The world is viewed as a collection of objects.
Each object belongs to a class (similar to OOP).
Classes can have subclasses (inheritance).
Objects can relate to other objects through relationships.
Example:
Imagine a Library Database:
Object → Book
Attributes: Title, Author, ISBN
Methods: Borrow(), Return()
Object → Member
Attributes: Name, MembershipID
Methods: PayFees(), ReserveBook()
Advantages
Rich data representation – Can store complex data like images, audio, video, not just
numbers and text.
Encapsulation – Data and operations are packaged together.
Inheritance – Reduces redundancy by reusing attributes/methods in subclasses.
Better for complex applications – Useful in CAD, multimedia databases, scientific
research, etc.
Disadvantages
Complexity – More difficult to design compared to simple relational models.
Performance issues – Objects require more storage and processing.
Less standardization – Fewer universally accepted query languages.
Learning curve – Requires knowledge of both OOP and database concepts.
Explanation
In this model:
Fields → Store individual values (like Name, Age).
Records → Combination of fields representing one entity.
Files (tables) → Collection of related records.
There are three main types:
Relational Model → Data stored in tables.
Hierarchical Model → Data in a tree structure.
Network Model → Data in a graph structure.
Example:
For a STUDENTS table:
RollNo Name Age Marks
101 Riya 20 85
102 Arjun 21 90
Advantages:
Simplicity – Easy to understand for users.
Efficient storage – Fixed-size records allow faster access.
Good for structured data – Works well when the schema is fixed.
Disadvantages:
Poor handling of complex data – Not suitable for multimedia or nested objects.
Rigid structure – Changing the schema can be difficult.
Redundancy – May store duplicate data.
6. Relational Model
Proposed by E.F. Codd in 1970, the Relational Model is the most widely used logical
model in modern databases.
It stores data in the form of tables (relations) made up of rows (tuples) and columns
(attributes).
Keys →
Primary Key: Uniquely identifies each record.
Foreign Key: Links tables together.
Candidate Key: Possible keys for unique identification.
Constraints → Rules to ensure data integrity (NOT NULL, UNIQUE, CHECK, etc.).
Example Table:
STUDENTS
b. Advantages
Simplicity – Easy to understand and design.
Data independence – Physical storage doesn’t affect logical design.
Flexibility – Can be modified without major disruption.
Data integrity – Enforces constraints.
Standardized query language – SQL.
c. Disadvantages
Performance issues – May be slower for very large datasets compared to
specialized DBs.
Overhead – Requires complex joins for related data.
Not ideal for complex data – Struggles with multimedia or unstructured data.
7. Hierarchical Model
The Hierarchical Model organizes data into a tree-like structure, where each record
(node) has one parent but can have many children.
It’s an older model, mainly used in mainframe systems.
Example:
Company Database:
Root: Company
Child: Department
Child: Employee
b. Advantages
Efficiency – Good for queries with predictable structure.
Data integrity – Parent-child links are explicit.
Fast navigation – Can quickly traverse known paths.
c. Disadvantages
Rigid structure – Hard to reorganize or change.
Redundancy – Duplicate data if relationships are complex.
Poor flexibility – One parent per child limit.
b. Advantages
Flexibility – Can represent complex relationships easily.
Efficiency – Direct navigation between related records.
Supports many-to-many relationships.
c. Disadvantages
Complexity – Harder to design and maintain.
Navigation-based – User must know the path to data.
Declining use – Mostly replaced by relational databases.
Chapter no. 03
1. ER Model.
The Entity–Relationship (ER) model is a conceptual framework used in database
design to visually represent the data and the relationships between data items. It
was introduced by Peter Chen in 1976 as a way to create a clear and simple
blueprint of a database before actually implementing it in a DBMS.
The ER model helps bridge the gap between real-world objects and database
structures.
It represents:
Entities → The objects in the real world.
Attributes → Properties of those objects.
Relationships → How entities are connected.
Example:
In a college database:
Entities → Student, Course, Faculty.
Attributes → Student_ID, Name, Age, Course_Name.
Relationships → “Enrolls In” (between Student and Course).
2. Components of an ER Diagram
An ER diagram is the visual representation of the ER model.
It has three main components:
Entities
Attributes
Relationships
a. Entities
An entity is an object in the real world that can be distinctly identified. It can be a
person, place, thing, or concept.
Types of Entities:
i. Strong Entity Type
An entity that can exist independently and has a primary key.
Represented by a rectangle in ER diagrams.
Example:
Student with attributes like Student_ID, Name, Age.
Student_ID acts as the primary key.
Example:
Dependent in an employee database.
Depends on Employee entity.
Primary key is a combination of Employee_ID and Dependent_Name.
b. Attributes
Attributes describe the properties of an entity.
Types of Attributes:
i. Composite Attributes
Attributes that can be divided into smaller subparts.
Example: Full_Name → First_Name + Middle_Name + Last_Name.
v. Key Attributes
Uniquely identify an entity in the entity set.
Represented by an oval with the attribute name underlined.
Example: Student_ID in the Student entity.
c. Relationships
A relationship shows how two or more entities are connected.
Example:
Student — Enrolls In → Course.
Represented by a diamond shape in ER diagrams.
a. Super Key
A set of one or more attributes that can uniquely identify a record.
Example: (Student_ID), (Student_ID + Name).
b. Composite Key
A key that consists of two or more attributes together to uniquely identify an entity.
Example: (Course_ID, Semester) for a course offered multiple times.
c. Candidate Key
Minimal set of attributes that uniquely identify an entity.
Example: In a Student table: Student_ID, Email_ID (both can be candidate keys).
d. Primary Key
One candidate key chosen as the main identifier of records.
Example: Student_ID as the primary key in the Student entity.
e. Alternate Key
Candidate keys that are not chosen as the primary key.
Example: Email_ID in the Student entity.
f. Secondary Key
An attribute used for data retrieval but not necessarily unique.
Example: Department in a Student entity.
4. Relations
a. Relationship Set
A collection of similar relationships.
Example: All “Enrolls In” relationships between Students and Courses form a
relationship set.
b. Degree of Relationship
The number of entity types involved in a relationship.
i. Unary Relationship
Relationship between entities of the same type.
Example: Employee — Manages → Employee.
1. One-to-One (1:1)
Definition:
One entity instance from Entity A is associated with at most one entity instance from
Entity B, and vice versa.
Example:
Entity A: Person
Entity B: Passport
Each person has only one passport, and each passport belongs to only one person.
Diagram:
Person (1) <-----> (1) Passport
Example:
Like a school locker assigned to exactly one student.
2. One-to-Many (1:N)
One entity instance from Entity A can be related to many instances in Entity B, but
each instance in Entity B is related to only one instance in Entity A.
Example:
Entity A: Teacher
Entity B: Student
One teacher can teach many students, but each student has only one main teacher
(in this relationship context).
Diagram:
Teacher (1) <------> (N) Student
Analogy:
A tree (teacher) with multiple branches (students).
3. Many-to-One (N:1)
Many instances in Entity A relate to one instance in Entity B.
Example:
Entity A: Employee
Entity B: Department
Many employees can work in one department, but a department is their only
assigned home department.
Diagram:
Employee (N) <------> (1) Department
4. Many-to-Many (M:N)
Many instances of Entity A can be associated with many instances of Entity B.
Example:
Entity A: Student
Entity B: Course
A student can enroll in multiple courses, and a course can have multiple students.
Diagram:
Student (M) <------> (N) Course
analogy: Like guests and events — many guests attend many events.
(b) Participation Constraints
Participation constraints specify whether all or only some instances of an entity
participate in a relationship.
1. Total Participation
Every instance of the entity must participate in the relationship.
In ER diagrams, total participation is shown by a double line.
Example:
Every employee must belong to a department.
Employee ==belongs to== Department
2. Partial Participation
Some instances of the entity participate in the relationship.
In ER diagrams, partial participation is shown by a single line.
Example:
Not every student is assigned to a club in a school.
Example:
Customer — places — Order
6. Specialization
Specialization is the process of dividing an entity into subclasses based on distinct
characteristics.
Example:
General entity: Employee
Subclasses: Engineer, Manager, Technician
analogy:
Think of a university: "Student" specialized into "Undergraduate" and "Postgraduate"
based on the level of study.
Notation:
In ER diagrams, specialization is shown as a top-down triangle from the parent entity
to subclasses.
7. Generalization
Generalization is the reverse of specialization — it combines multiple entities that
share common attributes into a generalized super-entity.
Example:
Entities: Car, Bike → generalized into Vehicle.
Both Car and Bike have attributes like Registration Number, Owner, etc.
Notation:
Bottom-up triangle pointing to the generalized entity.
Analogy:
Like children inheriting certain traits from parents, but also having unique traits.
Example:
Superclass: Employee
Predicate: Salary > 50,000 → Subclass: Senior Employee
Example:
Superclass: Vehicle (attribute: Type)
Type = "Car" → Subclass: Car
Type = "Bike" → Subclass: Bike
Example:
In a university, a Student entity can be classified into “Hostel Resident” and “Day
Scholar” based on admin decision.
Advantage:
Flexible, not restricted by attribute values.
1. Disjointness Constraints
Disjoint Specialization:
An entity can belong to only one subclass of the specialization.
Example: A Staff Member can be either a Teacher or an Administrator, not both.
Overlapping Specialization:
An entity can belong to multiple subclasses at the same time.
Example: A Person can be both a Doctor and a Researcher.
2. Completeness Constraints
Total Specialization: All entities of the superclass must belong to at least one
subclass.
Example: Every Employee is either a Permanent Employee or a Temporary
Employee.
Partial Specialization: Some entities in the superclass do not belong to any subclass.
Example: Some Employees are just general employees without specific
classification.
10. Aggregation
Aggregation is an abstraction in ER odelling that treats a relationship itself as an
entity so it can participate in another relationship.
Use case: When we want to express a relationship between a relationship and
another entity.
Example:
Relationship: Teaches (Professor – Course)
Steps:
Understand requirements from the real world.
Example: “A library has books, members, and loans.”
Identify entities — Book, Member, Loan.
Identify relationships — Member borrows Book (Loan).
Assign attributes — Book (ISBN, Title, Author), Member (ID, Name), Loan
(DateIssued, DateReturned).
Apply constraints — One book can be borrowed by one member at a time.
Requirements:
A set of customers.
Each customer owns one or more cars.
Each car may have zero or many accidents recorded.
Entities:
Customer (CustomerID, Name, Address)
Car (CarID, Model, Year)
Accident (AccidentID, Date, Description)
Relationships:
Owns (Customer – Car) → One-to-Many
Involved_in (Car – Accident) → One-to-Many
Diagram:
1. Entities to Table
Entities in an ER diagram become tables in a database. Each entity’s attributes
become the columns of that table, and the primary key of the entity becomes the
primary key of the table.
Mapping Rule:
Each regular entity becomes a separate table, with:
All its attributes as columns.
Primary key as defined in ER model.
Example:
Entity: Customer (CustomerID, Name, Email)
→ Table:
CUSTOMER
------------------------
CustomerID (PK) | Name | Email
Mapping Rule:
Create a table for the weak entity.
Include the primary key of the strong entity as a foreign key.
The combination of the weak entity’s partial key and the foreign key becomes the
primary key.
Example:
Weak Entity: Dependent (DependentName, Relationship) depends on Employee
(EmpID).
→ Table:
DEPENDENT
--------------------------------------
EmpID (PK, FK) | DependentName (PK) | Relationship
Example:
PhoneNumbers for Employee → Separate table:
EMPLOYEE_PHONE
--------------------------
EmpID (FK) | PhoneNumber
3. Relationships to Table
When converting ER relationships to tables, the approach depends on constraints
and cardinalities.
Example:
Customer (CustomerID) – Order (OrderID, CustomerID).
(b) Merged Relationship Approach
Rule: For 1-to-1 relationships, merge both entities into a single table if they are
closely related.
Example:
Person (PersonID) – Passport (PassportNumber) can be merged into:
PERSON_PASSPORT
---------------------------
PersonID (PK) | Name | PassportNumber
Example:
Student – Course relationship:
ENROLLMENT
--------------------------
StudentID (FK) | CourseID (FK) | DateEnrolled
(a) Tables
Separate Table for Each Subclass:
Create a table for the superclass and a table for each subclass with its unique
attributes.
Example:
EMPLOYEE (EmpID, Name)
PERMANENT_EMP (EmpID (PK, FK), Salary)
TEMPORARY_EMP (EmpID (PK, FK), HourlyRate)
(b) Columns
Add a Type Column:
Store subclass type in the superclass table using a discriminator attribute.
Example:
EMPLOYEE (EmpID, Name, EmployeeType, Salary, HourlyRate)
1. Data Definition
SQL defines how the database structure (tables, columns, relationships) should be
created.
Example: Creating a table for storing employee details.
2. Data Manipulation
SQL lets you insert, update, delete, and retrieve data.
Example: Adding new employee data or modifying an existing salary.
3. Data Control
SQL manages permissions and security for who can view or modify data.
4. Data Querying
SQL allows you to fetch only the data you need by writing queries.
Example: Show all employees in the "IT" department.
Analogy:
Think of SQL as the rules for running a restaurant:
a. CREATE Statement
Purpose: Used to create new database objects (like tables).
Syntax:
Example:
Here:
Examples:
Add a new column:
ALTER TABLE Students ADD Email VARCHAR(100);
Drop a column:
ALTER TABLE Students DROP COLUMN City;
c. DROP Statement
Purpose: Permanently deletes a table or other database object.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Students;
Note: Deletes both structure and data so no recovery unless you have a backup.
d. RENAME Statement
Purpose: Changes the name of a table or database object.
Syntax:
RENAME TABLE old_name TO new_name;
Example:
RENAME TABLE Students TO CollegeStudents;
e. TRUNCATE Statement
Purpose: Deletes all rows from a table but keeps the table structure.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE Students;
Faster than DELETE because it does not log each row deletion.
Cannot be rolled back in most databases.
Syntax:
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL
);
b. CHECK Constraint
Ensures that a column’s value meets a specified condition.
Syntax:
c. DEFAULT Constraint
Assigns a default value to a column if none is provided.
Syntax:
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
City VARCHAR(50) DEFAULT 'Mumbai'
);
Example: If the city is not entered, it will automatically be set to "Mumbai".
Constraint Purpose Example
NOT NULL Prevents null values Name VARCHAR(50) NOT NULL
CHECK Enforces a condition CHECK (Age >= 18)
DEFAULT Auto-assigns a value DEFAULT 'Mumbai'
The main rule of entity integrity is: No primary key attribute can be NULL, and all
rows must have a unique primary key value.
Think of a table as a school register — every student must have a unique roll
number; you cannot have two students with the same roll number, and a student
cannot have no roll number at all.
Here:
Roll_No is the primary key.
Two students cannot have the same Roll_No.
A row without a Roll_No is not allowed.
Violation Example:
Roll_No Name Age Class
1 Ramesh 15 10A
1 Suresh 16 10B
NULL Mahesh 15 10A
Here:
Emp_ID is the primary key — no duplicates, no NULL.
Email is unique — two employees cannot have the same email.
Phone_No is unique — two employees cannot share a phone number.
->Entity integrity ensures the existence and uniqueness of each record. The primary
key is mandatory for identification, while unique constraints provide additional
uniqueness rules for other columns.
Introduction:
Referential integrity is a rule that maintains consistency between related tables. It
ensures that a foreign key value in one table must match an existing primary key
value in another table or be NULL.
This prevents situations where you have a record pointing to something that does
not exist — often called an orphan record.
Think of it as: If a student is assigned to a class, that class must exist in the Classes
table.
If the class is deleted, we must decide what happens to the students in that class.
Example:
CREATE TABLE Departments (
Dept_ID INT PRIMARY KEY,
Dept_Name VARCHAR(50)
);
Here:
Departments is the parent table.
Employees is the child table.
Dept_ID in Employees must match a Dept_ID in Departments.
Referential Integrity Rules
When inserting, updating, or deleting data:
1. Insert Rule: we cannot insert a foreign key value that doesn’t exist in the parent
table.
Example: Adding an employee with Dept_ID = 5 when there is no department with
Dept_ID = 5.
2. Update Rule: we cannot change a primary key in the parent table if it’s being
referenced in the child table (unless you handle it with ON UPDATE actions).
3. Delete Rule: we cannot delete a parent record if there are child records depending
on it (unless you handle it with ON DELETE actions).
Syntax
DESCRIBE table_name;
or
SHOW COLUMNS FROM table_name;
Example
Let’s say we have a table students:
Output:
Tables_in_school_db
students
teachers
courses
Step 4 — View structure of a specific table
DESCRIBE students;
or
SHOW COLUMNS FROM students;
a. INSERT Statement
Used to add new records into a table.
Syntax:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Example:
INSERT INTO students (id, name, age, marks, admission_date)
VALUES (1, 'Asha', 20, 88.50, '2023-07-01');
b. DELETE Statement
Used to remove existing records from a table.
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM students
WHERE id = 1;
c. UPDATE Statement
Used to change existing data in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
UPDATE students
SET marks = 90.00
WHERE name = 'Asha';
Example:
UPDATE students SET marks = 95 WHERE id = 2;
COMMIT;
b. ROLLBACK
Undoes changes since the last COMMIT.
Useful when an incorrect update/delete has been made.
Example:
UPDATE students SET marks = 20 WHERE id = 2;
ROLLBACK; -- This will undo the update
->Always use WHERE with UPDATE and DELETE to avoid affecting all rows.
->Use ROLLBACK before COMMIT to undo changes.
->DML without COMMIT will not be permanent in transactional systems until
committed.