Database Concepts & Advanced SQL
Database Normalization
Normalization is the process of organizing data to reduce redundancy and improve consistency.Benefits
- Reduces duplicate data
- Improves data consistency
- Saves storage space
- Simplifies updates
- Improves database maintenance
Normal Forms
First Normal Form (1NF)
A table is in 1NF if:- Each column contains a single (atomic) value.
- No repeating groups.
- Each row is unique.
In 1NF
Practice
Why is the first table not in 1NF?Solution
Solution
The
Subjects column contains multiple values. Every column should contain only a single value.Second Normal Form (2NF)
A table is in 2NF if:- It is already in 1NF.
- Every non-key column depends on the entire primary key.
Practice
When is 2NF mainly applicable?Solution
Solution
When a table has a composite primary key.
Third Normal Form (3NF)
A table is in 3NF if:- It is already in 2NF.
- No non-key column depends on another non-key column.
Example
Instead of storing the manager with every employee:
Store manager details in the Department table.
Practice
What problem does 3NF solve?Solution
Solution
It removes transitive dependencies, where one non-key column depends on another non-key column.
ACID Properties
ACID properties ensure database transactions are reliable and consistent.Example
During a money transfer:- Debit ₹500
- Credit ₹500
Practice
Which ACID property ensures committed data is permanently saved?Solution
Solution
Durability
Window Functions
Window functions perform calculations across related rows without grouping them into a single row. UnlikeGROUP BY, every row remains in the result.
ROW_NUMBER()
Assigns a unique sequence number.RANK()
Assigns the same rank to equal values and skips the next rank. Example:DENSE_RANK()
Assigns the same rank to equal values but does not skip ranks. Example:PARTITION BY
Divides rows into groups before applying a window function.GROUP BY vs Window Functions
Practice
What is the main advantage of a window function overGROUP BY?
Solution
Solution
A window function performs calculations while keeping every row in the result, whereas
GROUP BY combines rows into a single row for each group.Summary
This chapter introduced:- Database Normalization
- 1NF
- 2NF
- 3NF
- ACID Properties
- Window Functions
ROW_NUMBER()RANK()DENSE_RANK()PARTITION BY
- Difference between
GROUP BYand Window Functions