The Wayback Machine - https://web.archive.org/web/20240921031218/https://www.geeksforgeeks.org/python-sqlite-where-clause/
Open In App

Python SQLite – WHERE Clause

Last Updated : 17 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Where clause is used in order to make our search results more specific, using the where clause in SQL/SQLite we can go ahead and specify specific conditions that have to be met when retrieving data from the database.

If we want to retrieve, update or delete a particular set of data we can use the where clause. If we don’t have condition matching values in your database tables we probably didn’t get anything returned.

WHERE Clause in SQL:

Syntax:  

SELECT column_1, column_2,…,column_N

FROM table_name

WHERE [search_condition]

Here, in this [search_condition] you can use comparison or logical operators to specify conditions.

For example:  = , > , < , != , LIKE, NOT, etc. 

WHERE Clause in SQLite using Python:

In Python SQLite Cursor object/class which contains all the methods to execute SQL queries to perform operations, etc. The Cursor is the method of connection class that returns a cursor object.

Therefore, to perform SQLite commands in python we need 3 basic things to be done −

  • Establish a connection with the database using the connect() method.
  • Create a cursor object by using the cursor() method.
  • Now SQLite queries/statements can be executed using the execute() method of the Cursor class.

We’ll create a database to manage data about students. We’ll be storing information about each student, and then we’ll also create a way to retrieve, update and delete data of students using the where clause. 

Let’s Creates Database (geekforgeeks_student.db) and a Table (STUDENT).

Python
# import the sqlite3 module
import sqlite3

# Define connection and cursor
connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# create table
cursor.execute("DROP TABLE IF EXISTS STUDENT")
createTable = '''CREATE TABLE STUDENT(
   Student_ID int, First_Name VARCHAR(100),
   Last_Name VARCHAR(100), Age int,
   Department VARCHAR(100)
)'''
cursor.execute(createTable)

# check the database creation data
if cursor:
    print("Database Created Successfully !")
else:
    print("Database Creation Failed !")

# Commit the changes in database and Close the connection
connection.commit()
connection.close()

Output:

Database Created Successfully!

The above code will create “geekforgeeks_student.db” file locally.

To view the content of the “geekforgeeks_student.db” we can use this and load our .db file as shown below –

In the above image, we can see the table and table schema has been created in the database.

Now we will insert data into STUDENT table.

Python
# import the sqlite3 module
import sqlite3

# Define connection and cursor
connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# Insert data into the table
cursor.execute("INSERT INTO STUDENT VALUES (1,'Rohit', 'Pathak', 21, 'IT')")
cursor.execute("INSERT INTO STUDENT VALUES (2,'Nitin', 'Biradar', 21, 'IT')")
cursor.execute("INSERT INTO STUDENT VALUES (3,'Virat', 'Kohli', 30, 'CIVIL')")
cursor.execute("INSERT INTO STUDENT VALUES (4,'Rohit', 'Sharma', 32, 'COMP')")

# printing the cursor data
if cursor:
    print("Data Inserted !")
else:
    print("Data Insertion Failed !")

# Commit the changes in database and Close the connection
connection.commit()
connection.close()

Output:

Database Inserted!

The above code will insert the data into the STUDENT table

The following codes show the use of Where Clause

Example 1: To retrieve the data of the students whose Department is IT 

Python
import sqlite3

connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# WHERE CLAUSE TO RETRIEVE DATA
cursor.execute("SELECT * FROM STUDENT WHERE Department = 'IT'")

# printing the cursor data
print(cursor.fetchall())

connection.commit()
connection.close()

Output:

