MySQL Basics and Python Integration Guide
MySQL Basics and Python Integration Guide
● Definition: An RDBMS organizes data into related tables with rows and columns. It uses
SQL (Structured Query Language) to manage and query data.
● Features:
○ Structured Data: Data is stored in tables, where each table has a specific schema.
○ Relationships: Tables can relate to each other via primary keys and foreign
keys.
○ ACID Compliance: Ensures atomicity, consistency, isolation, and durability of
transactions.
○ Data Integrity: Enforces constraints like unique, not null, and foreign key
relationships.
MySQL as an RDBMS:
2. Normalization:
Normalization is a database design process to reduce redundancy and improve data integrity by
organizing data into smaller, related tables.
● Normalization Levels:
○ 1NF (First Normal Form): Eliminate repeating groups by ensuring each column
contains atomic (indivisible) values.
○ 2NF (Second Normal Form): Remove partial dependencies by ensuring all
non-key attributes are fully functionally dependent on the primary key.
○ 3NF (Third Normal Form): Remove transitive dependencies (non-key attributes
depending on other non-key attributes).
○ BCNF (Boyce-Codd Normal Form): A stricter version of 3NF, ensuring no
anomalies arise from functional dependencies.
● Example of Normalization:
Unnormalized Table:
OrderID | CustomerName | ProductName | Quantity
------------------------------------------------
1 | John Doe | Widget A | 10
1 | John Doe | Widget B | 5
Normalized Structure:
Orders Table:
OrderID | CustomerName
----------------------
1 | John Doe
OrderDetails Table:
OrderID | ProductName | Quantity
---------------------------------
1 | Widget A | 10
1 | Widget B | 5
3. Database Models:
Database models describe how data is structured, stored, and retrieved. Key models include:
● Relational Model: Organizes data into tables (used by RDBMS like MySQL).
● Hierarchical Model: Data is stored in a tree-like structure (used in XML databases).
● Network Model: Data is organized in a graph structure (used in legacy systems).
● Document Model: Semi-structured data is stored as documents (e.g., JSON, XML).
MySQL Database Model:
● MySQL follows the relational model, using tables, rows, and columns.
● Relationships are defined via primary keys (unique identifiers) and foreign keys
(references to other tables).
4. Database Structures:
● Logical Structure:
○ Tables: Core data storage units.
○ Views: Virtual tables based on SQL queries.
○ Indexes: Improve query performance.
○ Stored Procedures: Encapsulate reusable SQL logic.
○ Triggers: Automate actions based on events.
● Physical Structure:
○ Data is stored in files on disk.
○ MySQL storage engines (e.g., InnoDB, MyISAM) manage how data is stored and
retrieved.
■ InnoDB: Supports transactions, foreign keys, and row-level locking.
■ MyISAM: Optimized for read-heavy workloads, but lacks ACID
compliance.
1. Creating a Database:
2. Creating a Table:
3. Inserting Data:
4. Querying Data:
5. Joining Tables:
1. Tables
● Definition: A view is a virtual table based on a SQL query. It does not store data itself
but presents data dynamically from the underlying tables.
● Advantages:
○ Simplifies complex queries.
○ Enhances security by limiting access to specific columns or rows.
3. Indexes
4. Constraints
● Definition: Constraints enforce rules at the table and column level to ensure data
integrity.
● Types of Constraints in MySQL:
○ PRIMARY KEY: Uniquely identifies each record.
○ FOREIGN KEY: Enforces referential integrity between two tables.
○ NOT NULL: Ensures a column cannot store NULL values.
○ UNIQUE: Ensures all values in a column are unique.
○ CHECK: Ensures a column satisfies a specific condition.
○ DEFAULT: Assigns a default value to a column if none is provided.
Example:
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50) UNIQUE NOT NULL,
ManagerID INT,
CONSTRAINT fk_manager FOREIGN KEY (ManagerID) REFERENCES
Employees(EmployeeID)
);
5. Data Types
Examples:
CREATE TABLE Products (
ProductID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(100),
Price DECIMAL(10, 2),
ManufactureDate DATE
);
6. Operators
● Arithmetic Operators:
○ +, -, *, /, %
Example:
SELECT Price * Quantity AS TotalCost FROM Orders;
● Comparison Operators:
○ =, !=, <>, <, <=, >, >=
Example:
SELECT * FROM Employees WHERE Salary > 50000;
● Logical Operators:
○ AND, OR, NOT
Example:
● Bitwise Operators:
○ &, |, ^, ~, <<, >>
Example:
SELECT 5 & 3 AS BitwiseAnd;
● String Operators:
○ CONCAT(), LIKE, INSTR()
Example:
SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM
Employees;
● Set Operators:
○ UNION, UNION ALL, INTERSECT, EXCEPT
Example:
SELECT Name FROM Employees WHERE Position = 'Manager'
UNION
SELECT Name FROM Employees WHERE Salary > 80000;
Putting It All Together
Data Definition Language (DDL) is a set of SQL commands used to define, modify, and
manage the structure of database objects such as tables, views, indexes, and schemas. DDL
statements do not manipulate the data within the database; they focus on the schema and
structural aspects.
Here’s a breakdown of the most commonly used DDL commands with examples:
1. CREATE
The CREATE statement is used to create new database objects, such as databases, tables, views,
or indexes.
Create a Database:
CREATE DATABASE SchoolDB;
Create a Table:
CREATE TABLE Students (
StudentID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT,
Major VARCHAR(50)
);
Create a View:
CREATE VIEW CS_Students AS
SELECT Name, Major
FROM Students
WHERE Major = 'Computer Science';
Create an Index:
CREATE INDEX idx_major ON Students (Major);
2. ALTER
The ALTER statement is used to modify the structure of an existing table or other database
objects.
The DROP statement is used to delete database objects permanently, including databases, tables,
views, or indexes.
Drop a Database:
DROP DATABASE SchoolDB;
Drop a Table:
DROP TABLE Students;
Drop a View:
DROP VIEW CS_Students;
Drop an Index:
DROP INDEX idx_major ON Students;
4. TRUNCATE
The TRUNCATE statement is used to delete all rows from a table while retaining its structure.
This is faster than DELETE since it does not log each row deletion.
Example:
TRUNCATE TABLE Students;
5. RENAME
Rename a Table:
RENAME TABLE Students TO Alumni;
USE LibraryDB;
1. Plan Before Altering: Changes to schema should be carefully planned as they may
impact the application using the database.
2. Backup Before Dropping: Always create a backup before using DROP or TRUNCATE
commands.
3. Use Constraints: Enforce integrity by using constraints (e.g., NOT NULL, UNIQUE,
FOREIGN KEY).
4. Avoid Frequent Alterations: Repeatedly altering tables can degrade performance.
Data Manipulation Language (DML) commands are used to interact with the data stored in a
database. They allow you to retrieve, insert, update, and delete data within database tables.
1. INSERT
The INSERT statement is used to add new rows to a table.
Syntax:
INSERT INTO table_name (column1, column2, ...) VALUES (value1,
value2, ...);
Examples: Insert a Single Row:
INSERT INTO Employees (Name, Position, Salary)
VALUES ('John Doe', 'Manager', 75000);
Insert Multiple Rows:
INSERT INTO Employees (Name, Position, Salary)
VALUES
('Alice Smith', 'Developer', 60000),
('Bob Brown', 'Analyst', 55000);
2. SELECT
The SELECT statement is used to retrieve data from one or more tables.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Examples: Retrieve All Columns:
SELECT * FROM Employees;
Retrieve Specific Columns:
SELECT Name, Salary FROM Employees;
Filter Rows:
SELECT Name, Salary
FROM Employees
WHERE Salary > 60000;
Order Results:
SELECT Name, Salary
FROM Employees
ORDER BY Salary DESC;
3. UPDATE
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Examples: Update a Single Row:
UPDATE Employees
SET Salary = 80000
WHERE Name = 'John Doe';
Update Multiple Rows:
UPDATE Employees
SET Salary = Salary + 5000
WHERE Position = 'Developer';
4. DELETE
Syntax:
DELETE FROM table_name WHERE condition;
Examples: Delete a Specific Row:
DELETE FROM Employees
WHERE Name = 'Bob Brown';
Delete Multiple Rows:
DELETE FROM Employees
WHERE Salary < 50000;
Delete All Rows (Keep Table Structure):
DELETE FROM Employees;
Transactions
Transactions ensure that a series of DML operations are treated as a single unit of work. They
maintain data integrity and consistency.
● Key Commands:
○ START TRANSACTION: Begins a transaction.
○ COMMIT: Saves changes made in the transaction.
○ ROLLBACK: Reverts changes made in the transaction.
Example:
START TRANSACTION;
Example:
SELECT [Link], [Link]
FROM Employees
INNER JOIN Departments
ON [Link] = [Link];
Using Subqueries
Example:
SELECT Name
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
1. Use Transactions for Critical Updates: To ensure data consistency, wrap critical DML
commands in transactions.
2. Test with SELECT Before Running Updates/Deletes:
Example:
-- Test
SELECT * FROM Employees WHERE Salary < 50000;
-- Then execute
DELETE FROM Employees WHERE Salary < 50000;
○
3. Avoid Omitting WHERE Clause: Ensure WHERE conditions are used with UPDATE and
DELETE to avoid unintentional changes.
4. Use Batching for Large Data Loads: For inserting/updating a large volume of data,
process in batches to avoid performance issues.
Queries in MySQL are commands that interact with the database to retrieve, insert, update, or
delete data. A subquery is a query nested inside another query, used to perform complex
filtering, comparisons, or calculations.
Types of Queries
Subqueries in MySQL
1. Types of Subqueries
Example:
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Example:
SELECT Department, AVG(Salary) AS AvgSalary
FROM (SELECT Department, Salary FROM Employees WHERE Salary >
50000) AS HighEarners
GROUP BY Department;
Example:
SELECT Name,
(SELECT DepartmentName FROM Departments WHERE
[Link] = [Link]) AS Department
FROM Employees;
Example:
SELECT Name
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments
WHERE Location = 'New York');
●
○ Finds employees working in New York-based departments.
Example:
SELECT Name
FROM Employees
WHERE EXISTS (SELECT 1 FROM Departments WHERE
[Link] = [Link] AND Location =
'London');
○ Finds employees in departments located in London.
6. Correlated Subquery
Example:
SELECT Name, Salary
FROM Employees e1
WHERE Salary > (SELECT AVG(Salary) FROM Employees e2 WHERE
[Link] = [Link]);
○ Finds employees earning more than the average salary in their department.
Example:
SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department
HAVING SUM(Salary) > (SELECT SUM(Salary) FROM Employees WHERE
Department = 'HR');
○ Finds departments where the total salary exceeds the HR department’s total salary.
Example:
UPDATE Employees
SET Salary = Salary * 1.10
WHERE DepartmentID = (SELECT DepartmentID FROM Departments WHERE
DepartmentName = 'Sales');
●
○ Gives a 10% salary raise to employees in the Sales department.
Example:
DELETE FROM Employees
WHERE DepartmentID NOT IN (SELECT DepartmentID FROM
Departments);
●
○ Deletes employees whose department no longer exists.
Performance Can be slower for large datasets. Usually faster with proper indexes.
Readability Easier to read for simple use cases. More complex but better for
multi-table ops.
6. Joins
In MySQL, joins are used to combine rows from two or more tables based on related columns.
Joins are one of the most powerful and frequently used features of SQL, enabling you to retrieve
data spread across multiple tables in a relational database.
1. INNER JOIN
2. LEFT JOIN (LEFT OUTER JOIN)
3. RIGHT JOIN (RIGHT OUTER JOIN)
4. FULL JOIN (FULL OUTER JOIN) - Not directly supported in MySQL but can be
simulated.
5. CROSS JOIN
6. SELF JOIN
1. INNER JOIN
● Combines rows from two tables when there is a match in the specified columns.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON [Link] = [Link];
Example:
SELECT [Link], [Link]
FROM Employees
INNER JOIN Departments
ON [Link] = [Link];
○ Retrieves employees and their department names for rows where there is a
matching DepartmentID.
● Returns all rows from the left table, and the matched rows from the right table. If no
match exists, NULL is returned for columns from the right table.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON [Link] = [Link];
Example:
SELECT [Link], [Link]
FROM Employees
LEFT JOIN Departments
ON [Link] = [Link];
● Returns all rows from the right table, and the matched rows from the left table. If no
match exists, NULL is returned for columns from the left table.
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON [Link] = [Link];
Example:
SELECT [Link], [Link]
FROM Employees
RIGHT JOIN Departments
ON [Link] = [Link];
● Combines results of both LEFT JOIN and RIGHT JOIN. Rows with no match in either
table will have NULL in columns from the other table.
● Note: MySQL does not support FULL JOIN directly but it can be simulated using
UNION.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON [Link] = [Link]
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON [Link] = [Link];
Example:
SELECT [Link], [Link]
FROM Employees
LEFT JOIN Departments
ON [Link] = [Link]
UNION
SELECT [Link], [Link]
FROM Employees
RIGHT JOIN Departments
ON [Link] = [Link];
5. CROSS JOIN
● Returns the Cartesian product of two tables. Every row from the first table is combined
with every row from the second table.
Syntax:
SELECT columns
FROM table1
CROSS JOIN table2;
Example:
SELECT [Link], [Link]
FROM Employees
CROSS JOIN Departments;
6. SELF JOIN
● A table is joined with itself to compare rows within the same table.
Syntax:
SELECT A.column1, B.column2
FROM table_name A, table_name B
WHERE condition;
Example:
SELECT [Link] AS Employee1, [Link] AS Employee2
FROM Employees E1
INNER JOIN Employees E2
ON [Link] = [Link];
○ Retrieves employees and their managers from the same Employees table.
1. Index Key Columns: Ensure the columns used in ON or WHERE conditions are indexed.
2. Minimize Data in Joins: Use only the columns you need.
3. Use Appropriate Joins: Avoid unnecessary joins; use the most efficient join type for
your query.
4. Analyze Execution Plans: Use EXPLAIN to understand how MySQL processes your
join query.
5. Filter Early: Use WHERE or ON clauses to filter data before performing the join.
MySQL Connector is a Python library used to interact with MySQL databases. It allows Python
programs to connect to a MySQL database, execute SQL queries, and retrieve data.
1. Installation
To install the MySQL Connector for Python, you can use pip:
Syntax:
import [Link]
db_connection = [Link](
host="hostname", # e.g., 'localhost'
user="username", # MySQL username
password="password", # MySQL password
database="database_name" # The database you want to connect
to
)
● Example:
import [Link]
Once the connection is established, you can use a cursor object to execute SQL queries. The
cursor is responsible for executing queries and retrieving results.
import [Link]
# Establishing a connection
db_connection = [Link](
host="localhost",
user="root",
password="your_password",
database="employees"
)
# Fetching results
results = [Link]()
for row in results:
print(row)
import [Link]
# Establishing a connection
db_connection = [Link](
host="localhost",
user="root",
password="your_password",
database="employees"
)
import [Link]
# Establishing a connection
db_connection = [Link](
host="localhost",
user="root",
password="your_password",
database="employees"
)
# Fetching results
results = [Link]()
for row in results:
print(row)
When you perform insert, update, or delete operations, you need to commit the transaction to
save the changes to the database.
db_connection.commit()
If you want to roll back any changes that haven't been committed yet, you can use:
db_connection.rollback()
It is important to handle exceptions that may arise during database operations. You can use
try-except blocks to catch errors such as connection issues or query syntax errors.
import [Link]
from [Link] import Error
try:
db_connection = [Link](
host="localhost",
user="root",
password="your_password",
database="employees"
)
cursor = db_connection.cursor()
[Link]("SELECT * FROM NonExistentTable")
except Error as e:
print(f"Error: {e}")
finally:
if db_connection.is_connected():
[Link]()
db_connection.close()
Always close the connection and cursor when done to free up resources.
[Link]()
db_connection.close()
Useful Tips
To use MySQL Connector in Python, you need to first install the connector module and then
import it into your Python script. Here’s how you can do it:
To install the MySQL Connector module, you can use the pip package manager.
Open your command-line terminal or command prompt and run the following command:
Once the library is installed, you can import it into your Python script to start interacting with
MySQL databases.
import [Link]
Now, you can use the [Link] module to establish connections, execute SQL
queries, and fetch results.
Verifying Installation
To verify that the connector is correctly installed, you can try to connect to a MySQL database
and execute a simple query. Here's a quick example:
import [Link]
This code will confirm if the connector is installed and working correctly by attempting to
connect to the database.
Here’s a complete example of how to use the connect(), cursor(), execute(), and
fetchall() methods to interact with a MySQL database using the MySQL Connector for
Python.
Steps:
Example:
import [Link]
Explanation of Steps:
1. connect(): This method establishes a connection to your MySQL database with the
provided credentials and database name.
2. cursor(): The cursor object is used to execute SQL queries.
3. execute(): Executes the provided SQL query. In this example, it selects all rows from
the Employees table.
4. fetchall(): Retrieves all rows of the query result and returns them as a list of tuples.
Each tuple represents a row of data.
5. Loop through results: Iterate through the result set and print each row.
6. Closing resources: Always close the cursor and database connection when done.
Notes:
● You can replace the SQL query with any valid SELECT query based on your database
structure.
● fetchall() retrieves all rows returned by the query, but if you're expecting large
result sets, consider using fetchone() (for single rows) or fetchmany(n) (for
multiple rows).
1. MySQLdb (MySQL-python)
MySQLdb is one of the oldest and most commonly used libraries to connect Python with
MySQL. It is part of the MySQL-python package, but it may require additional installation
steps.
Installation:
Example:
import MySQLdb
# Establishing a connection
db_connection = [Link](
host="localhost",
user="root",
passwd="your_password",
db="test_db"
)
# Executing a query
[Link]("SELECT * FROM Employees")
2. PyMySQL
PyMySQL is a pure-Python MySQL client, which is simpler to install and use, and works
similarly to mysql-connector-python.
Installation:
pip install PyMySQL
Example:
import pymysql
# Establishing a connection
db_connection = [Link](
host="localhost",
user="root",
password="your_password",
database="test_db"
)
# Executing a query
[Link]("SELECT * FROM Employees")
Installation:
For MySQL support, you need to install the MySQL driver (like PyMySQL or mysqlclient):
# Establishing a connection
db_connection = [Link]()
# Executing a query
result = db_connection.execute("SELECT * FROM Employees")
Installation:
# Define a model
class Employee([Link]):
id = [Link]([Link], primary_key=True)
name = [Link]([Link](100))
position = [Link]([Link](100))
# Query the database
@[Link]('/')
def index():
employees = [Link]()
for employee in employees:
print(f'{[Link]}, {[Link]}')
return "Check your console for employee data!"
if __name__ == '__main__':
[Link](debug=True)
For asynchronous applications (using asyncio), you can use Tortoise ORM. It's an
asynchronous ORM that works well with databases, including MySQL.
Installation:
Example:
# Define a model
class Employee(Model):
id = [Link](pk=True)
name = [Link](max_length=255)
position = [Link](max_length=255)
# Fetch data
employees = await [Link]()
for employee in employees:
print(f'{[Link]}, {[Link]}')
await Tortoise.close_connections()
If you are working with Django, the framework has its own ORM that simplifies MySQL (and
other databases) integration.
Installation:
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'test_db',
'USER': 'root',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '3306',
}
}
Then, you can use Django’s ORM to interact with the MySQL database, defining models and
performing queries like: