Python MySQL Create Table
In this page:
cursor.execute("CREATE TABLE table_name (column1 type, column2 type)")
Basic Table Creation
cursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))") defines a new table with three columns: an auto-incrementing integer primary key, and two text columns for name and address.
Example: Basic Table Creation
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, " # auto-incrementing primary key
"name VARCHAR(255), address VARCHAR(255))"
)
print("Table created")
Choosing Column Data Types
MySQL offers specific column types for different kinds of data -- INT for whole numbers, VARCHAR(n) for variable-length text up to n characters, TEXT for longer text, DATE/DATETIME for dates, and DECIMAL for exact-precision numbers like currency.
Example: Choosing Column Data Types
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE orders (id INT, price DECIMAL(10,2), placed_on DATE)" # DECIMAL for exact-precision currency values
)
print("DECIMAL used for money, not FLOAT")
Checking If a Table Already Exists
CREATE TABLE IF NOT EXISTS tableName (...) is the table-level equivalent of CREATE DATABASE IF NOT EXISTS -- it silently does nothing if a table with that name already exists, instead of raising an error, which is useful in repeatable setup scripts.
Example: Checking If a Table Already Exists
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT PRIMARY KEY)") # no error if the table already exists
print("Safe to run more than once")
Using SHOW TABLES to Confirm Creation
cursor.execute("SHOW TABLES") followed by iterating over the cursor lists every table in the currently selected database, a quick way to confirm a CREATE TABLE statement actually succeeded.
Example: Using SHOW TABLES to Confirm Creation
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SHOW TABLES") # lists every table in the current database
cursor.__iter__.return_value = iter([("customers",), ("orders",)])
for table in cursor:
print(table)
Foreign Keys and Table Relationships
A FOREIGN KEY constraint links a column in one table to the primary key of another, enforcing referential integrity -- MySQL will reject an insert that references a non-existent parent row, keeping related tables consistent with each other.
Example: Foreign Keys and Table Relationships
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, "
"FOREIGN KEY (customer_id) REFERENCES customers(id))" # enforces that customer_id must reference a real customer
)
print("orders.customer_id must reference an existing customers.id")
- Forgetting to specify a PRIMARY KEY column, which makes it harder to uniquely identify and later update or delete individual rows.
- Mismatching Python data types and MySQL column types -- for instance storing very large numbers in an INT column, which has a fixed maximum size.
- Running CREATE TABLE against a connection that is not pointed at any specific database, causing a 'No database selected' error.
- cursor.execute("CREATE TABLE name (...)") creates a new table with the given column definitions.
- Every table generally needs a PRIMARY KEY column to uniquely identify each row.
- AUTO_INCREMENT makes an integer primary key generate its own value automatically for each new row.
CREATE TABLE syntax is standard MySQL SQL, executed identically across all Python driver versions.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Python MySQL Get Started
- Python MySQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python MySQL Select From Table
- Python MySQL Select With a Filter
- Python MySQL Order By
- Python MySQL Delete Record
- Python MySQL Drop Table
- Python MySQL Update Table
- Python MySQL Limit
- Python MySQL Join