Databases and SQLite
Chapter 15 · Tamil Nadu State Board
- 13 min read
- 6-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson teaches how Python can use SQLite to create tables, add and change records, and retrieve data with SQL. It explains how clauses and operators filter, group, and sort results, and how aggregate functions summarise column values. It also shows how to join tables and save query results in a CSV file. These skills help students manage database information through Python scripts.
Written by AI from this lesson. How we check it
Key points
- A database is a structured collection of data, and its users can include people or software.
From your textbook
“A database is an organized collection of data. The term "database" can both refer to the data themselves”
- Python connects to SQLite through a connection, then uses a cursor to carry out SQL commands.
From your textbook
“All the commands will be executed using cursor object only.”
- Changes to records must be committed if they are to be saved.
From your textbook
“Any changes made in the values of the record should be saved by the commend "Commit"”
- SELECT retrieves table data, while fetchall(), fetchone(), and fetchmany() return different amounts of results.
From your textbook
“The fetchall() method is used to fetch all rows from the database table”
- SQL clauses can select unique values, filter conditions, group records, sort results, or filter groups.
From your textbook
“The following frequently used clauses are discussed here”
- Aggregate functions produce a single value from values in a column.
From your textbook
“These functions are used to do operations from the values of the column and a single value is returned.”
- Python can join tables for queries and write query results, including headings, to a CSV file.
From your textbook
“You can even store the query result in a CSV file.”
Formulas in this chapter
- Create a database connection and cursorconnection = sqlite3.connect("Academy.db") cursor = connection.cursor()Explained here
- Create the Student tableCREATE TABLE Student ( Rollno INTEGER PRIMARY KEY, Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1), Average DECIMAL(5,2), birth_date DATE);Explained here
- Insert records from a listfor p in student_data: sql_command = format_str.format(name=p[0], gr=p[1], gender=p[2], avg=p[3], birthdate=p[4]) cursor.execute(sql_command)Explained here
Databases and SQLite
Definition
- Database
- A database is an organized collection of data.
Definition
- Database management system
- A database management system is application software that lets users or programs interact with databases.
SQLite is a relational database system that stores data in regular files in the computer's internal memory. It is designed to be used inside applications, so it does not need a separate database server program. Python includes a library for using SQLite.
Basic steps for working with SQLite
- Use connect() and provide the database file name to open an existing database or create a new one.
- Create a cursor with cursor = connection.cursor().
- Use the cursor to execute SQL commands.
- Save record changes with connection.commit() before closing the connection.
Definition
- Cursor
- A cursor is a control structure used to move through database records and fetch results.
Remember: SQL commands are executed using the cursor object, and changes must be committed to be saved.
Creating a Database and Student Table
Python can connect to a database with sqlite3.connect("Academy.db"). If the database file does not exist, the connection creates it; if it already exists, the connection opens it. The cursor is created by calling the connection's cursor() method.
connection = sqlite3.connect("Academy.db") cursor = connection.cursor()
connection refers to the database connection, and cursor is the cursor object used to run SQL commands.
A table stores records in a database. The Student table has fields for Rollno, Sname, Grade, gender, Average, and birth_date. A cursor can execute a SQL command written as a triple-quoted string in Python.
CREATE TABLE Student ( Rollno INTEGER PRIMARY KEY, Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1), Average DECIMAL(5,2), birth_date DATE);
This command creates Student with the listed columns. Rollno is the primary key.
In SQLite3, an INTEGER PRIMARY KEY can generate a value when NULL is inserted for that column. The generated value is one larger than the highest value already used. If the table is empty, the value 1 is used.
Adding Records with INSERT
Use the SQL INSERT command to add records. The cursor's execute() method runs the command. After adding records, call connection.commit() to save the changes, then close the connection.
Worked example
Add two records to the Student table and save them.
Try it first, then show the solutionSolution
- Connect to Academy.db and create a cursor.
- Create the Student table with Rollno INTEGER PRIMARY KEY, Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1), Average DECIMAL (5, 2), and birth_date DATE.
- Run INSERT commands for Akshay and Aravind, using NULL for Rollno.
- Call connection.commit(), close the connection, and print the completion message.
Answer: The two records are added and saved. The program prints STUDENT TABLE CREATED.
Records can also come from a Python list. A loop can take each person's values, build an INSERT command, and execute it. In the example, student_data holds the records and format_str.format() fills the command's placeholders.
for p in student_data: sql_command = format_str.format(name=p[0], gr=p[1], gender=p[2], avg=p[3], birthdate=p[4]) cursor.execute(sql_command)
p is one record from student_data. Its indexed values fill the name, grade, gender, average, and birthdate placeholders.
Worked example
Add the people stored in student_data to the Student table.
Try it first, then show the solutionSolution
- Connect to Academy.db and create a cursor.
- Store the five records in student_data.
- Loop through the list and use format_str.format() to place each record's values in the INSERT command.
- Execute each command, commit the changes, and close the connection.
Answer: The records are added to the Student table. The program prints RECORDS ADDED TO STUDENT TABLE.
Querying a Table with Python
A query fetches data from a table. To query the Student table, use execute() with an SQL command that asks for the required data. The cursor is used to fetch results from the result set.
Remember: Use the cursor to run SQL commands and retrieve table data.
SELECT Queries and Fetch Methods
SELECT retrieves data from a database table. SELECT * FROM Student fetches all columns and rows from Student. The results can be collected as a list of tuples.
Ways to fetch query results
- fetchall() returns all rows from the result set.
- fetchone() returns the next row, or None when no row is left.
- fetchmany(n) returns the next n rows.
To display every row with fetchone(), get one row, print it, and repeat while the result is not None. A database file is created in the same folder as the Python file unless a different path is used when opening it.
Worked example
How can you fetch and print the first 3 rows from Student?
Try it first, then show the solutionSolution
- Run SELECT * FROM student.
- Use cursor.fetchmany(3) to get the first 3 rows.
- Print the result. To print each row on a new line without a loop, use print(*result, sep="\n").
Answer: fetchmany(3) returns the first 3 rows as a list of tuples.
DISTINCT and WHERE Clauses
Definition
- DISTINCT
- DISTINCT returns only unique values and avoids duplicate values in the selected column.
SELECT DISTINCT (Grade) FROM student returns the different grades. Its output is [('B',), ('A',), ('C',), ('D',)]. Without DISTINCT, the query displays 7 records because the table has 7 records and some values are duplicates.
Definition
- WHERE
- WHERE selects only the records that satisfy a specified condition.
Worked example
How can you get the unique grades of male students?
Try it first, then show the solutionSolution
- Select Grade from student.
- Use DISTINCT to avoid repeated grades.
- Add WHERE gender='M' as the condition.
Answer: SELECT DISTINCT (Grade) FROM student where gender='M' returns ('B',), ('A',), ('C',) and ('D',).
GROUP BY Clause
Definition
- GROUP BY
- GROUP BY puts records into groups and returns one record for each group.
GROUP BY is often used with aggregate functions such as COUNT, MAX, MIN, SUM and AVG. Grouping the student records by gender and counting gender gives one count for each gender.
Worked example
What does SELECT gender,count(gender) FROM student Group BY gender return?
Try it first, then show the solutionSolution
- Group the records by gender.
- Count the records in each gender group.
Answer: ('F', 2) and ('M', 5)
Sorting and filtering SQL results
ORDER BY sorts query results using a chosen field. It sorts in ascending order by default, as when student names are shown alphabetically. HAVING filters grouped results using group functions. Unlike WHERE, HAVING can be used with group functions.
WHERE and HAVING
| WHERE | HAVING |
|---|---|
| Filters records using a condition. | Filters grouped data using group functions. |
| Group functions cannot be used here. | Group functions can be used here. |
AND, OR, and NOT can be combined with WHERE conditions. AND requires both conditions to be true. OR accepts either condition. NOT excludes records that match the condition.
Worked example
Find students whose Average is from 80 to 90, including both limits.
Try it first, then show the solutionSolution
- Use Average>=80 to include the lower limit.
- Use Average<=90 to include the upper limit.
- Join the conditions with AND.
Answer: The query returns (1, 'Akshay', 87.8) and (5, 'VARUN', 80.6).
Worked example
Find students who were born in 2001.
Try it first, then show the solutionSolution
- Set the first date limit to '2001-01-01'.
- Set the last date limit to '2001-12-31'.
- Use both limits in the WHERE condition.
Answer: The query returns (1, 'Akshay', 'B') and (5, 'VARUN', 'B') for Rollno, Sname, and grade.
Remember: Use HAVING for conditions involving group functions, and use WHERE to filter records before grouping.
SQL aggregate functions
Aggregate functions use values from a column and return a single value. The functions covered here are COUNT(), AVG(), SUM(), MAX(), and MIN().
What each function does
- COUNT() counts matching rows. It returns 0 when no rows match. NULL values are not counted.
- AVG() finds the average of the column values. NULL values are ignored.
- SUM() adds the values in a column. NULL values are ignored.
- MAX() returns the largest value in the selected column.
- MIN() returns the smallest value in the selected column.
Worked example
Count all records in the student table.
Try it first, then show the solutionSolution
- Use COUNT(*) to count the rows.
Answer: The result is [(7,)].
Worked example
Find the average and sum of values in the Average field.
Try it first, then show the solutionSolution
- Use AVG(AVERAGE) to find the average.
- Use SUM(AVERAGE) to find the total.
Answer: The average result is [(84.65714285714286,)] and the sum result is [(592.6,)].
Worked example
Find the names and Average values for the highest and least averages.
Try it first, then show the solutionSolution
- Use MAX(AVERAGE) to find the highest value.
- Use MIN(AVERAGE) to find the smallest value.
Answer: The highest is ('PRIYA', 98.6). The least is ('TARUN', 62.3).
Updating and deleting table records
A Python script can update or delete records in a table. After an update or delete command, conn.commit() saves the change. The examples use Rollno to identify the student record.
Worked example
Change the name of the student with Rollno='6' to 'Priyanka'.
Try it first, then show the solutionSolution
- Run UPDATE Student SET sname ='Priyanka' where Rollno='6'.
- Run conn.commit() to save the change.
Answer: Total number of rows updated : 1. The record becomes (6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01').
Worked example
Delete the student record with Rollno='2'.
Try it first, then show the solutionSolution
- Run DELETE from Student where Rollno='2'.
- Run conn.commit() to save the change.
Answer: Total number of rows deleted : 1. The record for Rollno 2 is no longer in the displayed table.
Remember: Use UPDATE to change a record and DELETE to remove a record.
Entering user data into a table
Python input() can collect data while a program runs. The example collects 5 names, their ages, and their ids, then inserts each set into the person table.
How the example stores the input
- The program creates the person table with name, age, and id fields.
- It collects 5 names, then 5 ages, then 5 ids.
- It inserts each set of values using (?, ?, ?) as placeholders.
- It selects and displays all records from the person table.
Worked example
Enter five people’s names, ages, and ids, then display the records.
Try it first, then show the solutionSolution
- Enter RAM, KEERTHANA, KRISHNA, HARISH, and GIRISH.
- Enter ages 28, 12, 21, 18, and 16.
- Enter ids 1, 2, 3, 4, and 5.
- Insert each name, age, and id into the table.
Answer: The displayed records are ('RAM', 28, 1), ('KEERTHANA', 12, 2), ('KRISHNA', 21, 3), ('HARISH', 18, 4), and ('GIRISH', 16, 5).
Adding Records and Running SQL in Python
You can add records to an existing table by changing the field names in the code. Comment out the CREATE TABLE statement when the table already exists. The execute method runs one SQL statement.
Definition
- Placeholder
- A placeholder is a marker in an SQL statement where a value will be supplied instead of writing the value directly.
Placeholder styles supported by sqlite3
- Question marks? (qmark style)
- Named placeholders such as :name (named style)
Joining Tables and Reading Column Names
Python can query more than one table by joining them. In the example, student and Appointment are matched where their rollno values are equal. The result shows each matching student's name with their duty and age.
cursor.description contains information about the result columns. Each column's information is stored in a tuple, and index 0 gives its name. A list made from these names can be printed as the column headings.
Worked example
What result is produced by joining student and Appointment on matching rollno values?
Try it first, then show the solutionSolution
- Select student.rollno, student.sname, Appointment.Duty, and Appointment.Age.
- Match rows using student.rollno = Appointment.rollno.
- Print the column names from cursor.description, then print the fetched rows.
Answer: ['Rollno', 'Sname', 'Duty', 'age']; (1, 'Akshay', 'Prefect', 17); (2, 'Aravind', 'Secretary', 16)
Writing Query Results to a CSV File
A query result can be written to a CSV file using Python's csv module. The example sorts student records by GENDER in descending order and then by SNAME, writes the column headings and records, and reads the file to display its contents.
Steps for exporting a query to CSV
- Open a CSV file for writing and create a csv.writer.
- Run the SELECT query with ORDER BY.
- Get the column headings from cursor.description and write them to the file.
- Fetch the records and write each one to the file.
- Close the file, then read and display its contents if needed.
When a CSV file is read line by line, each record ends with a newline. The example removes it using replace() before printing. A CSV file can also be opened through MS-Excel to view the result in tabular form.
Listing Database Tables and Key SQL Ideas
To list tables, select name from sqlite_master where type='table'. The sqlite_master table stores key information about the database's tables.
SQL clauses for filtering and sorting
| Clause | Purpose |
|---|---|
| WHERE | Filters records using conditions. It can be combined with AND, OR, and NOT. |
| GROUP BY | Groups records into summary rows. |
| HAVING | Filters data based on group functions. |
| ORDER BY | Sorts data from selected fields. |
Important database and SQL points
- A database is an organized collection of data.
- A cursor is used to traverse and fetch database records. SQL commands are executed using the cursor object.
- SELECT retrieves data from a table and is the most commonly used SQL statement.
- Aggregate functions use column values to return a single value: COUNT() returns the number of rows, AVG() returns an average, SUM() returns a sum, MAX() returns the largest value, and MIN() returns the smallest value.
Remember: Use WHERE to filter individual records and HAVING to filter based on group functions; WHERE cannot be used along with GROUP BY.
Questions students ask
Short, direct answers to what students search for in this chapter.
What is a database?
A database is an organized collection of data. It stores data in a way that can be used by people or programs. A database management system is application software that allows users or programs to interact with a database.
What is a cursor in SQLite Python?
A cursor is a control structure used to move through database records and fetch results. In Python, it is created by calling cursor() on the connection. SQL commands are executed through the cursor object.
How do I create a database using SQLite in Python?
Import sqlite3, then call sqlite3.connect() with the database file name, such as sqlite3.connect("Academy.db"). The connection opens the database if it exists or creates a new database file if it does not. Create a cursor with connection.cursor().
How do I save changes after inserting records in SQLite?
After executing the INSERT commands with the cursor, call connection.commit() to save the record changes. Then close the database connection with connection.close(). Without committing, the changes may not be saved.
What does SELECT * FROM Student do?
SELECT * FROM Student retrieves all columns and rows from the Student table. The fetched data can be stored as a list of tuples. The SELECT statement is used to retrieve data from a database table.
What is the difference between fetchall(), fetchone() and fetchmany(n)?
fetchall() returns all rows in the result set. fetchone() returns the next row, or None if no row is left. fetchmany(n) returns the next n rows from the result set.
Show 11 more questions
How do I display all records using fetchone()?
Run the SELECT query and call fetchone() to get a row. Print that row, then call fetchone() again. Repeat this in a while loop while the result is not None. This displays the records one by one.
What is DISTINCT used for in SQL?
DISTINCT avoids duplicate values in the selected column. It returns only unique values. For example, selecting DISTINCT Grade from student returns the different grades instead of repeating grades found in multiple records.
What does GROUP BY do in SQL?
GROUP BY groups records by one or more columns and returns one record for each group. It is often used with aggregate functions such as COUNT, MAX, MIN, SUM and AVG to summarise the groups.
What is the difference between WHERE and HAVING in SQL?
WHERE filters records using a condition. HAVING filters grouped data using group functions. Group functions cannot be used in a WHERE clause, but they can be used in a HAVING clause.
What do SQL aggregate functions do?
Aggregate functions use values from a column and return one value. COUNT() counts rows, AVG() finds an average, SUM() adds values, MAX() returns the largest value, and MIN() returns the smallest value.
How does COUNT() handle NULL values?
COUNT() does not count NULL values in a specified column. For example, if one of the 7 Average values is NULL, COUNT(AVERAGE) returns 6. COUNT() returns 0 when no rows match the criteria.
How do you add user input to a table in Python?
Collect the values with input(), then insert them into the table with an SQL INSERT statement. The example uses placeholders (?, ?, ?) for a name, age, and id, and inserts one set of values at a time.
How do you join two tables in Python SQLite?
Run a SELECT query that names the required columns from both tables, then match their related fields in the WHERE condition. For example, student.rollno = Appointment.rollno joins the student and Appointment records with the same rollno.
How do I get column names from a SQLite query in Python?
After executing a query, read cursor.description. The column name is stored at index 0 in each column's information tuple. You can collect the names with [i[0] for i in cursor.description] and print that list.
How can I write SQLite query results to a CSV file?
Open a CSV file for writing and create a csv.writer. Execute the query, write column names obtained from cursor.description, then write each fetched record. Close the file when finished. The CSV file can later be read or opened through MS-Excel.
How do I display all table names in an SQLite database?
Execute SELECT name FROM sqlite_master WHERE type='table'; and print the fetched results. sqlite_master holds key information about database tables, so this query returns the names of the tables.
Book back answers
22 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
Choose the best answer (1 Mark)
Which of the following is an organized collection of data?
- (A) Database
- (B) DBMS
- (C) Information
- (D) Records
Try it, then show the answerAnswer
(A) Database
The chapter defines a database as an organized collection of data.
From the book: “A database is an organized collection of data.”
SQLite falls under which database system?
- (A) Flat file database system
- (B) Relational Database system
- (C) Hierarchical database system
- (D) Object oriented Database system
Try it, then show the answerAnswer
(B) Relational Database system
SQLite is described as a simple relational database system.
From the book: “SQLite is a simple relational database system”
Which of the following is a control structure used to traverse and fetch the records of the database?
- (A) Pointer
- (B) Key
- (C) Cursor
- (D) Insertion point
Try it, then show the answerAnswer
(C) Cursor
The cursor traverses and fetches database records.
From the book: “Cursor in step 3: is a control structure used to traverse and fetch the records of the database.”
Any changes made in the values of the record should be saved by the command
- (A) Save
- (B) Save As
- (C) Commit
- (D) Oblige
Try it, then show the answerAnswer
(C) Commit
The chapter says record changes should be saved using the Commit command.
From the book: “Any changes made in the values of the record should be saved by the commend "Commit"”
Practice
What is the role of a cursor in Python's work with a database?
Exam questions
Practice questions with model answers. These are not from an official paper.
How does a Python program use SQLite to execute SQL commands?5 marks
Python uses the SQLite library to connect to a database and send SQL commands to it. The cursor object is used to execute the commands.
- Import SQLite and connect: Import the sqlite3 module and create a connection by passing the database file name to connect(). If the file exists, it is opened; otherwise, a new database file is created.
- Create a cursor: Create a cursor object by calling the connection’s cursor() method. The cursor is the control structure used to traverse and fetch database records.
- Write the SQL command: Store the required SQL statement in a Python string. Triple-quoted strings can be used for SQL commands, since table values might contain single or double quotes.
- Execute the command: Pass the SQL statement to the cursor’s execute() method. This method runs the command, such as a CREATE TABLE, INSERT, or SELECT statement.
- Fetch query results: For a SELECT query, retrieve the results using methods such as fetchall(), fetchone(), or fetchmany(n), as required.
- Save changes and close: For changes to records, call commit() to save them before closing the database connection.
- Use the cursor for SQL commands: SQL commands are executed through the cursor object; this applies to the commands used to work with the database and its tables.
Example: connection = sqlite3.connect("Academy.db") cursor = connection.cursor() cursor.execute("SELECT * FROM Student") ans = cursor.fetchall()
Thus, a Python program connects to SQLite, executes SQL through a cursor, handles results, and commits changes before closing the connection.
Explain the difference between fetchall(), fetchone(), and fetchmany(n).5 marks
The three cursor methods retrieve rows from a query result set. They differ in how many rows they return at a time.
- fetchall(): It fetches and returns all rows from the result set.
- fetchone(): It returns the next row in the result set. If no row is left, it returns None.
- fetchmany(n): It returns the next specified number, n, of rows from the result set.
- Number of rows returned: fetchall() returns every remaining row, fetchone() returns one row at a time, and fetchmany(n) returns a specified number of rows.
- Using fetchone() for all records: A while loop can repeatedly call fetchone() to display all records one by one.
Example: The chapter shows result = cursor.fetchmany(3) to fetch and display the first 3 records.
Choose the method according to whether all rows, the next row, or a specified number of rows are required.
What are the uses of WHERE and HAVING clauses?2 marks
WHERE selects records that meet a specified condition. HAVING filters data based on group functions and can be used with group functions.
Name four aggregate functions and state what they return.5 marks
Aggregate functions perform operations on values in a column and return a single value.
- COUNT(): Returns the number of rows satisfying the specified criteria. It returns 0 if no rows match.
- AVG(): Returns the average of the values in a selected column. NULL values are ignored.
- SUM(): Returns the sum of the values in a selected column. NULL values are ignored.
- MAX(): Returns the largest value in the selected column.
- MIN(): Returns the smallest value in the selected column.
Example: For the Student table, COUNT(*) returns 7 rows.
Thus, aggregate functions summarise column values by returning a single value.
Watch out
- Do not confuse WHERE, which filters records, with HAVING, which filters based on group functions.
- Do not assume fetchone() returns all rows; use fetchall() for all rows or fetchmany(n) for a specified number.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →