Popular Searches
Popular Course Categories
Popular Courses

Creating Tables and Executing SQL Queries

Creating Tables and Executing SQL Queries

Database Connectivity and SQL Integration with Python

Creating Tables and Executing SQL Queries in Python

Course: Python Training

Topic: Creating Tables and Executing SQL Queries

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Creating Tables and Executing SQL Queries

Database programming allows Python applications to store, retrieve, modify, and organize information using a database management system. Two essential skills in database programming are creating tables and executing SQL queries.

A table defines how information is organized in a database. SQL (Structured Query Language) is used to create tables, insert records, retrieve information, update existing data, and delete records.

Python provides the built-in sqlite3 module for working with SQLite databases. SQLite is a useful starting point because it does not require a separate database server. Python can also connect to MySQL, PostgreSQL, SQL Server, and other database systems through suitable drivers.

Learning Objectives

  • Understand tables, columns, rows, and database schemas.
  • Learn common SQL data types and constraints.
  • Create tables using Python and SQL.
  • Execute SQL statements using execute().
  • Insert, retrieve, update, and delete records.
  • Use filtering, sorting, and aggregate queries.
  • Understand primary keys, foreign keys, and relationships.
  • Use parameterized queries to protect against SQL injection.
  • Manage database transactions and exceptions.
  • Build a practical Python database application.

2. Understanding Database Tables

A database table stores related information in rows and columns. Each column represents an attribute, while each row represents one record.

For example, a student management application may contain a table called students.

student_id name age course
1 Aarav Sharma 21 Python
2 Priya Patel 20 Data Analytics
3 Rahul Verma 22 Web Development

Important Database Terms

Term Description
Table A structure that stores related data.
Row A single record in a table.
Column A named attribute of a record.
Schema The structure and organization of database objects.
Primary key A column or group of columns that uniquely identifies a row.
Foreign key A column or group of columns that references a key in another table or the same table.
Constraint A rule that restricts the data that can be stored.
Query An SQL statement used to retrieve or manipulate data or database structures.

3. Setting Up SQLite in Python

The sqlite3 module is included in Python's standard library. You generally do not need to install an additional package to use SQLite with Python.

Step 1: Import the Module

import sqlite3

Step 2: Create a Database Connection

import sqlite3

connection = sqlite3.connect("college.db")
print("Database connection established")

connection.close()

The sqlite3.connect() function opens the specified SQLite database. If the database file does not exist, SQLite normally creates it, provided the directory is accessible.

The special database name :memory: creates a temporary in-memory database that disappears when its connection is closed.

import sqlite3

connection = sqlite3.connect(":memory:")
print("Temporary database created")
connection.close()

4. Understanding SQL Data Types

When creating a table, you define columns and specify their intended data types. The exact type system and behavior depend on the database engine. SQLite uses flexible typing and storage classes, while other relational databases may enforce declared column types more strictly.

Type or Declaration Typical Purpose Example
INTEGER Whole numbers and identifiers 21
REAL Floating-point numbers 89.5
TEXT Textual information Python Training
BLOB Binary data Binary file content
NUMERIC Values that can be stored using an appropriate numeric representation 100
DATE or DATETIME Date and time values in databases that support these types 2026-10-22

In SQLite, date and time values are commonly stored as ISO-formatted text, Unix timestamps, or numeric values. Other databases may provide dedicated date and time types.

5. Creating a Table Using CREATE TABLE

The SQL CREATE TABLE statement creates a new table in a database. It specifies the table name, column names, data types, and optional constraints.

Basic SQL Syntax

CREATE TABLE table_name (
    column1 DATA_TYPE,
    column2 DATA_TYPE,
    column3 DATA_TYPE
);

Example: Creating a Students Table

CREATE TABLE students (
    student_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER,
    course TEXT
);

This statement creates a table called students with four columns. The student_id column is the primary key, and the name column cannot contain a NULL value.

6. Creating Tables Through Python

Python can execute the CREATE TABLE statement by calling the connection or cursor's execute() method.

import sqlite3

connection = sqlite3.connect("college.db")

connection.execute("""
    CREATE TABLE IF NOT EXISTS students (
        student_id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER CHECK (age > 0),
        course TEXT NOT NULL
    )
""")

connection.commit()
connection.close()

print("Students table created successfully")

Explanation

  • sqlite3.connect("college.db") opens or creates the database file.
  • CREATE TABLE defines the new table and its columns.
  • IF NOT EXISTS prevents an error when a table with that name already exists.
  • INTEGER PRIMARY KEY AUTOINCREMENT provides automatically assigned increasing integer identifiers under SQLite's AUTOINCREMENT rules.
  • NOT NULL prevents a required value from being left NULL.
  • CHECK (age > 0) requires a positive age when the age value is not NULL.
  • commit() commits the current transaction.
  • close() releases the connection.

Important: IF NOT EXISTS does not modify an existing table to match a new definition. Use appropriate schema migrations when changing an existing table structure.

7. Understanding Primary Keys and Constraints

Constraints help maintain the accuracy and consistency of database information. They can prevent duplicate identifiers, missing required values, and invalid relationships.

Constraint Purpose Example
PRIMARY KEY Uniquely identifies each row. student_id INTEGER PRIMARY KEY
NOT NULL Requires a non-NULL value. name TEXT NOT NULL
UNIQUE Prevents duplicate values under the database's uniqueness rules. email TEXT UNIQUE
CHECK Requires a condition to be satisfied. age INTEGER CHECK(age > 0)
DEFAULT Provides a default value when one is not supplied. status TEXT DEFAULT 'Active'
FOREIGN KEY Enforces a relationship with a referenced key. course_id INTEGER REFERENCES courses(course_id)

Example: A Table with Constraints

import sqlite3

with sqlite3.connect("college.db") as connection:
    connection.execute("""
        CREATE TABLE IF NOT EXISTS courses (
            course_id INTEGER PRIMARY KEY,
            course_name TEXT NOT NULL UNIQUE,
            duration_months INTEGER CHECK (duration_months > 0),
            status TEXT NOT NULL DEFAULT 'Active'
        )
    """)

print("Courses table is ready")

This table requires a course name, prevents duplicate course names, checks that the duration is positive when provided, and supplies a default status.

8. Creating Related Tables with Foreign Keys

Relational databases can connect tables using primary keys and foreign keys. For example, a student may be enrolled in a course identified by a record in the courses table.

import sqlite3

with sqlite3.connect("college.db") as connection:
    connection.execute("PRAGMA foreign_keys = ON")

    connection.execute("""
        CREATE TABLE IF NOT EXISTS course_enrollments (
            enrollment_id INTEGER PRIMARY KEY,
            student_id INTEGER NOT NULL,
            course_id INTEGER NOT NULL,
            enrollment_date TEXT DEFAULT CURRENT_DATE,
            FOREIGN KEY (student_id) REFERENCES students(student_id),
            FOREIGN KEY (course_id) REFERENCES courses(course_id)
        )
    """)

print("Enrollment table created")

SQLite foreign-key enforcement should be enabled for each database connection using PRAGMA foreign_keys = ON. Referenced tables and keys should be created appropriately, and inserted foreign-key values must reference existing records when enforcement is active.

9. Executing SQL Queries with execute()

The execute() method runs a single SQL statement. It can be used for table creation, data insertion, record retrieval, and data modification. The behavior and supported statements depend on the database driver.

General Syntax

cursor.execute(sql_statement, parameters)

The parameters argument is optional when the statement has no placeholders. When supplying values, use the placeholder style supported by your database driver.

Example: Execute a SELECT Query

import sqlite3

connection = sqlite3.connect("college.db")

cursor = connection.execute(
    "SELECT student_id, name, age, course FROM students"
)

for row in cursor:
    print(row)

connection.close()

The query retrieves the specified columns from the students table. Each row is returned as a tuple by default when using the standard SQLite cursor.

10. Inserting Records with INSERT

The INSERT INTO statement adds new records to a table.

SQL Syntax

INSERT INTO table_name (column1, column2)
VALUES (value1, value2);

Python Example

import sqlite3

with sqlite3.connect("college.db") as connection:
    connection.execute(
        "INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
        ("Aarav Sharma", 21, "Python")
    )

print("Student record inserted")

SQLite uses question marks as positional parameter placeholders. The supplied tuple contains values in the same order as the placeholders. Parameterized queries keep values separate from SQL instructions and help prevent SQL injection.

Inserting Multiple Records

import sqlite3

students = [
    ("Priya Patel", 20, "Data Analytics"),
    ("Rahul Verma", 22, "Web Development"),
    ("Neha Singh", 19, "Python")
]

with sqlite3.connect("college.db") as connection:
    connection.executemany(
        "INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
        students
    )

print("Multiple student records inserted")

The executemany() method executes a parameterized statement for each supplied parameter set. It is useful when inserting many records with the same SQL statement.

11. Retrieving Records with SELECT

The SELECT statement retrieves information from one or more tables.

Retrieve All Columns

SELECT * FROM students;

The asterisk selects all columns. In application code, specifying the required columns is often preferable because it makes the query's purpose clearer and avoids retrieving unnecessary data.

Retrieve Specific Columns

SELECT name, course
FROM students;

Fetch All Results in Python

import sqlite3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "SELECT student_id, name, age, course FROM students"
    )

    records = cursor.fetchall()

    for record in records:
        print(record)

fetchall() returns all remaining rows in the result set as a list. For very large result sets, iterating over the cursor or fetching a manageable number of rows can reduce memory usage.

Fetch a Single Result

import sqlite3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "SELECT student_id, name, course FROM students WHERE student_id = ?",
        (1,)
    )

    student = cursor.fetchone()

    if student is not None:
        print(student)
    else:
        print("Student not found")

The fetchone() method returns one row or None if no rows remain. The parameter (1,) is a one-item tuple; the comma is required.

12. Filtering Records with WHERE

The WHERE clause filters records according to a condition. It is useful when the application needs only specific rows.

SELECT name, age
FROM students
WHERE age >= 21;

Filtering with Python Parameters

import sqlite3

minimum_age = 21

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "SELECT name, age, course FROM students WHERE age >= ?",
        (minimum_age,)
    )

    for row in cursor:
        print(row)

Common SQL Operators

Operator Meaning Example
= Equal to course = 'Python'
!= or <> Not equal to age != 18
> Greater than age > 20
< Less than age < 25
>= Greater than or equal to age >= 21
<= Less than or equal to age <= 22
AND Both conditions must be true age > 18 AND course = 'Python'
OR At least one condition must be true course = 'Python' OR course = 'SQL'
LIKE Matches a text pattern name LIKE 'A%'
IN Matches a value from a set course IN ('Python', 'SQL')
BETWEEN Checks whether a value falls within a range age BETWEEN 18 AND 25

13. Sorting and Limiting Query Results

The ORDER BY clause sorts results. Use ASC for ascending order and DESC for descending order.

SELECT name, age
FROM students
ORDER BY age ASC;

To display the oldest students first, use:

SELECT name, age
FROM students
ORDER BY age DESC;

The LIMIT clause restricts the number of returned rows in SQLite and several other databases.

SELECT student_id, name, course
FROM students
ORDER BY student_id
LIMIT 5;

Executing a Sorted Query in Python

import sqlite3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute("""
        SELECT name, age, course
        FROM students
        WHERE age >= ?
        ORDER BY age DESC
        LIMIT 5
    """, (18,))

    for row in cursor:
        print(row)

14. Updating Records with UPDATE

The UPDATE statement modifies values in existing records.

UPDATE students
SET course = 'Advanced Python'
WHERE student_id = 1;

Python Example

import sqlite3

student_id = 1
new_course = "Advanced Python"

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "UPDATE students SET course = ? WHERE student_id = ?",
        (new_course, student_id)
    )

    print("Rows matched or changed:", cursor.rowcount)

Always review the WHERE condition before running an update. If the condition is omitted, every row may be updated.

15. Deleting Records with DELETE

The DELETE statement removes records that match a specified condition.

DELETE FROM students
WHERE student_id = 3;

Python Example

import sqlite3

student_id = 3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "DELETE FROM students WHERE student_id = ?",
        (student_id,)
    )

    print("Rows deleted:", cursor.rowcount)

Omitting the WHERE clause can delete every row from the table. Deleting records should be handled carefully, especially in production applications.

16. Using Aggregate Functions

Aggregate functions calculate a single value from a group of rows. They are commonly used in reports, dashboards, and data analysis.

Function Purpose Example
COUNT() Counts rows or non-NULL values, depending on the expression. COUNT(*)
SUM() Calculates the sum of numeric values. SUM(amount)
AVG() Calculates the average of non-NULL numeric values. AVG(age)
MIN() Returns the minimum value. MIN(age)
MAX() Returns the maximum value. MAX(age)

Example: Count Students

import sqlite3

with sqlite3.connect("college.db") as connection:
    result = connection.execute(
        "SELECT COUNT(*) FROM students"
    ).fetchone()

    print("Total students:", result[0])

Example: Average Age

import sqlite3

with sqlite3.connect("college.db") as connection:
    result = connection.execute(
        "SELECT AVG(age) FROM students"
    ).fetchone()

    print("Average age:", result[0])

17. Grouping Records with GROUP BY

The GROUP BY clause groups rows that share the same value in one or more columns. Aggregate functions can then calculate a result for each group.

SELECT course, COUNT(*) AS total_students
FROM students
GROUP BY course
ORDER BY total_students DESC;

Executing GROUP BY in Python

import sqlite3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute("""
        SELECT course, COUNT(*) AS total_students
        FROM students
        GROUP BY course
        ORDER BY total_students DESC
    """)

    for course, total in cursor.fetchall():
        print(course, total)

This query counts how many students are registered in each course and sorts the results by the count in descending order.

18. Understanding JOIN Queries

A JOIN combines related information from two or more tables. For example, a student record may be connected to a course record using a course identifier.

Example Tables

students contains student information, while courses contains course information. Suppose each student record includes a course_id foreign key.

SELECT students.name, courses.course_name
FROM students
INNER JOIN courses
ON students.course_id = courses.course_id;

An INNER JOIN returns rows where the join condition matches. A LEFT JOIN returns every row from the left table and matching rows from the right table, using NULL values when no match exists.

Executing a JOIN in Python

import sqlite3

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute("""
        SELECT students.name, courses.course_name
        FROM students
        INNER JOIN courses
        ON students.course_id = courses.course_id
    """)

    for row in cursor:
        print(row)

Ensure that the referenced columns and tables exist before executing the query. The example requires a course_id column in the students table.

19. Using Named Parameters in SQLite

SQLite also supports named placeholders. Named parameters can improve readability when a query uses multiple values.

import sqlite3

student = {
    "name": "Anaya Rao",
    "age": 20,
    "course": "Python"
}

with sqlite3.connect("college.db") as connection:
    connection.execute("""
        INSERT INTO students (name, age, course)
        VALUES (:name, :age, :course)
    """, student)

print("Student added successfully")

Named placeholders use a colon followed by the parameter name. The supplied dictionary provides the corresponding values.

20. Preventing SQL Injection

SQL injection is a security vulnerability that occurs when untrusted input changes the intended meaning of an SQL statement. Parameterized queries help protect database operations by separating query structure from supplied values.

Unsafe Example

# Unsafe: do not build SQL using untrusted input.
student_name = input("Enter name: ")

query = "SELECT * FROM students WHERE name = '" + student_name + "'"

String concatenation can allow specially crafted input to change the query's meaning.

Safer Example

import sqlite3

student_name = input("Enter name: ")

with sqlite3.connect("college.db") as connection:
    cursor = connection.execute(
        "SELECT student_id, name, age, course FROM students WHERE name = ?",
        (student_name,)
    )

    for row in cursor.fetchall():
        print(row)

Always use the placeholder syntax supported by your database driver. Placeholders are for values, not arbitrary table names or column names. For dynamic identifiers, validate against an allowlist and use the database driver's safe SQL composition facilities where available.

21. Executing Multiple SQL Statements

In Python's SQLite interface, execute() is intended for one SQL statement at a time. Use executemany() for applying one parameterized data-modification statement to multiple parameter sets.

SQLite also provides executescript() for executing a script containing multiple SQL statements.

import sqlite3

script = """
CREATE TABLE IF NOT EXISTS departments (
    department_id INTEGER PRIMARY KEY,
    department_name TEXT NOT NULL UNIQUE
);

CREATE TABLE IF NOT EXISTS employees (
    employee_id INTEGER PRIMARY KEY,
    employee_name TEXT NOT NULL,
    department_id INTEGER,
    FOREIGN KEY (department_id)
        REFERENCES departments(department_id)
);
"""

with sqlite3.connect("college.db") as connection:
    connection.executescript(script)

print("Tables created successfully")

Use executescript() for trusted SQL scripts such as fixed schema setup. Do not insert untrusted user input directly into a script. Be aware that transaction handling for scripts differs from ordinary individual statements; consult the Python version's documentation when transaction boundaries are important.

22. Modifying and Removing Table Structures

Besides creating tables, SQL provides commands for changing or removing database structures. Supported schema changes vary between database systems.

Adding a Column with ALTER TABLE

ALTER TABLE students
ADD COLUMN email TEXT;

This statement adds an email column to an existing table in SQLite and several other databases.

Removing a Table with DROP TABLE

DROP TABLE IF EXISTS temporary_students;

DROP TABLE removes the table structure and its stored records. It should not be confused with DELETE, which removes rows while leaving the table itself in place.

Command Purpose
CREATE TABLE Creates a table.
ALTER TABLE Changes supported aspects of a table's structure.
DROP TABLE Removes a table and its data.
DELETE Removes selected rows from a table.
TRUNCATE TABLE Removes all rows in database systems that support this command.

SQLite does not support TRUNCATE TABLE as a standard SQL command. For SQLite, use an appropriate DELETE FROM table_name statement when the intention is to remove all rows.

23. Using Transactions and Handling Errors

A transaction groups database changes into a logical unit. If a sequence of related operations fails, rolling back the transaction can prevent partial changes from being saved.

Transaction Example

import sqlite3

connection = sqlite3.connect("college.db")

try:
    connection.execute(
        "INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
        ("Karan Mehta", 23, "Python")
    )

    connection.execute(
        "UPDATE students SET course = ? WHERE name = ?",
        ("Advanced Python", "Karan Mehta")
    )

    connection.commit()
    print("Database changes committed")

except sqlite3.Error as error:
    connection.rollback()
    print("Database error:", error)

finally:
    connection.close()

This example commits the changes after successful execution and rolls back uncommitted changes if a SQLite error occurs. In real applications, ensure that the operations and conditions match the intended business logic.

Using a Connection Context Manager

import sqlite3

with sqlite3.connect("college.db") as connection:
    connection.execute(
        "INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
        ("Meera Joshi", 21, "SQL")
    )

print("Operation completed")

The connection context manager commits a successful transaction or rolls it back if an exception occurs. It does not automatically close the connection when the block ends; use an explicit closing pattern when needed.

24. Complete Mini Project: Student Database Application

This mini project combines table creation, insertion, retrieval, filtering, updating, and deleting records in one Python application.

Project Requirements

  • Create a persistent SQLite database.
  • Create a students table if it does not exist.
  • Add student records using parameterized SQL.
  • Display all student records.
  • Search for a student by ID.
  • Update a student's course.
  • Delete a student by ID.

Complete Python Code

import sqlite3

DATABASE = "student_app.db"


def initialize_database():
    with sqlite3.connect(DATABASE) as connection:
        connection.execute("""
            CREATE TABLE IF NOT EXISTS students (
                student_id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL CHECK (age > 0),
                course TEXT NOT NULL
            )
        """)


def add_student(name, age, course):
    with sqlite3.connect(DATABASE) as connection:
        connection.execute(
            "INSERT INTO students (name, age, course) VALUES (?, ?, ?)",
            (name, age, course)
        )
    print("Student added successfully.")


def view_students():
    with sqlite3.connect(DATABASE) as connection:
        rows = connection.execute("""
            SELECT student_id, name, age, course
            FROM students
            ORDER BY student_id
        """).fetchall()

    if not rows:
        print("No student records found.")
        return

    for row in rows:
        print(row)


def search_student(student_id):
    with sqlite3.connect(DATABASE) as connection:
        row = connection.execute("""
            SELECT student_id, name, age, course
            FROM students
            WHERE student_id = ?
        """, (student_id,)).fetchone()

    if row is None:
        print("Student not found.")
    else:
        print(row)


def update_student_course(student_id, course):
    with sqlite3.connect(DATABASE) as connection:
        cursor = connection.execute("""
            UPDATE students
            SET course = ?
            WHERE student_id = ?
        """, (course, student_id))

    if cursor.rowcount:
        print("Student course updated.")
    else:
        print("Student not found.")


def delete_student(student_id):
    with sqlite3.connect(DATABASE) as connection:
        cursor = connection.execute(
            "DELETE FROM students WHERE student_id = ?",
            (student_id,)
        )

    if cursor.rowcount:
        print("Student deleted.")
    else:
        print("Student not found.")


def main():
    initialize_database()

    while True:
        print("\\n--- Student Database Application ---")
        print("1. Add student")
        print("2. View students")
        print("3. Search student")
        print("4. Update course")
        print("5. Delete student")
        print("6. Exit")

        choice = input("Enter choice: ").strip()

        if choice == "1":
            name = input("Enter name: ").strip()
            course = input("Enter course: ").strip()

            try:
                age = int(input("Enter age: "))
            except ValueError:
                print("Age must be an integer.")
                continue

            if not name or not course or age <= 0:
                print("Enter a name, a course, and a positive age.")
                continue

            try:
                add_student(name, age, course)
            except sqlite3.Error as error:
                print("Could not add student:", error)

        elif choice == "2":
            view_students()

        elif choice == "3":
            try:
                student_id = int(input("Enter student ID: "))
                search_student(student_id)
            except ValueError:
                print("Student ID must be an integer.")

        elif choice == "4":
            try:
                student_id = int(input("Enter student ID: "))
            except ValueError:
                print("Student ID must be an integer.")
                continue

            course = input("Enter new course: ").strip()

            if course:
                update_student_course(student_id, course)
            else:
                print("Course cannot be empty.")

        elif choice == "5":
            try:
                student_id = int(input("Enter student ID: "))
                delete_student(student_id)
            except ValueError:
                print("Student ID must be an integer.")

        elif choice == "6":
            print("Application closed.")
            break

        else:
            print("Invalid choice. Try again.")


if __name__ == "__main__":
    main()

How the Project Works

  1. initialize_database() creates the table when it does not already exist.
  2. add_student() inserts a student using a parameterized query.
  3. view_students() retrieves all student records in ID order.
  4. search_student() searches for one student using the primary key.
  5. update_student_course() changes the selected student's course.
  6. delete_student() deletes the record matching the specified ID.
  7. main() provides a menu for interacting with the database.

25. Common Errors and Troubleshooting

Error or Problem Possible Cause Solution
Table already exists The table was created previously. Use CREATE TABLE IF NOT EXISTS when appropriate.
No such table The table name is incorrect or the table has not been created in the connected database. Check the connection path, table name, and initialization code.
No such column The query refers to a column that does not exist. Review the table definition and query spelling.
Incorrect number of bindings The parameter count does not match the placeholders. Check the number and order of supplied values.
UNIQUE constraint failed A value violates a uniqueness constraint. Check for duplicates or handle the constraint error.
NOT NULL constraint failed A required column received a NULL value. Provide a valid value or revise the schema if appropriate.
Database is locked A concurrent operation or connection holds a database lock. Keep transactions short and investigate concurrent writes.
Changes are missing Changes were not committed or were rolled back. Review transaction handling and exception paths.
Unexpected results A filter, join, or sorting condition is incorrect. Test the SQL statement directly and verify its conditions.

