DBMS Unit 3
DBMS Unit 3
The basic form of an SQL query, specifically when retrieving data, is composed of a combination
of clauses. The most elementary form of an SQL query for data retrieval can be represented as
Syntax
SELECT [DISTINCT] column1, column2, ...
FROM tablename
WHERE condition;
Let's break it down:
1. SELECT Clause: This is where you specify the columns you want to retrieve. Use an
asterisk (*) to retrieve all columns.
2. FROM Clause: This specifies from which table or tables you want to retrieve the data.
3. WHERE Clause (optional): This allows you to filter the results based on a condition.
4. DISTINCT Clause (optional): is an optional keyword indicating that the answer should
not contain duplicates. Normally if we write the SQL without DISTINCT operator then it
does not eliminate the duplicates.
To provide a more holistic view, here are a few more SQL examples, keeping them as basic as
possible:
Syntax
SELECT * FROM tablename;
Syntax
SELECT column1, column2 FROM tablename;
Syntax
SELECT column1, column2 FROM tablename WHERE column1 = 'value';
Examples:
Finds Names that start or ends with "a“
Finds names that start with "a" and are at least 3 characters in length.
LIKE: The LIKE operator is used in a 'WHERE' clause to search for a specified pattern in a
column wild-card: There are two primary wildcards used in conjunction with the `LIKE`
operator percent sign (%) Represents zero, one, or multiple characters
underscore sign(_) Represents a single character
Here's a breakdown of how you can use these wildcards with the `LIKE` operator:
Example
SELECT FirstName
FROM Customers
WHERE FirstName LIKE 'Ma%';
2. Find values that end with a specific pattern:
Syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE '%pattern';
For instance, to find all products that end with "ing":
Example
SELECT ProductName
FROM Products
WHERE ProductName LIKE '%ing';
3. Find values that have a specific pattern anywhere:
Syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE '%pattern%';
Example, to find all books that have the word "life" anywhere in the title:
Example
SELECT BookTitle
FROM Books
WHERE BookTitle LIKE '%life%';
Using `_` Wildcard
1. Find values of a specific length where you only know some characters:
Syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE 'p_ttern';
For instance, if we're looking for a five-letter word where you know the first letter is "h" and the
third letter is "l", you could use:
Example
SELECT Word
FROM Words
WHERE Word LIKE 'h_l__';
Combining `%` and `_`
We can use both wildcards in the same pattern. For example, to find any value that starts with
"A", followed by two characters, and then "o":
Example
SELECT column_name
FROM table_name
WHERE column_name LIKE 'A__o%';
Keep in mind that the actual symbols used for wildcards might vary depending on the database
system. For example, in SQL Server, the wildcard for a single character is `[?]` instead of `_`.
Always refer to the specific documentation of the database you're working with.
***************************************************************************
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. Union All
3. Intersect
4. Minus/Except
1. Union
○ The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
○ In the union operation, all the number of data type and columns must be the same in both
the tables on which the UNION operation is being applied.
○ The union operation eliminates the duplicate rows from its result set.
Syntax
UNION
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
UNION ALL
UNION ALL
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
○ It is used to combine two SELECT statements. The Intersect operation returns the common
rows from both the SELECT statements.
○ In the Intersect operation, the number of data types and columns must be the same.
INTERSECT
Example:
INTERSECT
3 Jackson
4. Minus/Except
○ It combines the result of two SELECT statements. Except operator is used to display the
rows which are present in the first query but absent in the second query.
Syntax:
Except
Except
ID NAME
1 Jack
2 Harry
******************************************************************************
In independent nested queries, the execution order is from the innermost query to the outer query.
An outer query won't be executed until its inner query completes its execution. The outer query
uses the result of the inner query. Operators such as IN, NOT IN, ALL, and ANY are used to
write independent nested queries.
● The IN operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.
● The NOT IN operator checks if a column value in the outer query's result is not present in
the inner query's result. The final result will have rows that satisfy the NOT IN condition.
● The ALL operator compares a value of the outer query's result with all the values of the
inner query's result and returns the row if it matches all the values.
● The ANY operator compares a value of the outer query's result with all the inner query's
result values and returns the row if there is a match with any value.
Co-related Nested Queries
In co-related nested queries, the inner query uses the values from the outer query to execute the
inner query for every row processed by the outer-related
query. The
nested
co queries run
y slowl
because the inner queryuted
is exec
for every row of the outer query's result.
We can write a nested query in SQL by nesting a SELECT statement within another SELECT
statement. The outer SELECT statement uses the result of the inner SELECT
or statement f
processing.
We will use the Employees and Awards table below to understand independent
-related and co
nested queries. We will be using Oracle SQL syntax in our queries.
Let's create the Employees and Awards tables:
CREATE TABLE employee (id NUMBER PRIMARY KEY, name VARCHAR2(100) NOT
NULL, salary NUMBER NOT NULL, role VARCHAR2(100) NOT NULL );
CREATE TABLE
awards (id NUMBER PRIMARY KEY, employee_id
MBER NOT NUNULL,
award_date DATE NOT NULL);
Employees
1 Augustine Hammond
3 Cassy Delafoy
Example 3:
ALL
SELECT * FROM
employees
AND salary > ALL (SELECT salary FROM employees WHERE role = 'Manager');
Outpu
t
id name salary role
Explanatio
n
Example 4: ANY
AND salary > ANY (SELECT salary FROM employees WHERE role = 'Manager');
Output
Explanation
● The developer with id 3 earns (30000) more than the manager with id 2 (10000)
● The developer with id 5 earns (50000) more than the managers with id 2 (10000)
and 4
(40000)
WHERE salary > (SELECT AVG(salary) FROM employees emp2 WHERE [Link] =
[Link]);
Output
4 Garwood Saffen
40000 Manager
5 Faydra Beaves50000Developer
Explanatio
n
The manager with id 4 earns more than the average salary of all managers (25000), and the
developer with id 5 earns more than the average salary of all developers (30000).
y The inner quer
is executed for all rows fetched by the outer query. The inner query uses the role value
([Link])
of every outer query's row ([Link] = [Link]).
We can find the average salary of managers and developers using the below query:
Developer 30000
Manager 25000
************************************************************************
○ 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
○ The 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.
Syntax
1. COUNT(*)
2. or
3. COUNT([ALL|DISTINCT] expression)
Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
SELECT COUNT(*)
FROM
PRODUCT_MAST;
Output:
10
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
7
FROM PRODUCT_MAST;
Output:
3
FROM PRODUCT_MAST
GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3
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;
Output:
670
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE
QTY>3;
Output:
320
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
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()
or
AVG([ALL|DISTINCT] expression)
Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
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()
or
MAX([ALL|DISTINCT]
expression)
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
30
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()
or
MIN([ALL|DISTINCT]
expression)
Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
****************************************************************************
NULL values in SQL
In SQL there may be some records in a table that do not have values or data for every field and
those fields are termed as a NULL value.
NULL values could be possible because at the time of data entry information is not available. So
SQL supports a special value known as NULL which is used to represent the values of attributes
that may be unknown or not apply to a tuple. SQL places a NULL value in the field in the
absence of a user-defined value.
So, NULL values are those values in which there is no data value in the particular field in the
table.
SQL allows queries that check whether an attribute value is NULL. Rather than using = or to
compare an attribute value to NULL, SQL uses IS and IS NOT. This is because SQL considers
each NULL value as being distinct from every other NULL value, so equality comparison is not
appropriate.
Query:
VALUES
Output:
The IS NULL Operator
Suppose we find the Fname and Lname of the Employee having no Super_ssn then the query will
be:
Query:
Query:
Output:
Let’s suppose that we want to update SSN in the row where it is NULL.
Query:
UPDATE Employee
Integrity constraints in SQL are rules that help ensure the accuracy and reliability of data in the
database. They ensure that certain conditions are met when data is inserted, updated, or deleted.
While primary key, unique, and foreign key constraints are commonly discussed and used, SQL
allows for more complex constraints through the use of CHECK and custom triggers. Here are
some examples of complex integrity constraints:
● Ensuring a range: You might want a column to only have values within a certain range.
Example:
);
Example:
);
2. Comp
osite Primary and Foreign Keys
These are cases where the uniqueness or referential integrity constraint is applied over
more
than one
column.
Example
:
CREATE TABLE OrderDetails (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID),
Sometimes, instead of direct data manipulation on tables, using stored procedures can help
maintain more complex integrity constraints by wrapping logic inside the procedure. For
instance, you could have a procedure that checks several conditions before inserting a record.
4. Triggers:
● Triggers are blocks of code that are automatically executed in response to specific events,
such as insertions, updates, or deletions in a table.
● They can be used to enforce complex business rules or constraints that cannot be easily
defined using standard SQL constraints.
● For example, you might use a trigger to update the last_updated timestamp whenever a
row in a table is modified.
● A trigger is a procedure which is automatically invoked by the DBMS in response to
changes to the database, and is specified by the database administrator (DBA).
● A database with a set of associated triggers is generally called an active database.
Parts of trigger
A triggers description contains three parts, which are as follows − Event
Condition − A query that is run when the trigger is activated is called as a condition.
Action −A procedure which is executed when the trigger is activated and its condition is true.
Use of trigger
Triggers may be used for any of the following reasons −
To implement any complex business rule, that cannot be implemented using integrity constraints.
Triggers will be used to audit the process. For example, to keep track of changes made to a table.
Trigger is used to perform automatic action when another concerned action takes place.
Types of triggers
Statement level trigger − It is fired only once for DML statements irrespective of the number of
rows affected by the statement. Statement-level triggers are the default type of trigger.
Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be
fired before a command like INSERT, DELETE, or UPDATE is executed or after the command
is executed. Before triggers are automatically used to check the validity of data before the action
is performed. For instance, we can use before trigger to prevent deletion of rows if deletion
should not be allowed in a given case.
After-triggers − It is used after the triggering action is completed. For example, if the trigger is
associated with the INSERT command then it is fired after the row is inserted into the table.
To create a database trigger, we use the CREATE TRIGGER command. The details to be given at
the time of creating a trigger are as follows −
create table student (id int primary key, name varchar (20), age int, Phone bigint);
Values(3,'Geetha',19,9912199789);
create table student (id int primary key, name varchar (20),age int, Phone bigint);
Values(3,'Geetha',19,9912199789);
2 Rishi 18 9912199456
3 Geetha 19 9912199789
Active databases.
Active Database
The active database supports the preceding application by moving the reactive behavior from the
application into the DBMS. Active databases are thus able to monitor and react to specific
circumstances of relevance to an application. An active database system must provide a
knowledge model i.e. description mechanism and an execution model for supporting this
behavior. And for this we need triggers which have predefined action when situations occur.
An active Database is a database consisting of a set of triggers. These databases are very difficult
to be maintained because of the complexity that arises in understanding the effect of these
triggers. In such a database, DBMS initially verifies whether the particular trigger specified in
the statement that modifies the database) is activated or not, prior to executing the statement.
If the trigger is active then DBMS executes the condition part and then executes the action part
only if the specified condition is evaluated to true. It is possible to activate more than one trigger
within a single statement.
In such a situation, DBMS processes each of the triggers randomly. The execution of an active
part of a trigger may either activate other triggers or the same trigger that Initialized this action.
Such types of triggers that activate themselves are called ‘recursive triggers’. The DBMS
executes such chains of triggers in some predefined manner but it affects the concept of
understanding.
Features of Active Database
● It possesses all the concepts of a conventional database i.e. data modeling facilities, query
language, etc.
● It supports all the functions of a traditional database like data definition, data
manipulation, storage management, etc.
● It supports the definition and management of ECA rules.
● It detects event occurrences.
● It must be able to evaluate conditions and execute actions.
● It means that it has to implement rule execution.
Advantages of Active Database
******************************************************************************
Schema Refinement:
Redundancy means having multiple copies of the same data in the database. This problem arises
when a database is not normalized. Suppose a table of student details attributes is: student Id,
student name, college name, college rank, and course opted.
● Insertion anomaly
● Deletion anomaly
● Updation anomaly
Insertion Anomaly
If a student detail has to be inserted whose course is not being decided yet then insertion will not
be possible till the time course is decided for the student.
Deletion Anomaly
If the details of students in this table are deleted, then the details of the college will also get
deleted which should not occur by common sense. This anomaly happens when the deletion of a
data record results in losing some unrelated information that was stored as part of the record that
was deleted from a table.
It is not possible to delete some information without losing some other information in the table as
well.
Updation Anomaly
Suppose the rank of the college changes then changes will have to be all over the database which
will be time-consuming and computationally costly.
Student_ID Name Contact College Course Rank
Redundancy can lead to data inconsistencies, where the same data is stored in multiple locations,
and changes to one copy of the data are not reflected in the other copies. This can result in
incorrect data being used in decision-making processes and can lead to errors and inconsistencies
in the data.
Storage Requirements:
Redundancy increases the storage requirements of a database. If the same data is stored in
multiple places, more storage space is required to store the data. This can lead to higher costs and
slower data retrieval.
Update Anomalies:
Redundancy can lead to update anomalies, where changes made to one copy of the data are not
reflected in the other copies. This can result in incorrect data being used in decision-making
processes and can lead to errors and inconsistencies in the data.
Performance Issues:
Redundancy can also lead to performance issues, as the database must spend more time updating
multiple copies of the same data. This can lead to slower data retrieval and slower overall
performance of the database.
Security Issues:
Redundancy can also create security issues, as multiple copies of the same data can be accessed
and manipulated by unauthorized users. This can lead to data breaches and compromise the
confidentiality, integrity, and availability of the data.
Maintenance Complexity:
Redundancy can increase the complexity of database maintenance, as multiple copies of the same
data must be updated and synchronized. This can make it more difficult to troubleshoot and
resolve issues and can require more time and resources to maintain the database.
Data Duplication:
Redundancy can lead to data duplication, where the same data is stored in multiple locations,
resulting in wasted storage space and increased maintenance complexity. This can also lead to
confusion and errors, as different copies of the data may have different values or be out of sync.
Data Integrity:
Redundancy can also compromise data integrity, as changes made to one copy of the data may
not be reflected in the other copies. This can result in inconsistencies and errors and can make it
difficult to ensure that the data is accurate and up-to-date.
Usability Issues:
Redundancy can also create usability issues, as users may have difficulty accessing the correct
version of the data or may be confused by inconsistencies and errors. This can lead to frustration
and decreased productivity, as users spend more time searching for the correct data or correcting
errors.
Inconsistency:
If the same data is stored in multiple places within the database, there is a risk that updates or
changes made to one copy of the data may not be reflected in other copies, leading to
inconsistency and potentially incorrect results.
Difficulty in maintenance:
With redundant data, it becomes more difficult to maintain the accuracy and consistency of the
data. It requires more effort and resources to ensure that all copies of the data are updated
When data is redundant, there is a greater risk of errors in the database. For example, if the same
data is stored in multiple tables, there is a risk of inconsistencies between the tables.
Reduced flexibility:
Redundancy can reduce the flexibility of the database. For example, if a change needs to be made
to a particular piece of data, it may need to be updated in multiple places, which can be
timeconsuming and error-prone.
******************************************************************************
Decompositions
● When a relation in the relational model is not in appropriate normal form then the
decomposition of a relation is required.
● Decomposition is used to eliminate some of the problems of bad design like anomalies,
inconsistencies, and redundancy.
Types of Decomposition
1. Lossless Decomposition
2. Dependency Preservation
Lossless Decomposition
● If the information is not lost from the relation that is decomposed, then the decomposition
will be lossless.
● The lossless decomposition guarantees that the join of relations will result in the same
relation as it was decomposed.
● The relation is said to be lossless decomposition if natural joins of all the decomposition
give the original relation.
22 Denim 28 Mumbai
33 Alina 25 Delhi
46 Stephan 30 Bangalore
52 Katherine 36 Mumbai
60 Jack 40 Noida
DEPARTMENT table
827 22 Sales
438 33 Marketing
869 46 Finance
575 52 Production
678 60 Testing
Now, when these two relations are joined on the common column "EMP_ID", then the resultant
relation will look like:
Employee Department
Dependency Preserving
● If a relation R is decomposed into relation R1 and R2, then the dependencies of R either
must be a part of R1 or R2 or must be derivable from the combination of functional
dependencies of R1 and R2.
● For example, suppose there is a relation R (A, B, C, D) with a functional dependency set
(A->BC). The relational R is decomposed into R1(ABC) and R2(AD) which is
dependency preserving because FD A->BC is a part of relation R1(ABC).
***************************************************************************
Functional Dependency in DBMS
Relational database is a collection of data stored in rows and columns. Columns represent the
characteristic of data while each row in a table represents a set of related data, and every row in
the table has the same structure. The row is sometimes referred to as a tuple in DBMS.
Employee_Id,Employee_Name,Employee_Department,Salary
Employee Table
Employee_Id Employee_Name Employee_Department Salary
● It helps in maintaining the quality of data in the database, and the core concepts behind
database normalization are based on functional dependencies.
R (ABCD)
1. A → BCD
2. B → CD
● For the first functional dependency A → BCD, attributes B, C and D are functionally
dependent on attribute A.
Employee_IdName Age
1 Zayn 24
2 Phobe 34
3 Hikki 26
4 David 29
William Armstrong in 1974 suggested a few rules related to functional dependency. They are
called RAT rules.
● The process of Normalization starts with identifying the candidate keys in the relation.
Without functional dependency, it's impossible to find candidate keys and normalize the
database.
******************************************************************************
Normalization
A large database defined as a single relation may result in data duplication. This repetition of data
may result in:
○ It isn't easy to maintain and update data as it would involve searching many records in
relation.
So to handle these problems, we should analyze and decompose the relations with redundant data
into smaller, simpler, and well-structured relations that satisfy desirable properties.
Normalization is a process of decomposing the relations into relations with fewer attributes.
What is Normalization?
○ Normalization divides the larger table into smaller and links them using relationships.
○ The normal form is used to reduce redundancy from the database table.
Why do we need Normalization?
The main reason for normalizing the relations is removing these anomalies. Failure to eliminate
anomalies leads to data redundancy and can cause data integrity and other problems as the
database grows. Normalization consists of a series of guidelines that helps to guide you in
creating a good database structure.
○ Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new tuple into a
relationship due to lack of data.
○ Deletion Anomaly: The delete anomaly refers to the situation where the deletion of data
results in the unintended loss of some other important data.
○ Updation Anomaly: The update anomaly is when an update of a single data value requires
multiple rows of data to be updated.
The First Normal Form (1NF) is the first step in the normalization process of organizing data
within a relational database to reduce redundancy and improve data integrity. A relation (table) is
said to be in 1NF if it adheres to the following rules:
1. Atomic Values:
● Each attribute (column) contains only atomic (indivisible) values. This means values in
each column are indivisible units and there should be no sets, arrays, or lists.
● For example, a column called "Phone Numbers" shouldn't contain multiple phone
numbers for a single record. Instead, we'd typically break it into additional rows or
another related table.
2. Primary Key:
● Each table should have a primary key that uniquely identifies each row. This ensures that
each row in the table can be uniquely identified.
3. No Duplicate Rows:
● There shouldn’t be any duplicate rows in the table. This is often ensured by the use of the
primary key.
● The order in which data is stored doesn't matter in the context of 1NF (or any of the
normal forms). Relational databases don't guarantee an order for rows in a table unless
explicitly sorted.
● Columns should not contain multiple values of the same type. For example, a column
"Skills" shouldn't contain a list like "Java, Python, C++" for a single record. Instead,
these skills should be split across multiple rows or placed in a separate related table.
The table above is not in 1NF because the "Subjects" column contains multiple
values.
To transform it to 1NF:
Now, each combination of "Student_ID" and "Subject" is unique, and every attribute contains
only
atomic values, ensuring the table is in 1NF.
Achieving 1NF is a fundamental step in database normalization, laying the foundation for further
normalization processes to eliminate redundancy and ensure data integrity.
The Second Normal Form (2NF) is the next stage in the normalization process after the First
Normal Form (1NF). A relation is in 2NF if:
1. It is already in 1NF:
● This means the relation contains only atomic values, there are no duplicate rows, and it
has a primary key.
2. No Partial Dependencies:
● All non-key attributes (i.e., columns that aren't part of the primary key) should be
functionally dependent on the *entire* primary key. This rule is especially relevant for
tables with composite primary keys (i.e., primary keys made up of more than one
column).
● In simpler terms, no column should depend on just a part of the composite primary key.
Let's consider a table that keeps track of the courses that students are enrolled in, with the faculty
who teach those courses:
However, you'll notice that `Course_Name` and `Faculty` depend only on `Course_ID` and not
on the combination of `Student_ID` and `Course_ID`. This is a partial dependency.
It's worth noting that while 2NF does improve the structure of our database by reducing
redundancy and eliminating partial dependencies, it might not eliminate all anomalies or
redundancy. Further normalization forms (like 3NF and BCNF) address additional types of
dependencies and potential issues.
The Third Normal Form (3NF) is a further step in the normalization process after achieving
Second Normal Form (2NF). A relation is considered to be in 3NF if:
1. It is already in 2NF:
● This means the relation has no partial dependencies of non-key attributes on the primary
key.
2. No Transitive Dependencies:
● All non-key attributes are functionally dependent only on the primary key and not on any
other non-key attributes. If there is a dependency of one non-key attribute on another
nonkey attribute, it is called a transitive dependency, and such a dependency violates
3NF.
● Simply put, in 3NF, non-key attributes should not depend on other non-key attributes;
they should only depend on the primary key.
In the table above, `Product_ID` is the primary key. We can see that `Vendor_Address` depends
on `Vendor_Name` rather than `Product_ID`, which represents a transitive dependency.
This normalization eliminates the transitive dependency and reduces redundancy. If we need to
change a vendor's address, we now only have to make the change in one place in the `Vendor`
table.
To further refine the database structure, we might proceed to other normalization forms like
BCNF, but 3NF is often sufficient for many practical applications and strikes a good balance
between minimizing redundancy and maintaining a manageable schema.
Boyce-Codd Normal Form (BCNF) is an advanced step in the normalization process, and it's a
stronger version of the Third Normal Form (3NF). In fact, every relation in BCNF is also in 3NF,
but the converse isn't necessarily true. BCNF was introduced to handle certain anomalies that
3NF does not deal with.
1. It is already in 3NF.
X→Y, X is a superkey. This essentially means that the only determinants in the relation are
superkeys.
Here, "non-trivial" means that Y is not a subset of X, and a "superkey" is a set of attributes that
functionally determines all other attributes in the relation.
Consider a university scenario where professors supervise student theses in various topics. Now,
let's assume each professor can only supervise one topic, but multiple professors can supervise
the same topic.
Here:
Now, observe that {Professor} is not a superkey (because the primary key is a combination of
Student and Professor), but it determines another attribute in the table (Topic). This violates the
definition of BCNF.
To bring this table into BCNF, we can decompose it into two tables:
This decomposition eliminates the partial dependency and ensures that the only determinants are
superkeys, making the structure adhere to BCNF.
In practice, BCNF is a highly normalized form, and while it can minimize redundancy, it can also
increase the complexity of the database design. Designers often have to make trade-offs between
achieving higher normal forms and maintaining simplicity, depending on the specific use case
and requirements of the system.
The Fourth Normal Form (4NF) is an advanced level in the normalization process, aiming to
handle certain types of anomalies which aren't addressed by the Third Normal Form (3NF).
Specifically, 4NF addresses multi-valued dependencies.
1. It is already in 3NF.
To clarify, consider a relation R with attributes X, Y, and Z. We say that there is a multi-valued
dependency from X to Y, denoted
X Y, if for a single value of X, there are multiple values of Y associated with it, independent of
Z.
Let's illustrate 4NF with a scenario involving students, their hobbies, and the courses they've
taken:
In the table:
● For student `S1`, there are two hobbies (`Painting` and `Hiking`) and two courses (`Math`
and `Physics`), resulting in a combination of every hobby with every course.
● This design suggests a multi-valued dependency between `Student_ID` and `Hobby`, and
also between `Student_ID` and `Course`.
To bring the table to 4NF, we can decompose it into two separate tables:
With this separation:
There are no more multi-valued dependencies. This setup not only reduces redundancy but also
prevents the possibility of certain types of inconsistencies and anomalies in the data.
For most practical applications, normalization up to 3NF or BCNF is often adequate. However,
when specific types of redundancy or data anomalies are a concern, proceeding to 4NF or even
5NF can be beneficial.
The Fifth Normal Form (5NF), also known as Project-Join Normal Form (PJNF), is a further
step in the normalization process. It aims to address redundancy arising from certain types of join
dependencies that aren't covered by earlier normal forms.
2. Every non-trivial join dependency in the relation is implied by the candidate keys.
1. Every part supplied for a project is supplied by all suppliers supplying any part for that
project.
2. Every part supplied by a supplier is supplied by that supplier for all projects to which that
supplier supplies any part.
Given the above constraints, the following join dependencies exist on the table: