Dbms Notes (Nep Model)
Dbms Notes (Nep Model)
Data:
• It is a collection of information.
• The facts that can be recorded and which have implicit meaning known as 'data'.
• Example: Customer ----- 1. cname.
2. cno.
3. ccity
Database:
• It is a collection of interrelated data.
• These can be stored in the form of tables.
• A database can be of any size and varying complexity.
• A database may be generated and manipulated manually or it may be computerized.
• Example: Customer database consists the fields as cname, cno, and ccity
Database System:
• It is computerized system, whose overall purpose is to maintain the information and to
make that the information is available on demand.
Advantages of DBMS:
o Data Independence: DBMSs provide a layer of abstraction between the physical
storage of data and the applications that access the data. This means that changes
to the data structure do not necessarily affect the applications, making maintenance
easier.
o Data Integrity :DBMSs enforce rules and constraints that ensure data accuracy
and consistency across the database. This helps maintain the integrity of data,
reducing errors and inconsistencies.
o Data security: DBMSs provide robust security features that protect data from
unauthorized access and breaches.
o Data Backup and Recovery: DBMSs have built-in backup and recovery tools,
ensuring that data can be restored in the event of a system failure, accidental
deletion, or corruption.
o Concurrency Control : DBMSs allow multiple users to access and
modify data simultaneously without causing conflicts. They manage
concurrent access through locking mechanisms.
Applications Of Database
o Banking: Manage customer data, process transactions, and detect fraud.
o Education: Handle student records, library management, and online
learning systems. Universities: registration, grades
o Government: Manage citizen services, law enforcement data, and public
infrastructure.
o Manufacturing: Oversee supply chain, quality control, and production
planning.
o Transportation: Optimize fleet management, logistics, and ticketing systems.
Database users are categorized based up on their interaction with the data
base. These are seven types of data base users in DBMS.
3. System Analyst:
• System Analyst is a user who analyses the requirements of parametric end users.
They check whether all the requirements of end users are satisfied.
4. Sophisticated Users:
• Sophisticated users can be engineers, scientists, business analyst, who are familiar
with the database.
• They can develop their own data base applications according to their requirement.
• They don’t write the program code but they interact the data base by writing SQL
queries directly through the query processor.
Database system contains not only the database itself but also an entire definition or
description of the database structure and constraints also known as metadata of the
database. This definition is stored within the DBMS catalogue, which contains
information like the structure of every file, the sort and storage format of every data item,
and various constraints/rules on the information.
• The DBMS must implement concurrency control in the software to make sure that
several users trying to update equivalent data do so in a controlled manner in order
that the results of the updates are correct.
• For instance, when several reservation agents attempt to assign a seat on an airline
flight, the DBMS should make sure that each seat is often accessed by just one user
agent at a single time for an assignment to a passenger.
• A fundamental role of multi-user DBMS software is to make sure that concurrent
transactions operate correctly and efficiently with no inconsistency.
Data Models:
•
It defines the data elements and the relationships between the data elements. Data
Models are used to show how data is stored, connected, accessed and updated in
the database management system.
• Here, we use a set of symbols and text to represent the information so that
members of the organization can communicate and understand it.
Some of the Data Models in DBMS are:
1. Hierarchical Model
2. Network Model
3. Entity-Relationship Model
4. Relational Model
5. Object-Oriented Data Model
1. Hierarchical Model
• Hierarchical Model was the first DBMS
model. This model organizes the data in
the hierarchical tree structure.
• The hierarchy starts from the root which
has root data and then it expands in the
form of a tree adding child node to the
parent node.
• This model easily represents some of the
real-world relationships like food recipes,
sitemap of a website etc.
1. Ability to Merge more Relationships: In this model, as there are more relationships so
data is more related. This model has the ability to manage one-to-one relationships as
well as many-to- many relationships.
2. Many paths: As there are more relationships so there can be more than one path to the
same record. This makes data access fast and simple.
3. Circular Linked List: The operations on the network model are done with the help of the
circular linked list. The current position is maintained with the help of a program and
this position navigates through the records according to the relationship.
3. Entity-Relationship Model
• Entity-Relationship Model or simply ER Model is a high-level data model diagram.
• In this model, we represent the real-world problem in the pictorial form to make it
easy for the stakeholders to understand.
• It is also very easy for the developers to understand the system by just looking at the ER
diagram. We use the ER diagram as a visual tool to represent an ER Model.
• ER diagram has the following three components:
• In the above diagram, the entities are Teacher and Department. The attributes of Teacher
entity are Teacher_Name, Teacher_id, Age, Salary, Mobile_Number. The
attributes of entity Department entity are Dept_id, Dept_name. The two entities are
connected using the relationship. Here, each teacher works for a department.
Advantages of ER Model
• Simple: Conceptually ER Model is very easy to build. If we know the relationship between
the attributes and the entities we can easily build the ER Diagram for the model.
• Effective Communication Tool: This model is used widely by the database designers for
communicating their ideas.
• Easy Conversion to any Model: This model maps well to the relational model and can
be easily converted relational model by converting the ER model to the table. This model
can also be converted to any other model like network model, hierarchical model etc.
Disadvantages of ER Model
• No industry standard for notation: There is no industry standard for developing an ER
model. So one developer might use notations which are not understood by other
developers.
• Hidden information: Some information might be lost or hidden in the ER model. As it is
a high- level view so there are chances that some details of information might be hidden.
4. Relational Model
• Relational Model is the most widely used model. In this model, the data is maintained in
the form of a two-dimensional table. All the information is stored in the form of row and
columns.
• The basic structure of a relational model is tables. So, the tables are also called
relations in the relational model.
• Example: In this example, we have an Employee table.
Database Languages:
o A DBMS has appropriate languages and interfaces to
express database queries and updates.
o Database languages can be used to read, store and
update the data in the database. Types of Database
Language
Database Interfaces:
• A database management system (DBMS) interface is a user interface which allows for the
ability to input queries to a database without using the query language itself.
3. Web-Based Interface
o A browser-based interface that allows users to interact with the database through
a web application. This type of interface is often used for managing databases
remotely.
Examples:
MongoDB, Amazon RDS Management Console
Example: JDBC,ODBC
Classification of DBMS
Database Management Systems (DBMS) can be classified based on several criteria,
including the data model, the number of users, the number of sites, and the type of access
path.
E-R Model
Introduction
• The Entity-Relationship (E-R) Model is a conceptual framework used to describe the
structure of a database.
• It defines the data elements and the relationships between them, providing a high-level
view of how data is organized and connected.
• The E-R model is widely used in the design and analysis of databases, especially in the
initial stages of database design.
Component of ER Diagram
1. Entity:
• An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.
• Consider an organization as an example- manager, product, employee, department etc.
can be taken as an entity.
a. Weak Entity
• An entity that depends on another entity called a weak entity. The weak entity doesn't
contain any key attribute of its own. The weak entity is represented by a double rectangle.
b. Strong Entity
• A strong entity is an entity that is not dependent on any other entity. It has a primary key,
or a table includes a primary key.
Example-
Consider the following ER diagram-
In this ER diagram,
Two strong entity sets “Student” and “Course” are related to each other.
• Student ID and Student name are the attributes of entity set “Student”.
• Student ID is the primary key using which any student can be identified uniquely.
• Course ID and Course name are the attributes of entity set “Course”.
• Course ID is the primary key using which any course can be identified uniquely.
• Double line between Student and relationship set signifies total participation.
• It suggests that each student must be enrolled in at least one course.
• Single line between Course and relationship set signifies partial participation.
• It suggests that there might exist some courses for which no enrolments are made.
2. Attribute
The attribute is used to describe the property of an entity. Eclipse
is used to represent an attribute.
For example, id, age, contact number, name, etc. can be attributes of a
student.
a. Key Attribute
The key attribute is used to represent the main
characteristics of an entity. It represents a primary key. The key
attribute is represented by an ellipse with the text underlined.
b. Composite Attribute
An attribute that composed of many other
attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those
ellipses are connected with an ellipse.
c. Multivalued Attribute
An attribute can have more than one value. These attributes are known as
a multivalued attribute. The double oval is used to represent multivalued
attribute.
For example, a student can have more than one phone number.
d. Derived Attribute
An attribute that can be derived from other attribute is known
as a derived attribute. It can be represented by a dashed ellipse.
For example, A person's age changes over time and can be derived
from another attribute like Date of birth.
3. Relationship
A relationship is used to describe the relation between entities. Diamond or rhombus is
used to represent the relationship.
Types of relationship are as follows:
a. One-to-One Relationship
When only one instance of an entity is associated with the relationship, then it is known
as one to one relationship.
For example, A female can marry to one male, and a male can marry to one female
b. One-to-many relationship
When only one instance of the entity on the left, and more than one instance of an entity on
the right associates with the relationship then this is known as a one-to-many relationship.
For example, Scientist can invent many inventions, but the invention is done by the only
specific scientist.
b. Many-to-one relationship
When more than one instance of the entity on the left, and only one instance of an entity on
the right associates with the relationship then it is known as a many-to-one relationship.
For example, Student enrolls for only one course, but a course can have many students.
c. Many-to-many relationship
When multiple instances of one entity can be associated with multiple instances of another
entity.
For example, Employee can assign by many projects and project can have many employees.
Relationship Set-
A relationship set is a set of relationships of same type.
Example-
Set representation of above ER diagram is-
On the basis of degree of a relationship set, a relationship set can be classified into the
following types-
Roles refer to the function that an entity plays in a relationship. When entities participate in a
relationship, they take on roles that define how they interact within that relationship.
• These ratios define how many instances of one entity can or must be associated with
instances of another entity.
Types of Cardinality
There can be 4 types of cardinality –
1. One-to-one (1:1) –
In this type of cardinality mapping, an entity in E1 is connected to at most one entity in E2.
2. One-to-many (1: N) –
In this type of cardinality mapping, an entity in E1 is associated with any number of entities
in E2.
3. Many-to-one (N:1) –
In this type of cardinality mapping, an entity in A is connected to at most one entity in B.
4. Many-to-many (N: N) –
In this type of cardinality mapping, an entity in A is associated with any number of entities in
B, and an entity in B is associated with any number of entities in A.
Participation Constraints:
Participation Constraints refer to rules that dictate how entities in a relationship can or
must participate. It can be either total or partial.
When each entity in an entity set participates in a relation, it is called Total Participation.
However, when all entities in the given entity set do not participate in a relation, it is called
Partial Participation.
Structural Constraints:
• Cardinality Ratios and Participation Constraints taken together are called Structural
Constraints.
• The name constraints refer to the fact that such limitations must be imposed on the
data, for the DBMS system to be consistent with the requirements.
A simple ER Diagram:
• In the following diagram we have two entities Student and College and their relationship.
• The relationship between Student and College is many to one as a college can have many
students however a student cannot study in multiple colleges at the same time. Student
entity has attributes such as Stu_Id, Stu_Name & Stu_Addr and College entity has
attributes such as Col_ID & Col_Name.
• Here are the geometric shapes and their meaning in an E-R Diagram.
E R Diagram for Hospital management:
ER Diagram for College Database
References:
1. [Link]
2. [Link]
3. [Link]
types
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
info/215/erd/#:~:text=Data%20modeling%20is%20a%20technique,system%20
using%20diagrams%20and%20symbols.&text=The%20highest%20level%20of%
20abstraction,data%20requirements %20for%20a%20database.
10. [Link]
11. [Link]
12. [Link]
model/
13. [Link]
14. [Link]
types/
15. [Link]
16. [Link]
17. [Link]
18. [Link]
19. [Link]
Conventions,-and-Design- Issues_11434/
20. [Link]
conventions-and-design-issues
Relational Data Model & Relational Algebra
2.1 Relational model in DBMS
• In relational model, the data and relationships are represented by collection of inter-
related tables.
• Each table is a group of columns and rows, where column represents attribute of
an entity and rows represents records.
• The table name and column names are helpful to interpret the meaning of values
in each row.
• In the formal relational model terminology, a row is called a tuple, a column header
is called an attribute, and the table is called a relation.
• The data type describing the types of values that can appear in each column is
represented by a domain of possible values.
The structure of the relational model is based on a few fundamental concepts, which
include:
1. Relation (Table)
• A relation is a table with rows and columns. In the context of a relational
database, it represents a set of entities or relationships.
• Each row in the table is called a tuple, representing a single entity or record.
• Each column in the table is called an attribute, representing a data field or
property of the entity.
2. Attributes (Columns)
• Attributes are the properties or characteristics of a relation. They define the type
of data that can be stored in a table.
• Each attribute has a specific domain, which is the set of permissible values that
the attribute can have.
3. Domain
• A domain is the set of permissible values for an attribute. For example, the
domain for an attribute "age" might be all integers between 0 and 120.
• Each attribute in a relational model is associated with a domain that defines the
possible values it can hold.
4. Tuple (Row)
• A tuple is a single row in a table, representing a single record or instance of the
relation.
• A tuple is a finite ordered list of elements, where each element is a value
corresponding to one of the attributes.
5. Degree
• The degree of a relation is the number of attributes (columns) in a table. It
indicates the number of properties the relation captures.
6. Cardinality
• Cardinality refers to the number of tuples (rows) in a relation. It indicates the
number of records stored in the table.
Relation schema- A relational schema is the design for the table.
It includes none of the actual data, but is like a blueprint or design for the table, so
describes what columns are on the table and the data types. It may show basic table
constraints ( e.g. if a column can be null) but not how it relates to other tables.
(A1,A2,...,An), it means that the relation RRR has attributes A1,A2,...,AnA1, A2, ...,
AnA1,A2,...,An
Null value: A field with a NULL value is a field with no value. Primary key can’t be a null
value.
1. Relation Name
• Each relation (table) has a unique name within the database schema.
2. Tuples
• A relation consists of a set of tuples (rows). Each tuple represents a single entry in
the relation and contains a set of attribute values.
3. Attributes
• Each relation is defined by a fixed set of attributes (columns), where each attribute
has a name and a domain (the set of allowable values).
4. Attribute Domain
• Each attribute in a relation has a domain, which is the set of permissible values
for that attribute. For example, an attribute "Age" might have a domain of
integers.
5. Atomicity
6. NULL Values
7. Integrity Constraints
• Relations enforce integrity constraints, such as primary keys, foreign keys, and
unique constraints, to maintain the consistency and accuracy of the data.
• In a relational model, constraints are rules that enforce the integrity and validity of the data
in the database.
• These constraints ensure that the database remains accurate, consistent, and adheres to
the business rules.
• Here are the key types of constraints in the relational model:
Domain constraints
• Each table has certain set of columns and each column allows a same type of data, based
on its data type. The column does not accept values of any other data type.
• They ensure that the data entered into a database is valid and adheres to the predefined
rules or domains.
Example:
Integer Example:
• Attribute: Age
• Domain: Integer values between 0 and 120.
• Constraint: The Age attribute must hold an integer value
within this range.
String Example:
• Attribute: CountryCode
• Domain: A set of predefined country codes such as "US", "CA", "GB".
• Constraint: The CountryCode attribute must hold one of the specified country codes.
In the given fig, value ‘A’ is not allowed since only integer values can be taken by the age
attribute.
Key constraints
o Key Constraints ensure that each tuple (row) within a relation (table) can be uniquely
identified, and they play a crucial role in maintaining data integrity.
Here’s an overview of the key types of key constraints:
• A primary key is a unique identifier for each tuple in a relation. The primary key constraint
ensures that no two rows can have the same value for this key and that it cannot contain
NULL values.
• Characteristics:
o Uniqueness: Each value of the primary key must be unique across all rows in the table.
o Non-nullability: The primary key cannot have NULL values; every row must have a
valid primary key value.
• Example: In a students table, StudentID might be the primary key. No two students can share
the same StudentID, and every student must have a StudentID.
• Notation: Often denoted by underlining the attribute(s) in the schema, e.g.,
Students(StudentID, Name, Birthdate) where StudentID is underlined.
• A unique key constraint ensures that all values in a particular attribute or set of attributes
are unique across the relation, similar to a primary key, but it can accept NULL values.
• Characteristics:
o Uniqueness: The combination of values in the unique key columns must be unique
across all rows.
o Allowing NULLs: Unlike the primary key, a unique key can contain NULL values, but
only one NULL is allowed if the unique key is a single attribute.
• Example: In an Employees table, Email might be a unique key. No two employees can share
the same email address, but it's possible for the Email to be NULL if an employee doesn't
have one.
• Notation: Often denoted with the keyword UNIQUE in the schema definition.
• Entity integrity constraints state that primary key can never contain null value because
primary key is used to determine individual rows in a relation uniquely, if primary key
contains null value then we cannot identify those rows.
• This is achieved through the use of Primary Keys.
• Without entity integrity, it would be possible for multiple rows to represent the same entity,
leading to inconsistencies and data anomalies.
• A foreign key is an attribute (or a set of attributes) in one relation that refers to the primary
key in another relation. The foreign key constraint enforces referential integrity between two
tables.
• Characteristics:
o Referential Integrity: The foreign key values must either match a primary key value
in the referenced table or be NULL.
o Cascade Actions: On update or delete of the referenced row, certain actions can be
specified (like CASCADE, SET NULL, etc.) to maintain integrity.
• Example: In an Orders table, CustomerID might be a foreign key referencing CustomerID in
the Customers table. This ensures that each order is linked to a valid customer.
• Notation: The foreign key is often denoted by specifying the referenced table and primary
key, e.g., FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID).
Relational Algebra
Introduction
• Relational Algebra is a procedural query language.
• Relational algebra mainly provides a theoretical foundation for relational
databases and SQL.
• The main purpose of using Relational Algebra is to define operators that transform
one or more input relations into an output relation.
• These operators accept relations as input and produce relations as output
● SELECT (symbol: σ)
● PROJECT (symbol: π)
● RENAME (symbol: ρ )
● UNION (υ)
● INTERSECTION ( ),
● DIFFERENCE (-)
● JOIN
● DIVISION
● CARTESIAN PRODUCT ( x )
SELECT (σ): The SELECT operation is used for selecting a subset of the tuples
according to a given selection condition. Sigma(σ) Symbol denotes it.
σ condition (Relation)
Example:
This will fetch the tuples(rows) from table Student, for which age will be greater than 17.
Input:
σ BRANCH_NAME="Sachin" (LOAN)
Output:
• It will only project or show the columns or attributes asked for, and will also
remove duplicate data from the columns.
Example:
ΠName, Age(Student)
Above statement will show us only the Name and Age columns for all the rows of data in
Student table.
Input:
Π NAME, CITY (CUSTOMER)
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
The rename operation is used to rename the output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
ρ(STUDENT1, STUDENT)
Syntax: A X B
For example, if we want to find the information for Regular Class and Extra Class which are
conducted during morning, then, we can use the following operation:
For the above query to work, both RegularClass and ExtraClass should have the attribute time.
EMPLOYEE
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
EMPLOYEE X DEPARTMENT
Output:
PROJECT
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values
in both tables as long as the condition is satisfied.
It returns the combination of all rows from both the tables
where the condition satisfies.
Syntax
SELECT table1.column1, table1.column2
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, [Link]
FROM EMPLOYEE INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the
matching values from the right table. If there is no matching join
value, it will return NULL.
Syntax
SELECT table1.column1, table1.column2
FROM table1 LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, [Link]
FROM EMPLOYEE LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values
from the rows of right table and the matched values from the
left table. If there is no matching in both tables, it will return
NULL.
Syntax
SELECT table1.column1, table1.column2
FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, [Link]
FROM EMPLOYEE RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right
outer join. Join tables have all the records from both tables. It puts NULL
on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2
FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, [Link]
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Division operation ( ÷ ): The Division operator results in columns values in one table for which
there are other matching column values corresponding to every row in another table.
Relational Algebra Operations From Set Theory
Union operation (υ): UNION is symbolized by ∪ symbol. It includes all tuples that are
in tables A or in B. It also eliminates duplicate tuples. A ∪ B
● INTERSECTION ( ∩):
A ∩ B of two sets A and B is the set that contains all elements of A that also belong
to B (or equivalently, all elements of B that also belong to A ), but no other elements.
Retrieve students name those who participant in both arts and sports:
The result of set difference operation is tuples, which are present in one relation
but are not in the second relation.
Retrieve students name those who participant only in arts and not in sports:
ARTS - SPORTS
SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
1. COUNT FUNCTION
• COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
• COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Example: COUNT()
SELECT COUNT(*) FROM PRODUCT_MAST;
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST) FROM PRODUCT_MAST;
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function returns
the average of all non-Null values.
Syntax: AVG()
Ex: SELECT Avg(RATE) FROM PRODUCT_MAST
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines the
largest value of all selected values of a column.
Syntax: MAX()
Example: SELECT MAX(RATE) FROM PRODUCT_MAST;
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax: MIN() )
GROUP BY Statement
The GROUP BY Statement in SQL is used to arrange identical data into groups with the
help of some functions. i.e. if a particular column has the same values in different rows
then it will arrange these rows in a group.
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the
result-set by one or more
columns.
GROUP BY Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s)
Group By single column: Group By single column means, to place all the rows with
same value of only that particular column in one group.
HAVING Clause:
We can use HAVING clause to place conditions to decide which group will be the part of
final result-set. Also we cannot use the aggregate functions like SUM(), COUNT() etc. with
WHERE clause. So we have to use HAVING clause if we want to use any of these
functions in the conditions.
Syntax:
SELECT column1, function_name(column2) FROM table_name
WHERE condition
GROUP BY column1, column2 HAVING condition
ORDER BY column1, column2;
Example:
Nested Queries
In SQL, a nested query involves a query that is placed within another
query.
Output of the inner query is used by the outer query.
A nested query has two SELECT statements: one for the inner query and
another for the outer query.
Types of Nested Queries in SQL
Syntax
SELECT column1, column2, ...
FROM table1
WHERE column1 IN ( SELECT column1
FROM table2
WHERE condition );
1 John 1
2 Mary 2
3 Bob 1
4 Alice 3
5 Tom 1
1 Sales
2 Marketing
3 Finance
1 1 1000
2 2 2000
3 3 3000
4 1 4000
5 5 5000
6 3 6000
7 2 7000
SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id
FROM departments
WHERE dept_name = 'Sales');
OUTPUT:
emp_name
John
Bob
Tom
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
oTo create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.
Student_Marks
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Just like table query, we can query the view to view the data.
SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
1. DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
1. DROP VIEW MarksView;
Uses of a View :
Anomalies in the relational model refer to inconsistencies or errors that can arise when
working with relational databases, specifically in the context of data insertion, deletion,
and modification.
• Insertion Anomalies
• Deletion Anomalies
• Update Anomalies.
Example 1:
In the above table, we have four columns which describe the details about the workers like
their name, address, department and their id. The above table is not normalized, and there
is definitely a chance of anomalies present in the table.
Insertion Anomaly
• Occurs when new data cannot be added to the database because other required
data is missing.
• For example, if in the above table, we create a new row of a worker, and if it is not
allocated to any department then we cannot insert it in the table so, it will create
an insertion anomaly.
Deletion Anomaly
• If we delete some rows from the table and if any other information or data which is
required is also deleted from the database, this is called the deletion anomaly in the
database.
• For example, in the above table, if we want to delete the department number
ECT669 then the details of Rajesh will also be deleted since Rajesh's details are
dependent on the row of ECT669. So, there will be deletion anomalies in the table.
Update Anomaly
• When we update some rows in the table, and if it leads to the inconsistency of the
table then this anomaly occurs. This type of anomaly is known as an updation
anomaly.
• In the above table, if we want to update the address of Ramesh then we will have to
update all the rows where Ramesh is present. If during the update we miss any
single row, then there will be two addresses of Ramesh, which will lead to
inconsistent and wrong databases.
3.2 Decomposition
Types of Decomposition
There are two types of Decomposition:
• Lossless Decomposition
• Lossy Decomposition
Lossless Decomposition
• It ensures that when a relation (table) is decomposed into two or more smaller
relations, the original relation can be perfectly reconstructed by joining these
smaller relations without any loss of information.
• It is used to remove the redundant data from the database while retaining the
useful information. The lossless decomposition tries to ensure following things:
A B C
55 16 27
48 52 89
R1(A, B) R2(B, C)
A B B C
55 16 16 27
48 52 52 89
After performing the Join operation, we get the same original relation
A B C
55 16 27
48 52 89
Lossy Decomposition
As the name suggests, lossy decomposition means when we perform join operation on
the sub-relations it doesn’t result to the same relation which was decomposed. After the
join operation, we always found some extraneous tuples. These extra tuples generate
difficulty for the user to identify the original tuples.
Functional dependencies
Functional dependency is a concept that specifies the relationship between two sets of
attributes where one attribute determines the value of another attribute.
It is denoted as X → Y, where the attribute set on the left side of the arrow, X is
called Determinant, and Y is called the Dependent
Example:
Consider a table of student records:
101 Alice CS
103 Carol CS
In this table:
However, Name → Major is not necessarily a functional dependency because two students
with the same name could be enrolled in different majors.
Normalization
➢ Database Normalization is a technique of organizing the data in the database.
➢ Normalization is a systematic approach of decomposing tables to eliminate data
redundancy(repetition) and undesirable characteristics like Insertion, Update and
Deletion Anomalies.
➢ It is a multi-step process that puts data into tabular form, removing duplicated data
from the relation tables.
➢ It divides larger tables to smaller tables and links them using relationships.
➢ Normalization is used for mainly two purposes,
1. Eliminating redundant(useless) data.
2. Ensuring data dependencies make sense i.e data is logically stored.
To resolve the partial dependencies, we split the table into two smaller tables:
In this table:
BCNF is an advanced version of the Third Normal Form (3NF) that deals with certain types
of anomalies not addressed by 3NF.
1. It is in 3NF, meaning:
o The table is already in 2NF (i.e., no partial dependencies).
Dependencies:
Problem:
Neither Instructor nor Course alone is a candidate key. The combination of Instructor
and Course is the primary key, but we have a functional dependency (Instructor → Course)
that violates BCNF. In other words, knowing the instructor tells us the course they are
teaching, which leads to redundancy.
To make the table follow BCNF, we need to break it into two tables to eliminate the problem:
Query Processing and Transaction Management
1. Read Operation:
2. Write Operation:
A write operation modifies data in the database, changing its current state.
Writes are more critical because they can affect the integrity of the data.
Typically involves SQL commands like INSERT, UPDATE, or DELETE.
INSERT INTO students (name, age) VALUES ('John Doe', 20);
UPDATE students SET age = 21 WHERE student_id = 1;
DELETE FROM students WHERE student_id = 1;
The Lost Update problem occurs when two or more transactions read the same
data and then try to update it.
Since each transaction bases its update on the old data, the final value only reflects
one of the transactions' updates, causing the other transaction’s changes to be
"lost."
Ex Scenario: Two employees, A and B, access a shared system to update the stock
quantity of a product in a database. The current stock is 100.
• Locking Mechanisms: To avoid this issue, DBMS can use write locks to ensure
that once T1 starts updating the stock, T2 must wait until T1 completes its
transaction.
A Dirty Read problem occurs when a transaction reads data that has been modified
by another transaction but not yet committed.
If the modifying transaction is rolled back, the reading transaction ends up using
incorrect or inconsistent data.
Scenario: Two transactions, T1 and T2, are interacting with the same database record.
Assume T1 modifies a record but hasn’t committed the change yet, and T2 reads the
uncommitted data.
1. Transaction 1 (T1):
1. Updates a customer's balance from 10,000 to 5,000 due to a withdrawal.
2. Has not yet committed the transaction (the change is still tentative).
2. Transaction 2 (T2):
1. Reads the customer’s balance, which shows 5,000 (the uncommitted change
from T1).
• If T1 encounters an error and rolls back the transaction, restoring the balance to
10,000, T2 has already processed the incorrect balance of 5,000.
This leads to inconsistencies because T2 made decisions based on invalid data.
• Isolation Levels: To prevent dirty reads, DBMS uses isolation levels. For instance,
at the Read Committed isolation level, T2 will not be able to read uncommitted
changes from T1.
• Strict Two-Phase Locking (2PL): This ensures that no transaction can read data
that is in the process of being updated by another transaction until the update is
committed.
Types of failures
• Media Failure: Occurs when storage media is damaged, leading to data loss
or corruption.
ACID is an acronym that stands for atomicity, consistency, isolation, and durability (ACID).
Together.
Atomicity guarantees that all of the commands that make up a transaction are treated as
a single unit and either succeed or fail together.
This is important in the event of a system failure or power outage, in that if a transaction
wasn't completely processed, it will be discarded and the database maintains its data
integrity.
Consistency
Consistency guarantees that changes made within a transaction are populated across
the database system (e.g., nodes) and in alignment with DBMS constraints.
Isolation
Each transaction is isolated from the other transactions to prevent data conflicts. This
also helps database operations in relation to managing multiple entries and multi-level
transactions.
For example, if two users are trying to modify the same data (or even the same
transaction), the DBMS uses a mechanism called a lock manager to suspend other users
until the changes being made by the first user are complete.
Durability
Durability guarantees that once the transaction completes and changes are written to
the database, they are persisted. This ensures that data within the system will persist
even in the case of system failures like crashes or power outages. The concept of
durability is a key element in data reliability.
References:
[Link]