0% found this document useful (0 votes)
15 views

Project 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Project 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Project-3

Online Book Store Management:

1. Utilize SQL’s CREATE TABLE statements to define the structure of the


database tables required for storing data. Specify appropriate data types,
primary keys, and foreign key relationships to ensure data integrity and
consistency.

Creating table for Users:

Output:

Creating table for books:

Table format:
Creating table for Shopping Carts:

Output:

Creating table for CartItems:

Output:
Creating table for Orders:

Columns:

Creating table for OrderItems:


Output:

2. Implement SQL triggers to automate data validation and maintain data


consistency. Create triggers that fire before or after specific database events,
such as inserting or updating records, to enforce business rules or perform
calculations.

Prevent Negative Quantities in CartItems and OrderItems

Output:
Trigger function to prevent negative quantities in OrderItems:

Output:

Trigger to call the function before update:

Output:

Update Order Total Amount on Insert/Update/Delete of

OrderItems:
Output:

Ensure Unique Username in Users Table:


3. Use SQL functions to encapsulate complex business logic or

calculations. Define custom functions to perform tasks like data

transformations, unit conversions, or statistical computations.

Utilize these functions within SQL queries to simplify code and

promote reusability.

a. Convert Price from One Currency to Another

Output:
b. Calculate Average Price of Books by an Author

Output:

c. Get Top N Selling Books


Output:

d. Get User Order History

Output:
4. Apply normalization techniques to optimize the database design and
minimize data redundancy. Identify functional dependencies and normalize
the tables to achieve higher normal forms (e.g., 1NF, 2NF, 3NF). Use
SQL's ALTER TABLE statements to modify the table structure as needed.

Step-by-Step Normalization Process

1NF (First Normal Form)

Ensure that the table has atomic values and each record is unique. This is
already achieved in the given schema.

2NF (Second Normal Form)

Ensure that all non-key attributes are fully functionally dependent on the
primary key. Our current tables appear to be in 2NF since they have a single
primary key and no partial dependencies.

3NF (Third Normal Form)

Ensure that all non-key attributes are not transitively dependent on the
primary key. Let's review each table to ensure it adheres to 3NF.

Current Schema Review

 Users Table: This table is normalized with no partial or transitive


dependencies.
 Books Table: This table is normalized with no partial or transitive
dependencies.
 ShoppingCarts Table: This table is normalized with no partial or transitive
dependencies.
 CartItems Table: This table is normalized with no partial or transitive
dependencies.
 Orders Table: This table has attributes related to the order itself and is
normalized.
 OrderItems Table: This table is normalized with no partial or transitive
dependencies.

Based on the current schema, it appears that all tables are already normalized
up to 3NF.

So, all the created tables are in normalization up to 3NF.

5. Create entity-relationship diagrams (ERDs) to visually represent the


database schema and the relationships between tables. Use ERD tools to
design and communicate the database structure effectively.

ERD Description

 Users Table:
o Attributes: user_id, username, email, password, is_admin
o Primary Key: user_id
 Books Table:
o Attributes: book_id, title, author, price
o Primary Key: book_id
 ShoppingCarts Table:
o Attributes: cart_id, user_id
o Primary Key: cart_id
o Foreign Key: user_id references Users(user_id)
 CartItems Table:
o Attributes: cart_item_id, cart_id, book_id, quantity
o Primary Key: cart_item_id
o Foreign Keys: cart_id references ShoppingCarts(cart_id), book_id
references Books(book_id)
 Orders Table:
o Attributes: order_id, user_id, order_date, shipping_address,
billing_address, total_amount
o Primary Key: order_id
o Foreign Key: user_id references Users(user_id)
 OrderItems Table:
o Attributes: order_item_id, order_id, book_id, quantity, price
o Primary Key: order_item_id
o Foreign Keys: order_id references Orders(order_id), book_id references
Books(book_id)

6. Implement referential integrity constraints using SQL's foreign key


constraints. Define foreign key relationships between tables to ensure data
consistency and prevent orphaned records. Use ON DELETE and ON UPDATE
clauses to specify the behavior when referenced records are modified or
deleted.

To implement referential integrity constraints using SQL's foreign key


constraints, we need to define the foreign key relationships between the
tables and specify the actions to take on delete or update events. This helps
maintain data consistency and prevent orphaned records. Here’s how to
implement these constraints with ON DELETE and ON UPDATE clauses for the
provided database schema:

Here is how implementing referential integrity constraints:

Output:
Output:

7. Utilize SQL’s data import and export functionality to migrate data between
different databases or systems. Use SQL statements like COPY or IMPORT to
load data from external files, and employ EXPORT or COPY TO statements to
extract data from the database.

Import Data from a CSV File

Suppose you have a CSV file named books.csv with the following content:

title,author,price

"The Great Gatsby","F. Scott Fitzgerald",10.99

"1984","George Orwell",8.99

"To Kill a Mockingbird","Harper Lee",12.99

"The Catcher in the Rye","J.D. Salinger",7.99

Query:

Export Data to a CSV File:


8. Apply SQL's GROUP BY and HAVING clauses to perform

advanced data aggregation and filtering. Use GROUP BY to group

rows based on specific columns and apply aggregate functions to

calculate summary statistics. Utilize HAVING to filter the grouped

results based on additional conditions.

Grouping and Aggregating Orders

Task: Find the total amount spent by each user on orders.

Using HAVING to Filter Aggregated Results

Task: Find users who have spent more than $20 on their orders
Grouping by Book and Counting Sales

Task: Find out how many times each book has been sold.

Grouping and Aggregating with Multiple Columns

Task: Find out the total quantity of books sold and the total revenue
generated by each book.
Combining GROUP BY with JOIN

Task: Find out the total revenue generated by each book, along with the book
title and author.

9. Handle missing data effectively by using SQL's NULL value and


related functions. Use COALESCE or CASE statements to provide default
values for missing data, and employ IS NULL or IS NOT NULL conditions to
filter records based on the presence or absence of values.

Using COALESCE to Provide Default Values

1. Display a default email if it's missing:


2. Set a default total amount if it's missing:

Using CASE Statements for Conditional Logic

1. Mark users with missing emails:


2. Provide a default value for missing order amounts and calculate total:

11. Implement stored procedures to encapsulate complex database


operations and business logic. Use SQL’s CREATE PROCEDURE statement to
define reusable code blocks that can be invoked by application programs or
other stored procedures.

Create the Stored Procedure

We'll create a stored procedure named place_order that accepts user ID, book
ID, quantity, shipping address, and billing address as parameters. The
procedure will perform the following steps:

1. Check if the requested quantity is available.


2. Update the book quantity.

3. Create a new order.

4. Insert the order items.

5. Calculate the total amount and update the order.

Output:

You might also like