Okay, let's learn SQL and SQLite using Python. This will be a hands-on approach.
What We'll Cover:
- What is SQL and SQLite? (Brief introduction)
- Setting up your Environment (Python and SQLite)
- Connecting to a Database
- Creating a Table
- Inserting Data
- Querying Data (SELECT)
- Filtering Data (WHERE)
- Sorting Data (ORDER BY)
- Updating Data (UPDATE)
- Deleting Data (DELETE)
- Aggregations (COUNT, SUM, AVG, MIN, MAX)
- Grouping Data (GROUP BY)
- Joining Tables
- Parameterized Queries (Important for Security)
- Error Handling
- Transactions
- Committing and Closing Connections
1. What is SQL and SQLite?
-
SQL (Structured Query Language): A standard language for interacting with relational databases. It's used to create, read, update, and delete data. SQL is declarative, meaning you tell the database what you want, not how to get it.
-
SQLite: A lightweight, file-based database. It's serverless, meaning you don't need a separate database server to run it. It stores the entire database in a single file on your hard drive. SQLite is great for small to medium-sized applications, embedded systems, and local data storage. Because it doesn't require a server, it's very easy to set up and use.
2. Setting Up Your Environment
- Python: You'll need Python installed. If you don't have it, download it from https://www.python.org/downloads/ (I recommend Python 3.7 or newer).
- SQLite Module (sqlite3): The
sqlite3 module is typically included with Python installations. You usually don't need to install it separately. You can verify it's working by opening a Python interpreter and typing import sqlite3. If no error occurs, you're good to go.
3. Connecting to a Database
Let's start by connecting to an SQLite database. If the database file doesn't exist, SQLite will create it for you.
import sqlite3
# Define the database file name
db_file = "my_database.db" # Or any name you prefer
try:
# Connect to the database (creates it if it doesn't exist)
conn = sqlite3.connect(db_file)
print(f"Connected to database: {db_file}")
# Create a cursor object to execute SQL commands
cursor = conn.cursor() #important, because it's what interacts with the db
# You can start interacting with the database here.
# We'll add more code in the next steps.
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
# Ensure the connection is closed, even if errors occur.
if conn:
conn.close()
print("Connection closed.")
Explanation:
import sqlite3: Imports the SQLite module.
db_file = "my_database.db": Specifies the name of your database file.
conn = sqlite3.connect(db_file): Creates a connection to the database. If my_database.db doesn't exist, it will be created.
cursor = conn.cursor(): Creates a cursor object. The cursor is used to execute SQL commands.
conn.close(): Closes the database connection. Important: Always close the connection when you're finished with it to release resources. The finally block ensures that the connection is closed, even if an error occurs.
Run this code. It should print "Connected to database: my_database.db" and "Connection closed." If you look in the same directory as your Python script, you should now see a file named my_database.db.
4. Creating a Table
Now, let's create a table to store some data. We'll create a table named employees with columns for id, name, department, and salary.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to create the table
create_table_sql = """
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT,
salary REAL
);
"""
# Execute the SQL command
cursor.execute(create_table_sql)
conn.commit() # VERY IMPORTANT. Saves the changes to the database.
print("Table 'employees' created successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
create_table_sql: Contains the SQL command to create the table. Let's break down the SQL:
CREATE TABLE IF NOT EXISTS employees: Creates a table named employees if it doesn't already exist.
id INTEGER PRIMARY KEY: Creates a column named id with an integer data type. PRIMARY KEY means that each value in this column must be unique, and it's often used as the main identifier for each row in the table.
name TEXT NOT NULL: Creates a column named name with a text data type. NOT NULL means that this column cannot be left empty when inserting data.
department TEXT: Creates a column named department with a text data type.
salary REAL: Creates a column named salary with a floating-point number data type (for storing salaries with decimal places).
cursor.execute(create_table_sql): Executes the SQL command.
conn.commit(): Crucial! This saves the changes you made to the database. If you don't call commit(), the table won't be created.
Run this code. It should print "Table 'employees' created successfully." You can use a SQLite browser (like DB Browser for SQLite, available for free download) to open my_database.db and confirm that the employees table has been created. A SQLite browser is highly recommended for visually inspecting your database structure and data.
5. Inserting Data
Let's insert some data into the employees table.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to insert data
insert_sql = """
INSERT INTO employees (id, name, department, salary)
VALUES (?, ?, ?, ?); -- Use placeholders to prevent SQL injection
"""
# Data to insert
employees = [
(1, "Alice Smith", "Sales", 50000.00),
(2, "Bob Johnson", "Marketing", 60000.00),
(3, "Charlie Brown", "Engineering", 75000.00)
]
# Insert the data using executemany for efficiency
cursor.executemany(insert_sql, employees)
conn.commit()
print(f"{len(employees)} employees inserted successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
insert_sql: Contains the SQL command to insert data. Notice the ? placeholders. These are crucial for security (preventing SQL injection). We'll discuss parameterized queries more later.
employees: A list of tuples, where each tuple represents a row of data to insert. The order of the values in the tuple must match the order of the columns in the INSERT INTO statement.
cursor.executemany(insert_sql, employees): Executes the insert_sql command multiple times, once for each tuple in the employees list. This is more efficient than calling cursor.execute() repeatedly.
conn.commit(): Saves the changes to the database.
Run this code. It should print "3 employees inserted successfully." Open my_database.db in your SQLite browser and you should see the data in the employees table.
6. Querying Data (SELECT)
Now, let's retrieve data from the table using the SELECT statement.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to select all data from the employees table
select_sql = "SELECT * FROM employees;"
# Execute the SQL command
cursor.execute(select_sql)
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row) # Each row is a tuple
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql = "SELECT * FROM employees;": This SQL command selects all columns (*) from the employees table.
cursor.execute(select_sql): Executes the SQL command.
rows = cursor.fetchall(): Fetches all the rows returned by the query and stores them in a list of tuples. Each tuple represents a row.
- The
for loop iterates through the rows list and prints each row.
Run this code. It should print each row from the employees table.
7. Filtering Data (WHERE)
The WHERE clause is used to filter data based on specific conditions. Let's select only the employees in the "Sales" department.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to select employees from the Sales department
select_sql = "SELECT * FROM employees WHERE department = 'Sales';"
# Execute the SQL command
cursor.execute(select_sql)
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row)
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql = "SELECT * FROM employees WHERE department = 'Sales';": The WHERE department = 'Sales' clause filters the results to include only rows where the department column is equal to "Sales".
Run this code. It should print only the row for Alice Smith.
You can use other comparison operators in the WHERE clause, such as:
=: Equal to
!= or <>: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
LIKE: Pattern matching (e.g., WHERE name LIKE 'A%' to find names starting with "A")
IN: Checks if a value is in a list (e.g., WHERE department IN ('Sales', 'Marketing'))
BETWEEN: Checks if a value is within a range (e.g., WHERE salary BETWEEN 50000 AND 65000)
IS NULL: Checks if a value is NULL (we don't have any NULL values in our current data)
IS NOT NULL: Checks if a value is not NULL
You can also combine multiple conditions using AND and OR:
WHERE department = 'Sales' AND salary > 50000: Employees in the Sales department and with a salary greater than 50000.
WHERE department = 'Sales' OR department = 'Marketing': Employees in either the Sales or Marketing department.
8. Sorting Data (ORDER BY)
The ORDER BY clause is used to sort the results of a query. Let's select all employees and sort them by salary in descending order.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to select all employees and sort by salary in descending order
select_sql = "SELECT * FROM employees ORDER BY salary DESC;"
# Execute the SQL command
cursor.execute(select_sql)
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row)
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql = "SELECT * FROM employees ORDER BY salary DESC;": The ORDER BY salary DESC clause sorts the results by the salary column in descending order (DESC). To sort in ascending order (the default), use ORDER BY salary ASC or just ORDER BY salary.
Run this code. The employees will be printed with Charlie Brown first, then Bob, then Alice.
You can also sort by multiple columns. For example, ORDER BY department, salary DESC would sort by department in ascending order, and then within each department, sort by salary in descending order.
9. Updating Data (UPDATE)
The UPDATE statement is used to modify existing data in a table. Let's update Bob Johnson's salary to 65000.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to update Bob Johnson's salary
update_sql = """
UPDATE employees
SET salary = 65000.00
WHERE name = 'Bob Johnson';
"""
# Execute the SQL command
cursor.execute(update_sql)
conn.commit()
print("Salary updated successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
update_sql: Contains the SQL command to update the data.
UPDATE employees: Specifies the table to update.
SET salary = 65000.00: Sets the salary column to 65000.00.
WHERE name = 'Bob Johnson': Specifies the condition to identify the row to update (in this case, the row where the name is "Bob Johnson"). Important: Always use a WHERE clause in an UPDATE statement, or you'll update all rows in the table!
conn.commit(): Saves the changes to the database.
Run this code. It should print "Salary updated successfully." You can then query the table to verify that Bob Johnson's salary has been updated.
10. Deleting Data (DELETE)
The DELETE statement is used to remove data from a table. Let's delete Charlie Brown from the employees table.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to delete Charlie Brown from the employees table
delete_sql = """
DELETE FROM employees
WHERE name = 'Charlie Brown';
"""
# Execute the SQL command
cursor.execute(delete_sql)
conn.commit()
print("Employee deleted successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
delete_sql: Contains the SQL command to delete the data.
DELETE FROM employees: Specifies the table to delete from.
WHERE name = 'Charlie Brown': Specifies the condition to identify the row to delete. Important: Always use a WHERE clause in a DELETE statement, or you'll delete all rows in the table!
conn.commit(): Saves the changes to the database.
Run this code. It should print "Employee deleted successfully." You can then query the table to verify that Charlie Brown has been removed.
11. Aggregations (COUNT, SUM, AVG, MIN, MAX)
Aggregation functions calculate a single value from a set of rows.
COUNT(): Counts the number of rows.
SUM(): Calculates the sum of values in a column.
AVG(): Calculates the average of values in a column.
MIN(): Finds the minimum value in a column.
MAX(): Finds the maximum value in a column.
Let's calculate the average salary of all employees.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to calculate the average salary
select_sql = "SELECT AVG(salary) FROM employees;"
# Execute the SQL command
cursor.execute(select_sql)
# Fetch the result
average_salary = cursor.fetchone()[0] # fetchone() returns a tuple
print(f"Average salary: {average_salary}")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql = "SELECT AVG(salary) FROM employees;": The AVG(salary) function calculates the average salary.
average_salary = cursor.fetchone()[0]: cursor.fetchone() returns a tuple containing the result of the aggregation function. We access the first element of the tuple (index 0) to get the average salary value.
Run this code. It should print the average salary.
Here are some more examples:
SELECT COUNT(*) FROM employees: Counts the total number of employees.
SELECT SUM(salary) FROM employees WHERE department = 'Sales': Calculates the total salary of employees in the Sales department.
SELECT MIN(salary) FROM employees: Finds the lowest salary.
SELECT MAX(salary) FROM employees: Finds the highest salary.
12. Grouping Data (GROUP BY)
The GROUP BY clause is used to group rows that have the same value in one or more columns. It's often used in conjunction with aggregation functions.
Let's calculate the average salary for each department.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to calculate the average salary for each department
select_sql = """
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
"""
# Execute the SQL command
cursor.execute(select_sql)
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
department, average_salary = row
print(f"Department: {department}, Average Salary: {average_salary}")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql: Contains the SQL command to group the data and calculate the average salary.
SELECT department, AVG(salary): Selects the department and the average salary.
FROM employees: Specifies the table.
GROUP BY department: Groups the rows by the department column. The AVG(salary) function is then applied to each group, calculating the average salary for each department.
Run this code. It will print the average salary for each department in your employees table.
You can use HAVING to filter the groups after the GROUP BY operation. For example, to find departments with an average salary greater than 60000:
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;
13. Joining Tables
Joins are used to combine data from two or more tables based on a related column. To demonstrate this, let's create another table called departments and then join it with the employees table.
First, let's add some sample department data:
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Create the departments table
create_departments_sql = """
CREATE TABLE IF NOT EXISTS departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
location TEXT
);
"""
cursor.execute(create_departments_sql)
# Insert some department data
insert_departments_sql = """
INSERT INTO departments (id, name, location)
VALUES (?, ?, ?);
"""
departments = [
(1, "Sales", "New York"),
(2, "Marketing", "Los Angeles"),
(3, "Engineering", "San Francisco")
]
cursor.executemany(insert_departments_sql, departments)
conn.commit()
# Add a department_id column to the employees table
alter_table_sql = "ALTER TABLE employees ADD COLUMN department_id INTEGER;"
cursor.execute(alter_table_sql)
# Update the employees table with department_id based on department name
update_employees_sql = """
UPDATE employees
SET department_id = (
SELECT id
FROM departments
WHERE departments.name = employees.department
);
"""
cursor.execute(update_employees_sql)
conn.commit()
# Remove the original 'department' column
remove_department_column_sql = "ALTER TABLE employees DROP COLUMN department;"
cursor.execute(remove_department_column_sql)
conn.commit()
print("Departments table created and joined with employees table.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Important: This code changes the structure of your employees table!
Now, let's perform a join to get the employee name and the location of their department:
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to join the tables
select_sql = """
SELECT employees.name, departments.location
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
"""
# Execute the SQL command
cursor.execute(select_sql)
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
employee_name, department_location = row
print(f"Employee: {employee_name}, Location: {department_location}")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
select_sql: Contains the SQL command to join the tables.
SELECT employees.name, departments.location: Selects the name column from the employees table and the location column from the departments table. We use the table name as a prefix to disambiguate the columns (e.g., employees.name).
FROM employees INNER JOIN departments ON employees.department_id = departments.id: Specifies the tables to join (employees and departments) and the join condition (employees.department_id = departments.id). The INNER JOIN ensures that only rows where the join condition is met are included in the result. Rows in either table without a matching ID in the other table will not be included.
Types of Joins:
INNER JOIN: Returns rows only when there is a match in both tables. (This is the most common type of join.)
LEFT JOIN: Returns all rows from the left table (the table before the LEFT JOIN keyword) and matching rows from the right table. If there is no match in the right table, the columns from the right table will be NULL.
RIGHT JOIN: Returns all rows from the right table and matching rows from the left table. If there is no match in the left table, the columns from the left table will be NULL. (Note: RIGHT JOIN is not fully supported in SQLite, so you can use LEFT JOIN and swap the table order instead).
FULL OUTER JOIN: Returns all rows when there is a match in either table. (Note: FULL OUTER JOIN is also not fully supported in SQLite. You can simulate it using UNION ALL with LEFT JOIN and RIGHT JOIN.)
14. Parameterized Queries (Important for Security)
Parameterized queries are essential for preventing SQL injection vulnerabilities. SQL injection occurs when user input is directly inserted into an SQL query, potentially allowing attackers to execute arbitrary SQL code.
Instead of directly embedding values into the SQL string, you use placeholders and pass the values as separate arguments to the execute() method. The database driver then handles escaping and quoting the values correctly, preventing SQL injection.
Here's how to use parameterized queries for inserting data:
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command with placeholders
insert_sql = """
INSERT INTO employees (name, department_id, salary)
VALUES (?, ?, ?);
"""
# Data to insert (using variables)
name = "Eve Williams"
department_id = 1
salary = 55000.00
# Execute the SQL command with the values as a tuple
cursor.execute(insert_sql, (name, department_id, salary))
conn.commit()
print("Employee inserted successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
Explanation:
insert_sql: Contains the SQL command with ? placeholders.
cursor.execute(insert_sql, (name, department_id, salary)): The values are passed as a tuple to the execute() method. The sqlite3 module will automatically escape the values to prevent SQL injection.
Always use parameterized queries when working with user input or any data that might be untrusted.
15. Error Handling
It's crucial to handle database errors gracefully. The sqlite3 module raises exceptions for various error conditions. We've already been using try...except blocks for error handling. Here are some common SQLite exceptions:
sqlite3.Error: Base class for all SQLite exceptions.
sqlite3.DatabaseError: Errors related to the database itself (e.g., corruption).
sqlite3.OperationalError: Errors related to database operations (e.g., table not found, locked database).
sqlite3.IntegrityError: Errors related to data integrity constraints (e.g., unique constraint violation).
sqlite3.ProgrammingError: Errors related to programming mistakes (e.g., incorrect SQL syntax).
Example: Handling a unique constraint violation
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# SQL command to insert data (attempt to insert a duplicate ID)
insert_sql = """
INSERT INTO employees (id, name, department_id, salary)
VALUES (?, ?, ?, ?);
"""
# Data to insert (duplicate ID)
id = 1 # Assuming ID 1 already exists
name = "Duplicate Employee"
department_id = 2
salary = 45000.00
# Execute the SQL command
cursor.execute(insert_sql, (id, name, department_id, salary))
conn.commit()
print("Employee inserted successfully.")
except sqlite3.IntegrityError as e:
print(f"Integrity error: {e}") # Handle unique constraint violations
# You might want to rollback the transaction if an error occurs:
# conn.rollback() #More on transactions later
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
print("Connection closed.")
16. Transactions
Transactions are a sequence of database operations that are treated as a single unit of work. They ensure that either all operations within the transaction succeed, or none of them do. This is crucial for maintaining data consistency.
SQLite automatically starts a transaction when you make a change to the database. You can explicitly manage transactions using conn.commit() to save the changes and conn.rollback() to undo the changes.
Example: A transaction that inserts two new employees. If one insertion fails, the entire transaction is rolled back.
import sqlite3
db_file = "my_database.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Begin a transaction (optional in this simple case, but good practice)
# conn.execute("BEGIN")
# SQL command to insert data
insert_sql = """
INSERT INTO employees (name, department_id, salary)
VALUES (?, ?, ?);
"""
# Data to insert
employee1 = ("Frank Davis", 3, 80000.00)
employee2 = ("Grace Lee", 2, 70000.00)
# Execute the SQL commands
cursor.execute(insert_sql, employee1)
cursor.execute(insert_sql, employee2) # Could potentially raise an error
# Commit the transaction (save the changes)
conn.commit()
print("Employees inserted successfully.")
except sqlite3.Error as e:
print(f"Database error: {e}")
# Rollback the transaction (undo the changes)
if conn:
conn.rollback() #undoes everything since last commit or rollback
print("Transaction rolled back.")
finally:
if conn:
conn.close()
print("Connection closed.")
Important: In this example, even if the first cursor.execute() succeeds, if the second one fails (e.g., due to a constraint violation), the conn.rollback() will undo both insertions, leaving the database in its original state.
17. Committing and Closing Connections
We've emphasized this before, but it's worth repeating:
conn.commit(): Saves the changes you've made to the database. If you don't call commit(), your changes will be lost when the connection is closed.
conn.close(): Closes the database connection. Always close the connection when you're finished with it to release resources. The finally block ensures that the connection is closed, even if an error occurs.
Complete Example (Putting it all together):
import sqlite3
db_file = "my_database.db"
def create_connection(db_file):
"""Creates a database connection to the SQLite database specified by db_file."""
conn = None
try:
conn = sqlite3.connect(db_file)
print(f"Connected to database: {db_file}")
return conn
except sqlite3.Error as e:
print(f"Database error: {e}")
return None
def create_table(conn, create_table_sql):
"""Creates a table from the create_table_sql statement"""
try:
cursor = conn.cursor()
cursor.execute(create_table_sql)
conn.commit()
print("Table created/updated successfully")
except sqlite3.Error as e:
print(f"Error creating table: {e}")
def create_employee(conn, employee):
"""Creates a new employee into the employees table"""
sql = """
INSERT INTO employees (name, department_id, salary)
VALUES (?, ?, ?)
"""
cursor = conn.cursor()
try:
cursor.execute(sql, employee)
conn.commit()
print("Employee created successfully")
return cursor.lastrowid # returns the id of the inserted row, useful for referencing after insertion
except sqlite3.Error as e:
print(f"Error creating employee: {e}")
return None
def select_all_employees(conn):
"""Query all rows in the employees table"""
sql = "SELECT *