Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: MySQL Operators in E-Commerce

Python MySQL Operators - E-Commerce Guide

Learn how to use MySQL operators in Python with an E-Commerce platform.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
Read Time: 10 minutes Level: Intermediate Case Study: E-Commerce Platform Focus: Python Implementation

E-Commerce Case Study: This tutorial uses an E-Commerce platform database with customers, products, orders, and reviews. Operators help you filter products, find customers, and analyze sales data.

Python Focus: This tutorial focuses on using MySQL operators from Python using mysql-connector-python. For pure SQL operator reference and optimization, we have a separate MySQL Operators Guide coming soon.

On this page:
  • What are MySQL Operators?
  • Comparison Operators
  • Logical Operators
  • Arithmetic Operators
  • Special Operators
  • E-Commerce Python Examples
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Comparison operators — =, !=, >, <, >=, <=
  • Logical operators — AND, OR, NOT
  • Arithmetic operators — +, -, *, /, %
  • Special operators — LIKE, IN, BETWEEN, IS NULL
  • E-Commerce examples — filtering products, customers, orders

What are MySQL Operators?

Operators are symbols or keywords that perform operations on data in your SQL queries. They help you filter, compare, and manipulate data.

Comparison

=, !=, >, <, >=, <=

Logical

AND, OR, NOT

Arithmetic

+, -, *, /, %

Special

LIKE, IN, BETWEEN, IS NULL

E-Commerce Tables Used:

products (product_id, product_name, category, price, stock_quantity)
customers (customer_id, first_name, last_name, city, state)
orders (order_id, customer_id, total_amount, status)
reviews (review_id, product_id, rating, comment)
1

Why Operators Matter in E-Commerce

# ============================================================
# OPERATORS IN E-COMMERCE
# ============================================================

# 1. Comparison: Find expensive products
SELECT * FROM products WHERE price > 500;

# 2. Logical: Find products in Electronics under $1000
SELECT * FROM products 
WHERE category = 'Electronics' AND price < 1000;

# 3. Arithmetic: Calculate discounted price
SELECT product_name, price, price * 0.9 AS discounted_price
FROM products;

# 4. Special: Search products containing 'Phone'
SELECT * FROM products WHERE product_name LIKE '%Phone%';

# 5. Special: Find products in specific price range
SELECT * FROM products WHERE price BETWEEN 100 AND 500;

# 6. Special: Find customers from specific cities
SELECT * FROM customers WHERE city IN ('Mumbai', 'Delhi');

Key point: Operators let you write powerful, precise queries to filter and analyze your E-Commerce data.

Quick Check: What are operators used for? (Answer: To perform operations, comparisons, and filtering on data)

Comparison Operators

2

Comparing Values in E-Commerce

# ============================================================
# COMPARISON OPERATORS
# ============================================================

# =  equal to
# !=  not equal to
# >  greater than
# <  less than
# >=  greater than or equal to
# <=  less than or equal to

