Data Modeling Case Studies in PostgreSQL
1. Introduction
Data modeling is the process of creating a data model for the data to be stored in a database. In this lesson, we will explore two case studies focusing on data modeling using PostgreSQL.
2. Case Study 1: E-commerce Database Design
This case study focuses on the design of a database for an e-commerce platform. The objective is to model customer data, orders, and products.
Key Entities
- Customers
- Products
- Orders
- Order Items
Entity Relationship Diagram (ERD)
graph LR;
A[Customers] -->|places| B[Orders];
B -->|contains| C[Order Items];
C -->|references| D[Products];
SQL Schema Creation
Here is how to create the tables for the e-commerce model:
CREATE TABLE Customers (
CustomerID SERIAL PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100) UNIQUE
);
CREATE TABLE Products (
ProductID SERIAL PRIMARY KEY,
Name VARCHAR(100),
Price NUMERIC(10, 2)
);
CREATE TABLE Orders (
OrderID SERIAL PRIMARY KEY,
CustomerID INT REFERENCES Customers(CustomerID),
OrderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE OrderItems (
OrderItemID SERIAL PRIMARY KEY,
OrderID INT REFERENCES Orders(OrderID),
ProductID INT REFERENCES Products(ProductID),
Quantity INT
);
3. Case Study 2: Library Management System
This case study involves designing a database for a library management system.
Key Entities
- Members
- Books
- Loans
- Authors
Entity Relationship Diagram (ERD)
graph LR;
E[Members] -->|borrows| F[Loans];
F -->|includes| G[Books];
G -->|written by| H[Authors];
SQL Schema Creation
Here is how to create the tables for the library management system:
CREATE TABLE Members (
MemberID SERIAL PRIMARY KEY,
Name VARCHAR(100),
MembershipDate DATE
);
CREATE TABLE Authors (
AuthorID SERIAL PRIMARY KEY,
Name VARCHAR(100)
);
CREATE TABLE Books (
BookID SERIAL PRIMARY KEY,
Title VARCHAR(100),
AuthorID INT REFERENCES Authors(AuthorID)
);
CREATE TABLE Loans (
LoanID SERIAL PRIMARY KEY,
MemberID INT REFERENCES Members(MemberID),
BookID INT REFERENCES Books(BookID),
LoanDate DATE,
ReturnDate DATE
);
4. Common Practices in Data Modeling
When designing a database, consider the following best practices:
- Normalize your data to reduce redundancy.
- Use primary and foreign keys effectively.
- Document your design thoroughly.
- Consider indexing frequently queried fields.
5. FAQ
What is data modeling?
Data modeling is the process of creating a visual representation of a system or application’s data. It defines how data is connected, stored, and accessed.
Why is normalization important?
Normalization reduces data redundancy and improves data integrity, ensuring that data remains consistent and accurate over time.
What are primary and foreign keys?
A primary key is a unique identifier for a record in a table, while a foreign key is a field that links two tables together, establishing a relationship.