S4 1. Create Three Tables Named 'Orders', 'Customers', and 'Products' With The Following Structures
S4 1. Create Three Tables Named 'Orders', 'Customers', and 'Products' With The Following Structures
1. Create three tables named `orders`, `customers`, and `products` with the
following structures:
- `customers` table:
- `customer_id` (Primary Key)
- `customer_name`
- `email`
- `products` table:
- `product_id` (Primary Key)
- `product_name`
- `unit_price`
- `orders` table:
- `order_id` (Primary Key)
- `customer_id` (Foreign Key referencing `customers` table)
- `product_id` (Foreign Key referencing `products` table)
- `quantity`
- `order_date`
-- Create customers table
ANS
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
2. Add a new customer named 'John Doe' with email '[email protected]' and 3
more to the `customers` table.
ANS
-- Insert new customers into the customers table
INSERT INTO customers (customer_name, email) VALUES
('John Doe', '[email protected]'),
('Jane Smith', '[email protected]'),
('Alice Johnson', '[email protected]'),
('Bob Brown', '[email protected]');
5. List the total sales (quantity * unit_price) for each product. Include the
product name and the total sales amount, sorted in descending order of sales
amount.
ANS
SELECT
p.product_name,
SUM(o.quantity * p.unit_price) AS total_sales
FROM
products p
JOIN
orders o
ON
p.product_id = o.product_id
GROUP BY
p.product_name
ORDER BY
total_sales DESC;
7. List the top 3 customers with the highest total spending. Include the customer
name and their total spending amount, sorted in descending order of spending
amount.
ANS
UPDATE products
SET unit_price = 600.00
WHERE product_name = 'Tablet';
9. Delete the order record with `order_id` 3 from the `orders` table.
Ans
DELETE FROM orders
WHERE order_id = 3;
10. List all orders along with the customer name, product name, quantity, and
total price (quantity * unit_price). Sort the orders by order date in ascending
order.
Ans
SELECT u.user_name, p.product_name, o.quantity,
(o.quantity * p.unit_price) AS total_price, o.order_date
FROM orders o
JOIN registered_users u ON o.user_id = u.user_id
JOIN products p ON o.product_id = p.product_id
ORDER BY o.order_date ASC;
11. List the names of customers and the names of the products they ordered, but
only include customers who have placed at least one order.
Ans
12. List all products along with the names of customers who ordered them,
including products that have not been ordered and customers who have not
placed any orders.
Ans
SELECT p.product_name, u.user_name
FROM products p
LEFT JOIN orders o ON p.product_id = o.product_id
LEFT JOIN registered_users u ON o.user_id = u.user_id
ORDER BY p.product_name;