How to use the IN operator in SQLAlchemy in Python?
Last Updated :
22 Jun, 2022
In this article, we will see how to use the IN operator using SQLAlchemy in Python.
We will cover 2 examples, one each for SQLAchemy Core and ORM layers. In both examples, we will count the number of records present in the category table within the sakila database. The sample data from the table looks like.

If you do not have sakila database and want to follow along with this article without installing it then use the below SQL script to create the required schema and category table along with the records.
CREATE DATABASE IF NOT EXISTS `sakila`;
USE `sakila`;
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`category_id` tinyint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`category_id`)
);
INSERT INTO `category`
VALUES
(1, 'Action', '2006-02-14 23:16:27'),
(2, 'Animation', '2006-02-14 23:16:27'),
(3, 'Children', '2006-02-14 23:16:27'),
(4, 'Classics', '2006-02-14 23:16:27'),
(5, 'Comedy', '2006-02-14 23:16:27'),
(6, 'Documentary', '2006-02-14 23:16:27'),
(7, 'Drama', '2006-02-14 23:16:27'),
(8, 'Family', '2006-02-14 23:16:27'),
(9, 'Foreign', '2006-02-14 23:16:27'),
(10, 'Games', '2006-02-14 23:16:27'),
(11, 'Horror', '2006-02-14 23:16:27'),
(12, 'Music', '2006-02-14 23:16:27'),
(13, 'New', '2006-02-14 23:16:27'),
(14, 'Sci-Fi', '2006-02-14 23:16:27'),
(15, 'Sports', '2006-02-14 23:16:27'),
(16, 'Travel', '2006-02-14 23:16:27');
The SQL query which we are looking at in the below two examples is:
SELECT category_id, name FROM category WHERE name IN ("Action", "Horror", "Sci-Fi");
SQLAlchemy Core
In the above example and with reference to the category table created earlier, we have filtered out the records that have one of the 'Action', 'Horror', or 'Sci-Fi' in the name field. We are selecting the category_id and name column from the category table. As we can see the example corresponds to SQLAlchemy Core, we have used the metadata object to get the metadata information about the table. Now, let us look at how we can do the same using SQLAlchemy ORM.
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `category` TABLE FROM THE METADATA OBJECT
category_table = meta_data.tables['category']
# SELECT category_id, name FROM category
# WHERE name IN ("Action", "Horror", "Sci-Fi");
query = db.select([
category_table.c.category_id,
category_table.c.name
]).where(
category_table.c.name.in_([
"Action", "Horror", "Sci-Fi"
])
)
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).fetchall()
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print("\n", record)
Output:
SQAlchemy Core ExampleSQLAchemy ORM
The ORM example results are the same as the results obtained for the Core example. The difference between the two is the syntax. For the ORM, we need to define the table model. In the above code, we have created the Category class which also defines the different fields or columns present in the table. We use this class to query the database. Due to the use of class models, ORM feels more pythonic in SQLAlchemy. However, it is preferred when your program is supposed to define the database schema and architecture otherwise Core can prove to be much handy.
Python
# IMPORT REQUIRED LIBRARIES
from sqlalchemy.orm import sessionmaker
import sqlalchemy as db
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE TABLE MODEL TO USE IT FOR QUERYING
class Category(Base):
__tablename__ = 'category'
category_id = db.Column(
db.SmallInteger, primary_key=True,
autoincrement=True)
name = db.Column(db.String(25))
last_update = db.Column(db.DateTime)
# CREATE A SESSION OBJECT TO INITIATE QUERY IN DATABASE
Session = sessionmaker(bind=engine)
session = Session()
# SELECT category_id, name FROM
# category WHERE name IN
# ("Action", "Horror", "Sci-Fi");
result = session.query(Category.category_id, Category.name) \
.filter(
Category.name.in_(("Action", "Horror", "Sci-Fi"))
)
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print("\n", record.category_id, "-", record.name)
Output:
SQLAlchemy ORM Example
Similar Reads
How to Install SQLAlchemy in Python in Windows? SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that is used as flexible database access using SQL. In this article, we will look into the process of installing SQLAlchemy on a windows machine. Pre-requisites: The only thing that you need for installing Numpy on Windows are: Python
2 min read
How to Install SQLAlchemy in Python on Linux? SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that is used as flexible database access using SQL. In this article, we will look into the process of installing SQLAlchemy on a windows machine. Pre-requisites: The only thing that you need for installing Numpy on Windows are: Python
2 min read
How to Use the IN Operator with a SubQuery in SQL? In this article, we will see the use of IN Operator with a SubQuery in SQL. IN operator is used to compare the column values with the list of values. The list of values is defined after IN query in SQL. If we don't know the exact list of values to be compared, we can generate the list of values usin
2 min read
How to Install sqlalchemy in Python on MacOS? In this article, we will learn how to install SQLAlchemy in Python on MacOS. SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL Installation:Method 1: Using pip to install SQLAlchemy Follow the below steps to inst
2 min read
How to Use the IN Operator With a SubQuery? The IN Operator in SQL allows to specifies multiple values in WHERE clause, it can help you to easily test if an expression matches any value in the list of values. The use of IN Operator reduces the need for multiple OR conditions in statements like SELECT, INSERT, UPDATE, and DELETE. Sub Queries:T
3 min read
How to update existing table rows in SQLAlchemy in Python? In this article, we are going to see how to use the UPDATE statement in SQLAlchemy against a PostgreSQL database in Python. Creating table for demonstration:Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as sho
3 min read
Connecting PostgreSQL with SQLAlchemy in Python In this article, we will discuss how to connect PostgreSQL with SQLAlchemy in Python. In order to connect with any Database management system, it is essential to create an engine object, that serves as a central source of connection by providing a connection pool that manages the database connection
3 min read
How to use sum and order by in SQLAlchemy query? In this article, we are going to see how to perform the sum and count function in SQLAlchemy against a PostgreSQL database in python. SUM and count operations are performed in different methods using different functions. Such kinds of mathematical operations are database-dependent. In PostgreSQL, Gr
3 min read
How to use avg and sum in SQLAlchemy Query? In this article, we are going to see how to use avg and sum in SQLAlchemy query using Python. Installing SQLAlchemy SQLAlchemy is available via the pip install package. pip install sqlalchemy However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installe
2 min read
Connecting to SQL Database using SQLAlchemy in Python In this article, we will see how to connect to an SQL database using SQLAlchemy in Python. To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip - !pip install sqlalchemyThe create_engine() method of sq
3 min read