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: Create Table in MySQL

Sankalan Data Tech Team Verified
Python & MySQL Experts
Making database programming simple and fun for everyone. Learn by doing with real examples!
Read Time: 8 minutes Level: Beginner Topic: MySQL Tables, Python
What's Inside?
  • šŸ“– What is a Table?
  • šŸ“Š Understanding Data Types
  • šŸ”§ CREATE TABLE Syntax
  • šŸ—ļø Create Your First Table
  • šŸ”‘ Primary Keys Explained
  • šŸ“ˆ Auto-Increment
  • šŸ” Checking Table Existence
  • šŸ’¼ Real-World Example
  • āœ… Best Practices
  • šŸŽ® Try It Yourself
  • 🧠 Quick Quiz
  • ā“ FAQ
šŸ“¤ Share this:
Twitter LinkedIn Facebook WhatsApp Copy Link

šŸ“– What is a Table in MySQL?

If a database is like a filing cabinet, then a table is like one of the drawers inside it. And inside that drawer, you have folders and papers organized in a specific way.

🧠 Think of it like a spreadsheet! You know how Excel has rows and columns? A MySQL table works exactly the same way:

  • Columns = Categories (like "Name", "Age", "Email")
  • Rows = Individual records (like one person's information)

Let me give you a real-life example. Imagine you're building a system for a school. You would need a table called "students" to store information about each student.

This table would have columns like:

  • student_id – a unique number for each student
  • first_name – their first name
  • last_name – their last name
  • age – their age
  • email – their email address

Each row in this table would represent one student. So if you have 100 students, you'd have 100 rows in your table.

šŸ’” Key point to remember: Before you can store any data in MySQL, you must create a table first. It's like building shelves before you can put books on them. The table defines the structure of your data.

šŸ“Š Understanding Data Types

This is one of the most important concepts to understand. When you create a table, you need to tell MySQL what type of data each column will hold.

Think of it like this: you wouldn't put a phone number in a date field, right? You wouldn't store someone's age as text. Data types help MySQL understand what kind of information it's dealing with.

šŸ’” Why data types matter: Choosing the right data type saves space, makes your database faster, and prevents errors. For example, storing numbers as numbers (not text) lets you do math operations.

šŸ”¢ 1. Numeric Data Types

These are used for numbers. Let me explain the most common ones:

INT

Whole numbers – like 1, 25, 1000, -5. Perfect for IDs, ages, counts.
Example: student_id INT

DECIMAL

Numbers with decimals – like 99.99, 10.5, 3.14159. Great for prices, weights, measurements.
Example: price DECIMAL(10,2)

BOOLEAN

True or False – like is_active, is_deleted, has_paid.
Example: is_active BOOLEAN

šŸ“ 2. Text/String Data Types

These are used for text – names, descriptions, emails, any kind of words.

VARCHAR

Variable length text – like names, emails, addresses. You specify the max length.
Example: first_name VARCHAR(50) – up to 50 characters

TEXT

Long text – like blog posts, product descriptions, comments.
Example: description TEXT

CHAR

Fixed length text – like US state codes (CA, NY, TX). Always uses the same space.
Example: state_code CHAR(2)

šŸ’” Pro tip: Use VARCHAR for most text fields. It uses less space than CHAR and is more flexible. Use TEXT only for very long content.

šŸ“… 3. Date and Time Data Types

DATE

Just the date – like '2024-01-15'. Perfect for birthdays, hire dates.
Example: birth_date DATE

DATETIME

Date and time – like '2024-01-15 14:30:00'. Great for timestamps.
Example: created_at DATETIME

āš ļø Common mistake: Many beginners store dates as text (VARCHAR). Don't do this! Using DATE/DATETIME allows you to sort dates correctly, calculate age, and filter by date ranges.

šŸ”§ CREATE TABLE Syntax

Now that you understand what a table is and what data types are, let's look at the actual SQL command to create a table.

The basic syntax looks like this:

CREATE TABLE table_name ( column1_name data_type [constraints], column2_name data_type [constraints], ... );

Let me break this down piece by piece:

CREATE TABLE – The SQL command that tells MySQL "I want to create a new table"
table_name – The name you want to give your table (like "students" or "products")
column definitions – Each column has a name, a data type, and optional constraints
constraints – Rules like "this column cannot be empty" or "this must be unique"

šŸ“Œ Note: The ; at the end is important – it tells MySQL the command is complete. In Python, you'll put this SQL inside a string.

šŸ—ļø Create Your First Table

Let's create a table for a school. We'll call it "students". This table will store:

  • Each student's unique ID
  • Their first name and last name
  • Their age
  • Their email address
  • When they joined the school

Before we write any Python code, let's look at the SQL we need:

CREATE TABLE IF NOT EXISTS students ( student_id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, age INT, email VARCHAR(100) UNIQUE, joined_date DATE );

Let me explain each part of this SQL:

student_id INT AUTO_INCREMENT PRIMARY KEY

INT = whole number  |  AUTO_INCREMENT = automatically increases (1,2,3...)  |  PRIMARY KEY = unique identifier for each row

first_name VARCHAR(50) NOT NULL

VARCHAR(50) = text up to 50 characters  |  NOT NULL = this field must have a value (can't be empty)

email VARCHAR(100) UNIQUE

UNIQUE = no two students can have the same email address

Now, let's put this into Python code. Here's how you create a table from Python:

1 Import the module and connect to MySQL
import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="myapp_db"  # Use the database we created earlier
)
2 Define the SQL query
create_table_query = """
CREATE TABLE IF NOT EXISTS students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    age INT,
    email VARCHAR(100) UNIQUE,
    joined_date DATE
)
"""
3 Execute the query
cursor = connection.cursor()
cursor.execute(create_table_query)

print("āœ… Table 'students' created successfully!")

# Always close your connections
cursor.close()
connection.close()

šŸŽ‰ You did it! You've just created your first table in MySQL from Python. That wasn't so hard, was it?

šŸ’” Remember: The IF NOT EXISTS part is your safety net. If the table already exists, MySQL will just ignore the command instead of throwing an error.

šŸ”‘ Primary Keys Explained

A Primary Key is one of the most important concepts in databases. Let me explain it with a simple example.

šŸŽÆ Think of a primary key like your Aadhar card or Social Security number.

Every person in India has a unique Aadhar number. No two people have the same one. It's the official way to identify each person uniquely.

A primary key does the exact same thing in a database! It's a column (or combination of columns) that uniquely identifies each row.

Why is a primary key so important?

āœ…
Uniqueness
Every row can be identified without confusion
āœ…
Speed
MySQL automatically creates an index for faster searches
āœ…
Relationships
You can link this table to other tables using the primary key
āœ…
Data Integrity
Prevents duplicate rows from being inserted

What makes a good primary key?

  • Unique – no two rows have the same value
  • Never changes – once assigned, it stays the same forever
  • Simple – usually a number (INT) or a short text
  • No empty values – every row must have a primary key

šŸ’” Most common practice: Use an auto-incrementing integer as your primary key. It's simple, guaranteed unique, and MySQL handles it automatically.

šŸ“ˆ Auto-Increment – Let MySQL Do the Counting

AUTO_INCREMENT is a super useful feature. When you set a column to AUTO_INCREMENT, MySQL automatically assigns a unique number to each new row.

šŸŽ« Think of it like a ticket counter.

Imagine you're at a bakery. The counter has a machine that prints numbers: 1, 2, 3, 4, 5... Each customer gets the next number. You don't have to decide which number to give – the machine does it for you.

AUTO_INCREMENT works exactly the same way. When you add a new student, MySQL automatically gives them the next ID number. You don't have to calculate it yourself!

Here's how it works with our students table:

When you insert the first student:

student_id = 1  # MySQL assigns it automatically

When you insert the second student:

student_id = 2  # Automatically increments

When you insert the third student:

student_id = 3  # And so on...

šŸ’” Pro tip: You never need to specify the AUTO_INCREMENT column when inserting data. Just leave it out and MySQL will fill it in.

šŸ” Checking If a Table Exists

Before creating a table, you might want to check if it already exists. Here are a few ways to do it:

Method 1: Using SHOW TABLES

cursor.execute("SHOW TABLES LIKE 'students'")
result = cursor.fetchone()

if result:
    print("āœ… Table 'students' exists")
else:
    print("āŒ Table 'students' does not exist")

Method 2: Using INFORMATION_SCHEMA (Most Reliable)

cursor.execute("""
    SELECT TABLE_NAME 
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_SCHEMA = 'myapp_db' 
    AND TABLE_NAME = 'students'
""")
result = cursor.fetchone()

if result:
    print("āœ… Table exists")

Method 3: Just Use IF NOT EXISTS (Simplest)

# This is the easiest way – just let MySQL handle it!
cursor.execute("CREATE TABLE IF NOT EXISTS students (...)")

šŸ’” Recommendation: If you're just creating a table once, use IF NOT EXISTS. It's the simplest and most reliable approach.

šŸ’¼ Real-World Example: E-Commerce Database

Let's build something more realistic. Imagine you're creating a database for an online store. You'd need tables for:

  • products – items you're selling
  • customers – people who buy from you
  • orders – purchases made by customers

Here's a complete Python script that creates all these tables:

import mysql.connector from mysql.connector import Error def create_ecommerce_tables(): """Create all tables for an e-commerce store""" try: # Connect to MySQL connection = mysql.connector.connect( host="localhost", user="root", password="secret", database="myapp_db" ) cursor = connection.cursor() # ============================================================ # 1. PRODUCTS TABLE # ============================================================ products_query = """ CREATE TABLE IF NOT EXISTS products ( product_id INT AUTO_INCREMENT PRIMARY KEY, product_name VARCHAR(100) NOT NULL, description TEXT, price DECIMAL(10, 2) NOT NULL, stock_quantity INT DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) """ cursor.execute(products_query) print("āœ… Products table created") # ============================================================ # 2. CUSTOMERS TABLE # ============================================================ customers_query = """ CREATE TABLE IF NOT EXISTS customers ( customer_id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, phone VARCHAR(20), address TEXT, registered_date DATE ) """ cursor.execute(customers_query) print("āœ… Customers table created") # ============================================================ # 3. ORDERS TABLE # ============================================================ orders_query = """ CREATE TABLE IF NOT EXISTS orders ( order_id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, order_date DATETIME DEFAULT CURRENT_TIMESTAMP, total_amount DECIMAL(10, 2) NOT NULL, status VARCHAR(20) DEFAULT 'pending', FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ) """ cursor.execute(orders_query) print("āœ… Orders table created") # ============================================================ # 4. ORDER ITEMS TABLE # ============================================================ order_items_query = """ CREATE TABLE IF NOT EXISTS order_items ( order_item_id INT AUTO_INCREMENT PRIMARY KEY, order_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL, price DECIMAL(10, 2) NOT NULL, FOREIGN KEY (order_id) REFERENCES orders(order_id), FOREIGN KEY (product_id) REFERENCES products(product_id) ) """ cursor.execute(order_items_query) print("āœ… Order items table created") connection.commit() print("šŸŽ‰ All tables created successfully!") except Error as e: print(f"āŒ Error: {e}") if connection: connection.rollback() finally: if cursor: cursor.close() if connection: connection.close() # Run it! create_ecommerce_tables()

What's happening in this example?

products table – stores product name, description, price, and how many are in stock
customers table – stores customer information (name, email, address)
orders table – stores each order with customer ID, date, total amount
order_items table – stores which products are in each order

šŸ”— Notice the FOREIGN KEY in orders and order_items?
This links tables together. For example, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) means "this order belongs to a customer." It's how you connect related data!