26. Best Practices for Executing SQL Queries

  • Use parameterized queries instead of concatenating user input into SQL strings.
  • Specify column names explicitly in important queries.
  • Use primary keys and suitable constraints to maintain data integrity.
  • Check update and delete conditions before running statements.
  • Use transactions for related changes that must succeed or fail together.
  • Close connections and cursors when they are no longer needed.
  • Handle database exceptions instead of silently ignoring them.
  • Validate data in the application and enforce important rules in the database.
  • Use indexes for frequently searched or joined columns when they improve performance.
  • Keep credentials and sensitive information out of publicly shared source code.
  • Back up important data and test recovery procedures.
  • Test SQL queries with valid, invalid, empty, and boundary-case inputs.

27. Interview Questions and Answers

Q1. What is the purpose of CREATE TABLE?

Answer: It creates a database table and defines its columns, data types, and optional constraints.

Q2. How can Python create a table in SQLite?

Answer: Import sqlite3, connect to a database, execute a CREATE TABLE statement, and manage the transaction and connection.

Q3. What is the purpose of execute()?

Answer: It executes a single SQL statement using the database connection or cursor.

Q4. What is the difference between execute() and executemany()?

Answer: execute() runs a statement with one parameter set, while executemany() applies the same parameterized statement to multiple parameter sets.

Q5. What is the purpose of a primary key?

Answer: A primary key uniquely identifies each row in a table.

Q6. Why are constraints important?

Answer: Constraints enforce rules that help maintain data integrity, such as preventing missing required values or duplicate identifiers.

Q7. What is the difference between WHERE and ORDER BY?

Answer: WHERE filters rows, while ORDER BY sorts the returned rows.

Q8. What is the difference between DELETE and DROP TABLE?

Answer: DELETE removes rows from a table; DROP TABLE removes the table structure and its data.

Q9. Why should parameterized queries be used?

Answer: They separate SQL code from supplied values and help protect against SQL injection.

Q10. What is a JOIN?

Answer: A JOIN combines related records from multiple tables using a join condition.

Q11. What does fetchone() return?

Answer: It returns the next result row or None when no row remains.

Q12. What does commit() do?

Answer: It commits the current transaction so that its changes are saved according to the database's transaction rules.

Q13. What is a foreign key?

Answer: A foreign key references a key in another table or the same table to help enforce relationships between records.

Q14. What is the purpose of GROUP BY?

Answer: It groups rows that share values so aggregate functions can calculate summaries for each group.

Q15. How do you execute several SQL statements in SQLite?

Answer: Use separate execute() calls for individual statements or use executescript() for a trusted script containing multiple SQL statements.

28. Practical Exercises

  1. Create a database named library.db.
  2. Create a books table with book ID, title, author, and publication year.
  3. Add at least five books using parameterized queries.
  4. Retrieve all books and sort them by title.
  5. Display books published after a selected year.
  6. Update the author of a particular book.
  7. Delete a book by its ID.
  8. Create a members table with a primary key and a unique email address.
  9. Create a related loans table using foreign keys.
  10. Write a query that counts how many books each author has in the database.
  11. Build a menu-driven library management program.
  12. Add error handling for invalid input and database constraint violations.

29. Quick Revision Checklist

  • Understand the structure of tables, rows, columns, and schemas.
  • Know how to connect Python to SQLite.
  • Create tables using CREATE TABLE.
  • Understand data types, primary keys, foreign keys, and constraints.
  • Execute SQL using execute() and executemany().
  • Insert records with INSERT and retrieve records with SELECT.
  • Filter, sort, and limit query results.
  • Update and delete records safely.
  • Use aggregate functions, grouping, and joins.
  • Apply parameterized queries and prevent SQL injection.
  • Manage transactions, exceptions, and database connections.
  • Practice by building a complete database application.

30. Additional Learning Resources

Conclusion

Creating tables and executing SQL queries are fundamental skills for Python database programming. By learning to define table structures, apply constraints, execute parameterized statements, retrieve and modify records, and manage transactions, developers can build applications that store and process information reliably.

Begin with SQLite and the built-in sqlite3 module, then apply the same concepts to database servers such as MySQL and PostgreSQL using their appropriate Python drivers. Regular practice with real-world projects will strengthen your understanding of SQL and database application development.

Continue learning through the Python Training Course at JustAcademy and register for a course demo.

whatsapp