S5
S5
1. Create two tables named products and categories with the following structures:
categories table:
o category_id (Primary Key, Auto increment)
o category_name
products table:
o product_id (Primary Key, Auto increment)
o product_name
o category_id (Foreign Key referencing categories table)
Ans
3. Insert 12 records into the products table with appropriate category_id values from the
categories table. Start product_id from 1.
Ans
INSERT INTO products (product_name, category_id)
VALUES
('Laptop', 1),
('Smartphone', 1),
('Television', 1),
('Headphones', 1),
('Sofa', 2),
('Chair', 2),
('Table', 2),
('Cabinet', 2),
('Shirt', 3),
('Jeans', 3),
('Jacket', 3),
('Sweater', 3),
('Rice', 4),
('Vegetables', 4),
('Fruits', 4),
('Cereal', 4);
4. Update the product_name of the product with product_id 6 to 'Wireless Speaker'.
Ans
UPDATE products
SET product_name = 'Wireless Speaker'
WHERE product_id = 6;
5. List all category_name values along with the count of products in each category.
Display the total products and sort the result in ascending order of category name.
Ans
SELECT c.category_name, COUNT(p.product_id) AS total_products
FROM categories c
LEFT JOIN products p ON c.category_id = p.category_id
GROUP BY c.category_name
ORDER BY c.category_name ASC;
6. List all products along with their category names sorted alphabetically by product
name.
Ans
SELECT p.product_name, c.category_name
FROM products p
JOIN categories c ON p.category_id = c.category_id
ORDER BY p.product_name ASC;
7. Delete the product record with product_id 9 from the products table.
Ans
DELETE FROM products
WHERE product_id = 9;
8. Alter the products table to add a new column named price of type DECIMAL(8,2).
Ans
ALTER TABLE products
ADD COLUMN price DECIMAL(8,2);
9. Update the price column for all products in the 'Electronics' category to 150.00.
Ans
UPDATE products p
JOIN categories c ON p.category_id = c.category_id
SET p.price = 150.00
WHERE c.category_name = 'Electronics';
11. List the names of all products along with their category names, but only include
products that are assigned to a category.
Ans
SELECT p.product_name, c.category_name
FROM products p
JOIN categories c ON p.category_id = c.category_id;
12. List all categories along with the names of the products in each category, including
categories that have no product
Ans
SELECT c.category_name, p.product_name
FROM categories c
LEFT JOIN products p ON c.category_id = p.category_id
ORDER BY c.category_name, p.product_name;
a