Certainly! Let's provide examples for each of the concepts you mentioned using a hypothetical e-commerce database scenario.
1. Normalization and Denormalization:
Normalization:
-- Normalized tables
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(255),
-- Other customer-related fields
);
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
-- Other order-related fields
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
-- This is a normalized structure where customer information is in a separate table.
Denormalization:
-- Denormalized table
CREATE TABLE DenormalizedOrders (
order_id INT PRIMARY KEY,
customer_name VARCHAR(255),
order_date DATE,
-- Other denormalized order-related fields
);
-- In this denormalized structure, customer information is duplicated within the Orders table for better query performance.
2. Query Optimization:
-- Example of query optimization using indexing
CREATE INDEX idx_orders_customer_id ON Orders(customer_id);
-- This index improves the performance of queries that involve filtering or sorting by the customer_id column.
3. Transaction Management:
-- Example of transaction management
BEGIN TRANSACTION;
-- Update the order status
UPDATE Orders SET status = 'Shipped' WHERE order_id = 123;
-- Deduct the product quantity from inventory
UPDATE Products SET quantity = quantity - 1 WHERE product_id = 456;
-- If both updates succeed, commit the transaction
COMMIT;
-- If any update fails, roll back the entire transaction
ROLLBACK;
4. Database Security:
-- Example of role-based access control
CREATE ROLE Customer;
CREATE ROLE Admin;
-- Grant privileges to roles
GRANT SELECT, INSERT, UPDATE, DELETE ON Orders TO Customer;
GRANT ALL PRIVILEGES ON Orders TO Admin;
-- Assign roles to users
CREATE USER alice WITH PASSWORD 'password';
GRANT Customer TO alice;
5. Stored Procedures and Triggers:
-- Example of a stored procedure
CREATE PROCEDURE UpdateOrderStatus(IN order_id INT, IN new_status VARCHAR(50))
BEGIN
UPDATE Orders SET status = new_status WHERE order_id = order_id;
END;
-- Example of a trigger
CREATE TRIGGER Before_Order_Insert
BEFORE INSERT ON Orders
FOR EACH ROW
SET NEW.order_date = NOW();
-- The trigger automatically sets the order_date to the current timestamp before inserting a new order.
These examples showcase how these concepts are implemented in SQL for a simplified e-commerce database. Keep in mind that the specifics may vary based on the actual database management system you are using (e.g., MySQL, PostgreSQL, etc.).
Top comments (0)