[(1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (2, ‘Nitin’, ‘Biradar’, 21, ‘IT’)]

We have 2 records in STUDENT table whose Department is IT.

Example 2: To retrieve the data of the students whose First Name starts with ‘R’. We can also use Wildcard characters with where clause as shown below

Python
import sqlite3

connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# WHERE CLAUSE TO RETRIEVE DATA
cursor.execute("SELECT * from STUDENT WHERE First_name Like'R%'")

# printing the cursor data
print(cursor.fetchall())

connection.commit()
connection.close()

Output:

[(1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (4, ‘Rohit’, ‘Sharma’, 32, ‘COMP’)]

We have 2 records in the STUDENT table whose First Name starts with the letter ‘R’.

Example 3: To update the data of student whose Student ID is 4 

Python
import sqlite3

connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# WHERE CLAUSE TO UPDATE DATA
cursor.execute("UPDATE STUDENT SET Department ='E&TC' WHERE Student_ID = 2")

# printing the cursor data
cursor.execute("SELECT * from STUDENT")
print(cursor.fetchall())

connection.commit()
connection.close()

Output:

[(1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (2, ‘Nitin’, ‘Biradar’, 21, ‘E&TC’), 

(3, ‘Virat’, ‘Kohli’, 30, ‘CIVIL’), (4, ‘Rohit’, ‘Sharma’, 32, ‘COMP’)]

Check the database content 

Department is updated for Student ID 2.

Example 4: To Delete the data of student whose Age ID is 32

Python
import sqlite3

connection = sqlite3.connect('geekforgeeks_student.db')
cursor = connection.cursor()

# WHERE CLAUSE TO DELETE DATA
cursor.execute("DELETE from STUDENT WHERE Age = 32")

#printing the cursor data
cursor.execute("SELECT * from STUDENT")
print(cursor.fetchall())

connection.commit()
connection.close()

Output:

[(1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (2, ‘Nitin’, ‘Biradar’, 21, ‘E&TC’), (3, ‘Virat’, ‘Kohli’, 30, ‘CIVIL’)]

Check the database content

Data of Student whose Age is 32 has been deleted.



Previous Article
Next Article

Similar Reads

Python SQLite - JOIN Clause
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let's see a brief about join in SQLite. Join Clause A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows: INNER JOIN (OR JOIN) - Gives the records that have common attrib
5 min read
Python SQLite - ORDER BY Clause
In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.ASC to sort in ascending order.
3 min read
Python SQLite - LIMIT Clause
In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let's get a brief about the LIMIT clause. If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement. Syntax: SELECT colum
2 min read
Python MySQL - Order By Clause
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause OrderBy is used to arrange the result set in either ascending or descendi
2 min read
Python MySQL - Where Clause
Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.Syntax SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION]; The above syntax is used for displaying a certain set of data following the condit
2 min read
Python MySQL - Limit Clause
A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driver a
2 min read
Python MariaDB - Where Clause using PyMySQL
Where clause is used in MariaDB database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MariaDB database by using the where clause. Syntax : SELECT column1, column2, …. cloumnN FROM [TABLE NAME] WHERE [CONDITION]; The above syntax is used for displaying a certain set of data following t
2 min read
Python MariaDB - Order By Clause using PyMySQL
A MySQL client library is employed when we have to use MySQL with other programming languages. The work of PyMySQL is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause The OrderBy is used to arrange the result set in either ascending or d
2 min read
Python MariaDB - Limit Clause using PyMySQL
The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of the OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows. Syntax : S
2 min read
Python MySQL - GROUP BY and HAVING Clause
In this article, we will see how to perform groupby() and HAVING() operations on SQL using Python. Here we will consider a college database to perform group by operation on the department with respect to student strength. GROUP BY The GROUP BY statement groups rows that have the same values into single based on the aggregate function used. Aggregat
2 min read
Python PostgreSQL - Limit Clause
In this article, we are going to see how to use the limit clause in PostgreSQL using pyscopg2 module in Python. In PostgreSQL LIMIT constraints the number of rows returned by the query. By default, It is used to display some specific number of rows from the top. If we want to skip a number of rows before returning the rows then we use the OFFSET cl
2 min read
Python PostgreSQL - Where Clause
In this article, we are going to see how to use the Where clause in PostgreSQL using Psycopg2 in Python. Where Clauses help us to easily deal with the databases. As we know we have a huge amount of data stored in our database, so extracting only useful and required information clauses is helpful. The WHERE clause is used to extract only those recor
2 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
How to store Python functions in a Sqlite table?
SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
3 min read
Creating a sqlite database from CSV with Python
Prerequisites: PandasSQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embed
2 min read
Python SQLite - CRUD Operations
In this article, we will go through the CRUD Operation using the SQLite module in Python. CRUD Operations The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let's discuss these operations one by one with the help of
4 min read
Python SQLite - Create Table
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to create a table: CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); N
1 min read
SQLite Datatypes and its Corresponding Python Types
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python. In this article, w
3 min read
How to connect to SQLite database that resides in the memory using Python ?
In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost a
3 min read
How to Delete a Specific Row from SQLite Table using Python ?
In this article, we will discuss how to delete of a specific row from the SQLite table using Python. In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in
3 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python SQLite - DROP Table
In this article, we will discuss the DROP command in SQLite using Python. But first, let's get a brief about the drop command. DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure. Syntax: DROP TABLE TABLE_NAME; For dropping table, we will first create a database and a table in i
2 min read
Change SQLite Connection Timeout using Python
In this article, we will discuss how to change the SQLite connection timeout when connecting from Python. What is a connection timeout and what causes it? A connection timeout is an error that occurs when it takes too long for a server to respond to a user's request. Connection timeouts usually occur when there are multiple active connections to a
3 min read
Python SQLite - Deleting Data in Table
In this article, we will discuss how we can delete data in the table in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to delete data from a table: DELETE FROM table_name [WHERE Clause] To create the database, we will execute the following code: C/C++ Code import sqlite3 # Connec
2 min read
How to Count the Number of Rows of a Given SQLite Table using Python?
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. To create the database
2 min read
Article Tags :
Practice Tags :