# ============================================================
# E-COMMERCE EXAMPLES
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# 1. Equal to - Find specific product
cursor.execute("SELECT * FROM products WHERE category = 'Electronics'")
products = cursor.fetchall()
print("Electronics Products:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# 2. Not equal to - Find products not in Electronics
cursor.execute("SELECT * FROM products WHERE category != 'Electronics'")
products = cursor.fetchall()
print("\nNon-Electronics Products:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# 3. Greater than - Find expensive products
cursor.execute("SELECT * FROM products WHERE price > 500")
products = cursor.fetchall()
print("\nProducts over $500:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# 4. Less than - Find affordable products
cursor.execute("SELECT * FROM products WHERE price < 100")
products = cursor.fetchall()
print("\nProducts under $100:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# 5. Greater than or equal - Products $100 and above
cursor.execute("SELECT * FROM products WHERE price >= 100")
products = cursor.fetchall()
print("\nProducts $100 and above:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# 6. Less than or equal - Products $200 and below
cursor.execute("SELECT * FROM products WHERE price <= 200")
products = cursor.fetchall()
print("\nProducts $200 and below:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

cursor.close()
connection.close()

Comparison operators summary:

  • = — equals (exact match)
  • != — not equals
  • > — greater than
  • < — less than
  • >= — greater than or equal
  • <= — less than or equal

Quick Check: What operator finds products under $100? (Answer: < or price < 100)

Logical Operators

3

Combining Conditions in E-Commerce

# ============================================================
# LOGICAL OPERATORS
# ============================================================

# AND - both conditions must be true
# OR - at least one condition must be true
# NOT - reverses the condition

# ============================================================
# AND OPERATOR - Multiple filters
# ============================================================

# Electronics under $500
cursor.execute(
    "SELECT * FROM products WHERE category = 'Electronics' AND price < 500"
)
products = cursor.fetchall()
print("Electronics under $500:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# Customers from Mumbai with orders
cursor.execute("""
    SELECT c.first_name, c.last_name, c.city, COUNT(o.order_id) as order_count
    FROM customers c
    JOIN orders o ON c.customer_id = o.customer_id
    WHERE c.city = 'Mumbai' AND o.status = 'completed'
    GROUP BY c.customer_id
""")
results = cursor.fetchall()
print("\nMumbai customers with completed orders:")
for r in results:
    print(f"  {r[0]} {r[1]} - {r[2]} orders")

# ============================================================
# OR OPERATOR - Multiple alternatives
# ============================================================

# Products from Electronics OR Footwear
cursor.execute(
    "SELECT * FROM products WHERE category = 'Electronics' OR category = 'Footwear'"
)
products = cursor.fetchall()
print("\nElectronics or Footwear products:")
for p in products:
    print(f"  {p[1]} - {p[2]}")

# Customers from Mumbai OR Delhi
cursor.execute(
    "SELECT * FROM customers WHERE city = 'Mumbai' OR city = 'Delhi'"
)
customers = cursor.fetchall()
print("\nCustomers from Mumbai or Delhi:")
for c in customers:
    print(f"  {c[1]} {c[2]} - {c[4]}")

# ============================================================
# NOT OPERATOR - Excluding conditions
# ============================================================

# Products not in Electronics
cursor.execute("SELECT * FROM products WHERE NOT category = 'Electronics'")
products = cursor.fetchall()
print("\nProducts not in Electronics:")
for p in products:
    print(f"  {p[1]} - {p[2]}")

# Orders not completed
cursor.execute("SELECT * FROM orders WHERE NOT status = 'completed'")
orders = cursor.fetchall()
print("\nOrders not completed:")
for o in orders:
    print(f"  Order {o[0]} - Status: {o[5]}")

# ============================================================
# COMBINING AND + OR
# ============================================================

# Electronics OR Footwear products under $200
cursor.execute("""
    SELECT * FROM products 
    WHERE (category = 'Electronics' OR category = 'Footwear') 
    AND price < 200
""")
products = cursor.fetchall()
print("\nElectronics or Footwear under $200:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

Logical operators summary:

  • AND — all conditions must be true
  • OR — at least one condition must be true
  • NOT — reverses the condition
  • Use parentheses to group conditions

Quick Check: What operator finds products in Electronics OR Footwear? (Answer: OR)

Arithmetic Operators

4

Performing Calculations on E-Commerce Data

# ============================================================
# ARITHMETIC OPERATORS
# ============================================================

# +  addition
# -  subtraction
# *  multiplication
# /  division
# %  modulo (remainder)

# ============================================================
# E-COMMERCE EXAMPLES
# ============================================================

# 1. Calculate discounted price (10% off)
cursor.execute("""
    SELECT product_name, price, price * 0.9 AS discounted_price
    FROM products
""")
products = cursor.fetchall()
print("Products with 10% discount:")
for p in products:
    print(f"  {p[0]} - Original: ${p[1]}, Discounted: ${p[2]}")

# 2. Calculate total revenue per product
cursor.execute("""
    SELECT p.product_name, 
           SUM(oi.quantity * oi.unit_price) AS total_revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    GROUP BY p.product_id
""")
results = cursor.fetchall()
print("\nRevenue per product:")
for r in results:
    print(f"  {r[0]} - ${r[1]}")

# 3. Apply tax calculation (18% GST)
cursor.execute("""
    SELECT product_name, price, 
           price * 0.18 AS tax,
           price + (price * 0.18) AS price_with_tax
    FROM products
""")
products = cursor.fetchall()
print("\nProduct prices with 18% tax:")
for p in products:
    print(f"  {p[0]} - Base: ${p[1]}, Tax: ${p[2]}, Total: ${p[3]}")

# 4. Calculate average order value
cursor.execute("""
    SELECT AVG(total_amount) AS avg_order_value,
           SUM(total_amount) AS total_revenue,
           COUNT(order_id) AS total_orders
    FROM orders
    WHERE status = 'completed'
""")
result = cursor.fetchone()
print(f"\nOrder Statistics:")
print(f"  Average order value: ${result[0]}")
print(f"  Total revenue: ${result[1]}")
print(f"  Total orders: {result[2]}")

# 5. Update stock after sale (simulate)
cursor.execute("""
    SELECT product_name, stock_quantity, 
           stock_quantity - 5 AS updated_stock
    FROM products
""")
products = cursor.fetchall()
print("\nStock after selling 5 units:")
for p in products:
    print(f"  {p[0]} - Current: {p[1]}, After sale: {p[2]}")

Arithmetic operators summary:

  • + — addition
  • - — subtraction
  • * — multiplication
  • / — division
  • % — modulo

Quick Check: How do you calculate a 10% discount? (Answer: price * 0.9 or price - (price * 0.1))

Special Operators

5

LIKE, IN, BETWEEN, IS NULL

# ============================================================
# SPECIAL OPERATORS
# ============================================================

# LIKE - pattern matching
# IN - matches any value in a list
# BETWEEN - checks if value is in a range
# IS NULL - checks for null values

# ============================================================
# LIKE OPERATOR - Pattern matching
# ============================================================

# Products starting with 'i'
cursor.execute("SELECT * FROM products WHERE product_name LIKE 'i%'")
products = cursor.fetchall()
print("Products starting with 'i':")
for p in products:
    print(f"  {p[1]}")

# Products containing 'Phone'
cursor.execute("SELECT * FROM products WHERE product_name LIKE '%Phone%'")
products = cursor.fetchall()
print("\nProducts containing 'Phone':")
for p in products:
    print(f"  {p[1]}")

# Customers with names ending in 'a'
cursor.execute("SELECT * FROM customers WHERE first_name LIKE '%a'")
customers = cursor.fetchall()
print("\nCustomers with names ending in 'a':")
for c in customers:
    print(f"  {c[1]} {c[2]}")

# ============================================================
# IN OPERATOR - Multiple values
# ============================================================

# Products in specific categories
cursor.execute(
    "SELECT * FROM products WHERE category IN ('Electronics', 'Footwear')"
)
products = cursor.fetchall()
print("\nProducts in Electronics or Footwear:")
for p in products:
    print(f"  {p[1]} - {p[2]}")

# Customers from specific cities
cursor.execute(
    "SELECT * FROM customers WHERE city IN ('Mumbai', 'Delhi', 'Bangalore')"
)
customers = cursor.fetchall()
print("\nCustomers from Mumbai, Delhi, or Bangalore:")
for c in customers:
    print(f"  {c[1]} {c[2]} - {c[4]}")

# ============================================================
# BETWEEN OPERATOR - Range
# ============================================================

# Products in price range
cursor.execute("SELECT * FROM products WHERE price BETWEEN 100 AND 500")
products = cursor.fetchall()
print("\nProducts between $100 and $500:")
for p in products:
    print(f"  {p[1]} - ${p[4]}")

# Orders with total between $100 and $500
cursor.execute("SELECT * FROM orders WHERE total_amount BETWEEN 100 AND 500")
orders = cursor.fetchall()
print("\nOrders between $100 and $500:")
for o in orders:
    print(f"  Order {o[0]} - ${o[3]}")

# ============================================================
# IS NULL - Check for null values
# ============================================================

# Products with no description
cursor.execute("SELECT * FROM products WHERE description IS NULL")
products = cursor.fetchall()
print("\nProducts without description:")
for p in products:
    print(f"  {p[1]}")

# Orders without tracking number
cursor.execute("SELECT * FROM orders WHERE tracking_number IS NULL")
orders = cursor.fetchall()
print("\nOrders without tracking number:")
for o in orders:
    print(f"  Order {o[0]}")

Special operators summary:

  • LIKE — pattern matching (% for wildcard)
  • IN — matches any value in a list
  • BETWEEN — checks if value is in a range
  • IS NULL — checks for missing values

Quick Check: What operator searches for products containing 'Phone'? (Answer: LIKE '%Phone%')

E-Commerce Python Examples

6

Building E-Commerce Features with Operators

# ============================================================
# E-COMMERCE OPERATORS IN PYTHON
# ============================================================

import mysql.connector

class ECommerceOperators:
    """E-Commerce operations using MySQL operators"""
    
    def __init__(self, db_config):
        self.db_config = db_config
        self.connection = None
        self.cursor = None
    
    def connect(self):
        try:
            self.connection = mysql.connector.connect(**self.db_config)
            self.cursor = self.connection.cursor()
            return True
        except Exception as e:
            print(f"Connection failed: {e}")
            return False
    
    # ============================================================
    # COMPARISON OPERATORS
    # ============================================================
    
    def get_products_by_price(self, operator, price):
        """Get products using comparison operators"""
        query = f"SELECT * FROM products WHERE price {operator} %s"
        self.cursor.execute(query, (price,))
        return self.cursor.fetchall()
    
    def get_products_by_category(self, category):
        """Get products in a category"""
        query = "SELECT * FROM products WHERE category = %s"
        self.cursor.execute(query, (category,))
        return self.cursor.fetchall()
    
    # ============================================================
    # LOGICAL OPERATORS
    # ============================================================
    
    def get_products_by_category_and_price(self, category, min_price, max_price):
        """Get products with AND operator"""
        query = """
            SELECT * FROM products 
            WHERE category = %s AND price BETWEEN %s AND %s
        """
        self.cursor.execute(query, (category, min_price, max_price))
        return self.cursor.fetchall()
    
    def get_products_by_categories(self, categories):
        """Get products with OR/IN operator"""
        placeholders = ', '.join(['%s'] * len(categories))
        query = f"SELECT * FROM products WHERE category IN ({placeholders})"
        self.cursor.execute(query, categories)
        return self.cursor.fetchall()
    
    # ============================================================
    # ARITHMETIC OPERATORS
    # ============================================================
    
    def get_discounted_products(self, discount_percent):
        """Get products with calculated discount"""
        query = f"""
            SELECT product_name, price, 
                   price * {discount_percent/100} AS discount,
                   price - (price * {discount_percent/100}) AS discounted_price
            FROM products
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def get_category_revenue(self):
        """Get revenue by category with SUM"""
        query = """
            SELECT p.category, 
                   SUM(oi.quantity * oi.unit_price) AS total_revenue
            FROM products p
            JOIN order_items oi ON p.product_id = oi.product_id
            GROUP BY p.category
            ORDER BY total_revenue DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    # ============================================================
    # SPECIAL OPERATORS
    # ============================================================
    
    def search_products(self, search_term):
        """Search products using LIKE"""
        query = "SELECT * FROM products WHERE product_name LIKE %s"
        self.cursor.execute(query, (f"%{search_term}%",))
        return self.cursor.fetchall()
    
    def get_products_by_price_range(self, min_price, max_price):
        """Get products using BETWEEN"""
        query = "SELECT * FROM products WHERE price BETWEEN %s AND %s"
        self.cursor.execute(query, (min_price, max_price))
        return self.cursor.fetchall()
    
    def get_products_in_stock(self):
        """Get products in stock (not null)"""
        query = "SELECT * FROM products WHERE stock_quantity IS NOT NULL"
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    # ============================================================
    # COMBINED OPERATORS
    # ============================================================
    
    def get_sales_analytics(self):
        """Sales analytics using multiple operators"""
        query = """
            SELECT 
                p.category,
                COUNT(DISTINCT o.order_id) AS order_count,
                SUM(oi.quantity) AS total_units,
                SUM(oi.quantity * oi.unit_price) AS total_revenue,
                AVG(oi.unit_price) AS avg_price,
                MAX(oi.unit_price) AS max_price,
                MIN(oi.unit_price) AS min_price
            FROM products p
            JOIN order_items oi ON p.product_id = oi.product_id
            JOIN orders o ON oi.order_id = o.order_id
            WHERE o.status = 'completed'
            GROUP BY p.category
            HAVING total_revenue > 100
            ORDER BY total_revenue DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def display_results(self, results, title="Results"):
        """Display results"""
        if not results:
            print(f"\n{title}: No results")
            return
        print(f"\n{title}: {len(results)} rows")
        print("-" * 60)
        for row in results:
            print(f"  {row}")
    
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

# ============================================================
# DEMONSTRATION
# ============================================================

db_config = {
    "host": "localhost",
    "user": "root",
    "password": "secret",
    "database": "ecommerce_db"
}

store = ECommerceOperators(db_config)

if store.connect():
    
    print("=" * 60)
    print("E-COMMERCE OPERATORS DEMONSTRATION")
    print("=" * 60)
    
    # 1. Comparison operators
    print("\n1. COMPARISON OPERATORS")
    products = store.get_products_by_price(">", 500)
    print(f"Products over $500: {len(products)}")
    
    # 2. Logical operators
    print("\n2. LOGICAL OPERATORS")
    products = store.get_products_by_category_and_price("Electronics", 100, 500)
    print(f"Electronics between $100-$500: {len(products)}")
    
    # 3. Arithmetic operators
    print("\n3. ARITHMETIC OPERATORS")
    discounted = store.get_discounted_products(20)
    print(f"Products with 20% discount: {len(discounted)}")
    
    # 4. Special operators
    print("\n4. SPECIAL OPERATORS")
    products = store.search_products("Phone")
    print(f"Products containing 'Phone': {len(products)}")
    
    # 5. Combined operators
    print("\n5. SALES ANALYTICS")
    analytics = store.get_sales_analytics()
    print("Sales by category:")
    for row in analytics:
        print(f"  {row[0]}: {row[1]} orders, {row[2]} units, ${row[3]} revenue")
    
    store.close()

This example shows:

  • All operator types in E-Commerce context
  • Comparison, logical, arithmetic, and special operators
  • Combined operators for analytics
  • Python methods for each operator type

Quick Check: What makes this a Python tutorial rather than a MySQL tutorial? (Answer: The focus is on executing queries from Python and building Python methods)

Best Practices

7

Best Practices for Using Operators

# ============================================================
# BEST PRACTICES FOR OPERATORS
# ============================================================

print("1. USE PARAMETERIZED QUERIES")
print("   - Always use %s placeholders")
print("   - Even with operators, protect against injection")

print("\n2. USE INDEXES ON OPERATOR COLUMNS")
print("   - Columns used with =, >, <, LIKE should be indexed")
print("   - BETWEEN and IN benefit from indexes")

print("\n3. AVOID FUNCTIONS ON INDEXED COLUMNS")
print("   - WHERE YEAR(date) = 2024 is slow")
print("   - Use date BETWEEN '2024-01-01' AND '2024-12-31'")

print("\n4. USE LIKE CAREFULLY")
print("   - 'Phone%' is faster than '%Phone%'")
print("   - Leading % prevents index usage")

print("\n5. USE IN OVER MULTIPLE OR CONDITIONS")
print("   - IN is cleaner and often faster")
print("   - WHERE city IN ('Mumbai', 'Delhi')")

print("\n6. USE BETWEEN OVER >= AND <=")
print("   - BETWEEN is cleaner and more readable")
print("   - WHERE price BETWEEN 100 AND 500")

print("\n7. USE EXPLAIN TO ANALYZE")
print("   - Check how operators affect performance")
print("   - Identify slow queries")

print("\n8. BE CONSISTENT")
print("   - Use same operator style throughout")
print("   - Maintain readability")

Summary of best practices:

  • Parameterized queries — always for security
  • Indexes — on columns used with operators
  • Use IN over OR — cleaner and faster
  • Use BETWEEN over >= <= — more readable
  • Avoid leading % in LIKE — prevents index usage

Quick Check: Why should you avoid leading % in LIKE? (Answer: It prevents the database from using indexes)

Try It Yourself

Experiment with MySQL operators in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
MYSQL OPERATORS - PRACTICE
========================================

1. COMPARISON OPERATORS
----------------------------------------
Products over $500: 2
iPhone 15 Pro - $999.99
MacBook Air M3 - $1099.99

Products under $100: 2
Levi's Jeans - $69.99
Nike T-Shirt - $29.99

2. LOGICAL OPERATORS
----------------------------------------
Electronics under $500: 2
Apple Watch - $399.99
Sony Headphones - $299.99

Electronics or Footwear: 4
iPhone 15 Pro - Electronics
MacBook Air M3 - Electronics
Nike Air Max - Footwear
Apple Watch - Electronics
Sony Headphones - Electronics

3. SPECIAL OPERATORS
----------------------------------------
Products containing 'Phone': 1
iPhone 15 Pro

Products between $100-$300: 3
Nike Air Max - $149.99
Ray-Ban Sunglasses - $199.99
Sony Headphones - $299.99

4. OPERATOR SUMMARY
----------------------------------------
┌─────────────────┬──────────────────────────────────────────────┐
│ Operator Type │ Examples │
├─────────────────┼──────────────────────────────────────────────┤
│ Comparison │ =, !=, >, <, >=, <= │
│ Logical │ AND, OR, NOT │
│ Arithmetic │ +, -, *, /, % │
│ Special │ LIKE, IN, BETWEEN, IS NULL │
└─────────────────┴──────────────────────────────────────────────┘

Operators make your E-Commerce queries powerful!
🏆

You've Got It!

You now understand MySQL operators in Python with an E-Commerce case study. You know comparison, logical, arithmetic, and special operators.

Quick Quiz

Test what you've learned:

1. What operator finds products over $500?
2. What operator combines multiple conditions?
3. What operator searches for patterns in text?
4. What operator checks if a value is in a list?
5. What is the best practice for using LIKE?

Frequently Asked Questions

What is the difference between = and LIKE? ▼

= checks for exact matches. LIKE checks for patterns using wildcards. Use = for exact values and LIKE for partial matches.

What is the difference between IN and OR? ▼

IN is cleaner and often faster for multiple values. OR is more flexible but can be slower. Use IN for lists of values.

Why avoid leading % in LIKE? ▼

Leading % prevents MySQL from using indexes, making queries slower. Use 'Phone%' instead of '%Phone%' when possible.

What is a common interview question about MySQL operators? ▼

Common questions include: "Explain the difference between = and LIKE," "What is the difference between IN and OR?" and "How do you use BETWEEN in a query?"

Will this conflict with future pure MySQL tutorials? ▼

No. This tutorial focuses on using operators from Python with mysql-connector. Future MySQL tutorials will focus on SQL syntax and optimization with different titles and URLs.

Where to Go From Here

Now that you understand MySQL operators, check out these related topics:

DDL Statements

Learn how to create and modify database structures.

Learn More →

JOIN Operations

Learn how to combine data from multiple tables.

Learn More →

Aggregation

Learn how to summarize data with GROUP BY.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: SELECT Statement Next: DDL Statements →