This tutorial provides 100 examples combining Python (lists, dictionaries, tuples, strings, functions,
loops, conditionals, classes, inheritance, encapsulation) and MySQL topics (Introduction, Database Creation,
Create Table, Insert Data, Describe/Alter/Drop Table, Select Records, Where/Like/Order By, Delete Records,
Update Records, Limit/Hint/Auto/Regex/Dedupe, Commit/Rollback, Join Tables, Aggregate Functions, Subqueries,
Stored Procedures, Indexes, Views, Triggers, Dates/Times, DISTINCT) for real-time applications like
e-commerce, user management, inventory systems, and analytics. Examples use
mysql-connector-python in a standard Python environment with a MySQL server on
localhost and a database my_db with tables users,
orders, products, categories, cart, and
user_logs. Replace placeholder credentials (host, user, password) with your actual MySQL
settings. Code blocks and outputs span 100% width of the content area (70% on desktop, 100% on mobile).
Prerequisites: Ensure MySQL server is running, my_db database exists, and
tables are set up as described. Install mysql-connector-python
(pip install mysql-connector-python) and replace your_password. Create stored
procedures, triggers, and views as shown in the setup instructions.
Defines a function to connect to MySQL for an e-commerce platform setup.
Connected to MySQL database
Creates a database for an e-commerce application.
E-commerce database created
Uses a DatabaseManager class to create a cart table for an e-commerce shopping
cart.
Cart table created
Uses a Product class with string validation to insert a product.
Product Headphones added
Alters the products table to add a discount column for a promotional campaign.
Discount column added to products
Fetches user details into a dictionary for a user profile page.
User profile for ID 4:
{'name': 'Diana Smith', 'email': 'diana@example.com'}
Searches products using LIKE with string processing for a search bar.
Search results for 'phone':
('Smartphone', 699.99)
Deletes cart items older than 30 days for cleanup in an e-commerce system.
Deleted 0 old cart items
Uses a ProductManager class to update product discounts for a sale event.
Updated discount for product ID 1
Fetches a limited number of products into a list for a featured products section.
Top 2 products:
('Smartphone', 699.99)
('Headphones', 99.99)
Uses a Checkout class to place an order with a transaction for a checkout system.
Order placed for user 4: Laptop
Fetches user orders using INNER JOIN into a list for an order history page.
Orders for user 4:
('Diana Smith', 'Tablet')
('Diana Smith', 'Monitor')
Calculates total sales per category using SUM and GROUP BY into a dictionary for an
analytics dashboard.
Sales by category: Tech: $799.98
Identifies users with orders over $500 using a subquery, stored in a tuple for a loyalty program.
High-value customers: Diana Smith
Uses a Checkout class to call a stored procedure for order placement.
Order placed for user 4: Phone
Creates an index on users.email to optimize email-based queries.
Index created on users.email
Queries the user_orders view into a list for an order summary report.
User orders from view:
('Diana Smith', 'Tablet')
('Diana Smith', 'Monitor')
('Eve', None)
('Grace', None)
Uses an InventoryManager class to insert an order, triggering a stock update.
Order added for Tablet, stock updated via trigger
Fetches orders from the last 30 days into a tuple for an order tracking system.
Recent orders: (4, 'Tablet', '2025-07-01 10:00:00') (4, 'Monitor', '2025-07-10 14:30:00')
Fetches unique ordered products using DISTINCT into a tuple for a recommendation system.
Unique ordered products: Tablet Monitor
Uses a User class with email validation to register a user.
User John Doe registered
Uses a PremiumUser class inheriting from User to check premium status.
Premium status for Diana Smith: Premium
Fetches user cart items with product details using INNER JOIN into a dictionary for a checkout
page.
Cart for user 4: Smartphone: 2 units, $699.99
Uses an OrderManager class to count orders per user for an analytics report.
User order counts:
('Diana Smith', 2)
('Eve', 0)
('Grace', 0)
Calls a stored procedure to add a user and order for a streamlined checkout.
Added user Jane Doe and order for Phone
Searches products using regex for advanced filtering in a product catalog.
Products matching regex 'phone|tablet':
('Smartphone', 699.99)
('Tablet', 499.99)
Creates a view for product summaries using a DatabaseManager class.
Product summary view created
Updates a user’s email, triggering a log entry in user_logs.
User email updated, log entry created
Fetches user order history within a date range using a join for a reporting system.
Order history since 2025-07-01
('Diana Smith', 'Tablet', '2025-07-01 10:00:00')
('Diana Smith', 'Monitor', '2025-07-10 14:30:00')
Removes duplicate emails from the users table using a loop and subquery.
Removed 0 duplicate emails
Uses a Cart class to add an item to the cart, storing details in a dictionary.
Added 1 of product ID 2 to cart
Fetches products with their categories using a join, stored in a list for a catalog page.
Product categories:
('Smartphone', 'Tech')
('Headphones', 'Tech')
Calculates the average order value using AVG for a financial report.
Average order value: $399.99
Fetches products with stock using a subquery, stored in a list for inventory management.
Products in stock: Smartphone Headphones
Uses a class to call a stored procedure to update product stock.
Updated stock for product ID 1
Fetches products table structure into a dictionary for admin panel.
Structure of products:
{'id': 'int', 'name': 'varchar(100)', 'price': 'decimal(10,2)', 'stock': 'int', 'category_id': 'int', 'discount': 'decimal(5,2)'}
Deletes a user for account deactivation.
Deleted user ID 5
Sorts products by price for a product listing page.
Sorted products by price:
('Smartphone', 699.99)
('Tablet', 499.99)
('Headphones', 99.99)
Updates cart quantity with a transaction for a checkout system.
Updated cart for user 4
Fetches discounted products from a view into a dictionary for a sale page.
Discounted products: Headphones: $99.99, Tech
Fetches MySQL version using a string for system diagnostics.
MySQL version: 8.0.27
Creates a user_logs table using a class for audit logging.
User logs table created
Inserts a new category for product organization.
Category Electronics added
Drops a temporary table for cleanup in an admin panel.
Table temp_table dropped
Fetches all products into a list for a product catalog.
All products:
('Smartphone', 699.99)
('Tablet', 499.99)
('Headphones', 99.99)
Filters products by price range for a product listing page.
Products between $100 and $600:
('Tablet', 499.99)
Deletes an order for order cancellation.
Deleted order ID 1
Updates a user’s name using a class for profile management.
Updated name for user ID 4
Fetches top customers by order count into a list for a loyalty report.
Top 2 customers by orders:
('Diana Smith', 2)
('Eve', 0)
Fetches products not ordered using a subquery for inventory analysis.
Products not ordered: Smartphone Headphones
Creates an orders table using a class for database setup.
Orders table created
Inserts an order with a timestamp using a class for an e-commerce checkout system.
Order added for user 4 on 2025-07-15 12:00:00
Fetches user activity logs within a date range using a loop for an audit system.
User activity logs: User 4: Updated at 2025-07-10 14:00:00
Uses encapsulation in a User class to fetch and protect user data for a profile page.
User name: Diana Jones
Checks product stock using conditionals for inventory alerts.
Smartphone has sufficient stock: 50 units
Inserts multiple products using a loop and list for bulk inventory updates.
Inserted 2 products
Updates product prices with a discount using a loop for a promotional campaign.
Applied 10% discount to category 1
Fetches order summaries with user and product details into a dictionary for a dashboard.
Order summary: Tablet: Diana Smith, $499.99 Monitor: Diana Smith, $299.99
Calculates total stock value using SUM for inventory reporting.
Total stock value: $42999.50
Fetches users with no orders using a subquery, stored in a tuple for marketing analysis.
Users with no orders: Eve Grace
Creates an index on order_date to optimize date-based queries.
Index created on orders.order_date
Queries a view for cart items into a list for a shopping cart page.
Cart items from view:
('Smartphone', 699.99)
Inserts a user, triggering a log entry in user_logs.
User inserted, log entry created
Fetches recent user activity into a dictionary for a monitoring dashboard.
Recent user activity: User 4: Updated at 2025-07-10 14:00:00
Fetches unique categories ordered using DISTINCT into a tuple for analytics.
Unique ordered categories: Tech
Checks order status based on total using conditionals for an order tracking system.
Order 1 status: Standard
Updates user details with a transaction using a class for profile management.
Updated email for user 4
Searches products using regex for advanced filtering in a product catalog.
Products matching '^[A-M].*':
('Headphones', 99.99)
('Laptop', 999.99)
('Mouse', 29.99)
Calculates total sales within a date range for a financial report.
Total sales from 2025-07-01 to 2025-07-31: $799.98
Creates a view for cart details using a class for a shopping cart system.
Cart details view created
Calls a stored procedure to count user orders for analytics.
Order count for user 4: 2
Deletes logs older than 90 days for database cleanup.
Deleted 0 old logs
Fetches product stock with category details into a list for inventory management.
Product stock:
('Smartphone', 50, 'Tech')
('Headphones', 100, 'Tech')
('Tablet', 30, 'Tech')
Uses encapsulation to fetch and protect order data for an order details page.
Order product: Tablet
Fetches top products by total sales into a list for a sales report.
Top 2 products by sales:
('Tablet', 499.99)
('Monitor', 299.99)
Fetches user orders using a subquery into a dictionary for an order history page.
User orders count: Diana Smith: 2 orders Eve: 0 orders Grace: 0 orders
Updates product stock, triggering a log entry in user_logs.
Product stock updated, log entry created
Counts orders by category using a join and COUNT for analytics.
Orders by category: Tech: 2 orders
Creates an index on users.name using a class for query optimization.
Index created on users.name
Fetches recent orders from a view for a recent activity page.
Recent orders from view:
('Diana Smith', 'Tablet', '2025-07-01 10:00:00')
('Diana Smith', 'Monitor', '2025-07-10 14:30:00')
Deletes multiple cart items using a loop for cart cleanup.
Deleted cart items for 2 users
Fetches products within a price range into a tuple for a product filter.
Products between $50 and $200:
('Headphones', 99.99)
Updates product details with a transaction using a class for inventory management.
Updated product ID 1
Segments customers based on order totals using a subquery and conditionals for marketing.
Diana Smith: VIP Eve: Regular Grace: Regular
Creates a view for sales reports using a class for analytics.
Sales report view created
Updates an order using a stored procedure and class for order management.
Updated order ID 1
Fetches recent user logs with user details using a join for audit reporting.
Recent logs with user details:
('Diana Smith', 'Updated', '2025-07-10 14:00:00')
Fetches unique user emails using DISTINCT into a list for a mailing list.
Unique emails: diana_updated@example.com eve@example.com grace@example.com
Checks product availability based on stock and cart quantities for a checkout system.
Smartphone: Available
Updates stock for multiple products using a loop for inventory restocking.
Updated stock for 2 products
Calculates total cart value for a user using a join and SUM for checkout.
Cart total for user 4: $1399.98
Fetches products not in any cart using a subquery for product recommendations.
Products not in cart: Tablet Laptop Mouse
Creates a trigger to log product discount updates using a class for audit tracking.
Discount update trigger created
Groups orders by month using MONTH and COUNT for monthly sales reports.
Orders by month: Month 7: 2 orders
Fetches unique products in carts using DISTINCT for cart analysis.
Unique products in cart: Smartphone
Updates cart quantity based on stock availability using conditionals for checkout validation.
Updated cart quantity for user 4
Deletes an order with a transaction using a class for order cancellation.
Deleted order ID 2
Fetches product sales from a view using SUM for a sales report.
Sales from view: Tablet: $499.99 Monitor: $299.99
Fetches user orders matching a regex pattern for product filtering.
Orders matching 'Tablet|Phone':
('Diana Smith', 'Tablet')
Fetches high-value orders using a subquery into a dictionary for premium customer analysis.
High-value orders: Tablet: Diana Smith, $499.99