āœ… Best Practices for Creating Tables

Here are some tips I've learned from years of building databases:

1 Always use IF NOT EXISTS

This prevents errors if your script runs twice. It's a safety net that every developer should use.

2 Use meaningful column names

Instead of col1, col2, use names like first_name, email, created_at. Future you will thank you!

3 Choose the right data types

Use INT for numbers, VARCHAR for text, DATE for dates. It saves space and makes queries faster.

4 Always have a primary key

Every table should have a primary key. It's the most important rule of database design.

5 Use NOT NULL where appropriate

If a column must have a value (like a customer's name), mark it NOT NULL. It prevents incomplete data from entering your database.

6 Use AUTO_INCREMENT for primary keys

It's the easiest way to guarantee unique IDs. Let MySQL do the work for you.

7 Add useful timestamps

Columns like created_at and updated_at are incredibly useful for debugging and tracking.

šŸŽÆ The golden rule of database design: Think about how you'll use the data in the future. A well-designed table makes your life much easier down the road!

šŸŽ® Try It Yourself

Play with the code below. Click "Run" to create a table and see it in action!

Loading... 0%
Python Code
============================================= CREATE TABLE - PRACTICE ============================================= šŸ“‹ Creating a 'students' table... āœ… Table 'students' created! Columns: student_id (INT, PRIMARY KEY, AUTO_INCREMENT), first_name (VARCHAR(50), NOT NULL), last_name (VARCHAR(50), NOT NULL), age (INT), email (VARCHAR(100), UNIQUE) šŸ“‹ Creating a 'products' table... āœ… Table 'products' created! Columns: product_id (INT, PRIMARY KEY), product_name (VARCHAR(100), NOT NULL), price (DECIMAL(10,2)), stock (INT, DEFAULT 0) šŸ“‹ All tables created: • students • products šŸ”„ Trying to create 'students' again... ā„¹ļø Table 'students' already exists āœ… Done! Creating tables is easy!
šŸ†

You're Doing Great!

You now understand how to create tables in MySQL from Python. You know about data types, primary keys, and best practices.

🧠 Quick Quiz

Let's see what you've learned about creating tables!

1ļøāƒ£ What SQL command creates a table in MySQL?
2ļøāƒ£ What data type should you use to store someone's age?
3ļøāƒ£ What is the purpose of a PRIMARY KEY?
4ļøāƒ£ What does AUTO_INCREMENT do?
5ļøāƒ£ Why should you use NOT NULL on a column?

ā“ Frequently Asked Questions

šŸ¤” What's the difference between VARCHAR and TEXT? ā–¼

VARCHAR is for shorter text (up to 65,535 characters). You specify a maximum length like VARCHAR(255). It stores data more efficiently and can be indexed.

TEXT is for longer text (up to 65,535 characters). You can't set a maximum length and it's less efficient. Use TEXT for blog posts, product descriptions, etc.

Rule of thumb: Use VARCHAR for names, emails, addresses. Use TEXT for longer content.

šŸ¤” Can I change a table after creating it? ā–¼

Yes! You can use ALTER TABLE to:

  • Add new columns
  • Change column data types
  • Rename columns
  • Add or remove constraints

Example: ALTER TABLE students ADD COLUMN phone VARCHAR(20);

šŸ¤” How do I delete a table? ā–¼

Use DROP TABLE to delete a table permanently:
DROP TABLE IF EXISTS students;

āš ļø Warning: This deletes ALL data in the table. There's no undo!

šŸ¤” What's a FOREIGN KEY? ā–¼

A FOREIGN KEY is a column that links to another table's primary key. It creates a relationship between tables.

Example: In an orders table, customer_id is a foreign key that points to customers(customer_id). This tells MySQL that each order belongs to a customer.

It ensures data integrity – you can't add an order for a customer that doesn't exist.

šŸ¤” How many tables can a database have? ā–¼

Technically, MySQL can have up to 4,294,967,295 tables per database. But in practice, you'll only need a few dozen for most applications.

A well-designed database for a medium-sized application might have 10-50 tables.

ā¬…ļø Previous: Create Database Next: Insert Data →