Database Normalization
Database normalization is a process that involves designing a database schema to minimize redundancy and dependency issues. It helps in achieving data consistency and improving database performance.
Importance of Database Normalization
Database normalization provides several benefits:
Data Consistency: By eliminating redundant data, normalization ensures that each piece of data is stored in only one place, reducing the risk of inconsistencies and anomalies.
Efficient Storage: Normalized databases are more efficient in terms of storage as redundant data is eliminated. This leads to reduced storage requirements and improved database performance.
Simplified Updates: With a normalized database, updates to data can be made in one place, improving maintainability and reducing the risk of data inconsistency.
Reduced Anomalies: Normalization eliminates anomalies such as insertion, update, and deletion anomalies that can occur when data is not properly organized.
Forms of Database Normalization
Database normalization is divided into several forms, known as normal forms:
First Normal Form (1NF): Ensures that each column in a table contains only atomic values (values cannot be divided further).
Second Normal Form (2NF): Builds upon 1NF and ensures that all non-key columns depend on the entire primary key.
Third Normal Form (3NF): Builds upon 2NF and ensures that there is no transitive dependency between non-key columns.
Boyce-Codd Normal Form (BCNF): Builds upon 3NF and ensures that every determinant is a candidate key.
Example
Let's consider an example to understand database normalization better. Suppose we have a database table called 'Customers' with the following columns:
- CustomerID
- CustomerName
- Address
- City
- Country
This table violates the 2NF because 'Address', 'City', and 'Country' depend on the entire primary key 'CustomerID'. To normalize the table, we can split it into two tables:
- 'Customers' table with 'CustomerID' and 'CustomerName'
- 'Addresses' table with 'CustomerID', 'Address', 'City', and 'Country'
By doing this, we have eliminated the redundancy and achieved 2NF.
1// Example code snippet
2
3// Create a table
4CREATE TABLE Customers (
5 CustomerID INT PRIMARY KEY,
6 CustomerName VARCHAR(255),
7 Address VARCHAR(255),
8 City VARCHAR(255),
9 Country VARCHAR(255)
10);
11
12// Insert data
13INSERT INTO Customers (CustomerID, CustomerName, Address, City, Country)
14VALUES (1, 'John Doe', '123 Main St', 'New York', 'USA'),
15 (2, 'Jane Smith', '456 Elm St', 'Los Angeles', 'USA');
16
17// Select data
18SELECT * FROM Customers;
xxxxxxxxxx
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}