Dynamic Column Parameterization in SQLAlchemy Core
Last Updated :
28 Apr, 2025
SQLAlchemy Core is an adaptable SQL toolkit and Object Relational Mapping (ORM) library, for Python. It is specifically designed to integrate with databases offering an extensive set of functionalities, for creating, querying, and manipulating database tables and records. When working with databases a frequent necessity is the ability to dynamically specify column names in your queries or operations. In this article, we are going to see how to pass the column name as a parameter in SQLAlchemy against the MySQL database in Python.
Prerequisites:
Creating Student Table
Import necessary functions and modules from the SQLAlchemy package. Establish a connection with the MySql database using the create_engine() function as shown below, and create a model class called Student with attributes student_id, student_name, gender,phone_number, and branch. Insert the record into the student table using add() and commit() the changes as shown.
Python3
from sqlalchemy import Column, create_engine, Integer, String, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# create Base class
base_class = declarative_base()
# Establish connection
engine = create_engine("mysql+pymysql://user_name:password@host:port/db_name")
# Model class
# the model class should have one primary key attribute
# other wise it will give an error
class Student(base_class):
__tablename__ = "student"
student_id = Column(Integer, primary_key=True)
student_name = Column(String(50))
gender = Column(String(10))
phone_number = Column(Integer)
branch = Column(String(10))
# create_all method will create a table in database named with student
base_class.metadata.create_all(engine)
# creating session
Session = sessionmaker(bind=engine)
session = Session()
# creating Instance of Student class
# No need to give student_id explicitly. it automatically assigned by Sqlalchemy
# if you given not a problem it will work
sudnt1 = Student(student_name="Alice", gender="Male",
phone_number=123456789, branch="ECE")
sudnt2 = Student(student_name="Kohli", gender="Male",
phone_number=123456789, branch="CSE")
sudnt3 = Student(student_name="Bob", gender="Male",
phone_number=123456789, branch="CSE")
sudnt4 = Student(student_name="Dhoni", gender="Male",
phone_number=123456789, branch="ECE")
# adding Instance to session(adding data to table)
session.add(sudnt1)
session.add(sudnt2)
session.add(sudnt3)
session.add(sudnt4)
# committing changes
session.commit()
# closing connection
session.close()
Student TablePass the Name of a Column as a Parameter in SQLAlchemy Core
Below are the methods and steps by which we can pass the name of a column as a parameter in SQLAlchemy Core:
- By using bindparam()
- By using literal_column()
- By using getattr()
- Updating Data using bindparam() and literal_column()
By using bindparam()
bindparam() in SQLAlchemy core allows us to create named parameters and dynamically pass values to SQL statements or queries.
Syntax: bindparam(name, value=None,type=None)
Parameters:
name : name of the bind parameter
value : default value for the bind parameter (optional)
type : The SQLAlchemy type to be associated with the bind parameter (optional)
Returns: returns a BindParameter object, which represents the bind parameter and its associated properties.
Example: Here, we create a bind parameter "branch_param" with value="CSE" using the bindparam. Then we create a query to select all the student details whose branch column matches the brach_param value.
Python3
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# create Base class
base_class = declarative_base()
# Establish connection
engine = create_engine("mysql+pymysql://userName:password@host:port/dbName")
# model class
class Student(base_class):
__tablename__ = "student"
student_id = Column(Integer, primary_key=True)
student_name = Column(String(50))
gender = Column(String(10))
phone_number = Column(Integer)
branch = Column(String(10))
# creating session
Session = sessionmaker(bind=engine)
session = Session()
# creating branch_param with value equal to CSE
branch_param = bindparam("branch_param", value="CSE")
# creating the query to select the student details
# whose branch column matches with the brach_param value
query = session.query(Student).filter(branch_param == Student.branch)
# executing the query
result = query.all()
print("Bind Param Output"
print("____________________")
for row in result:
# print(row) it print refference of row object
print(row.student_id, row.student_name, row.phone_number, row.branch)
print(row.student_id, row.student_name, row.phone_number, row.branch)
# closing db connection
session.close()
Output
Bindparam OutputBy using literal_column()
In SQLAlchemy Core literal_column() function allows you to include a literal SQL expression or column in your queries. It allows you to include raw SQL expressions or column values directly into your queries.
Syntax: sqlalchemy.sql.expression.literal_column(text)
Parameters:
text: it can be any SQL expression.
Returns: returns a ColumnClause object representing the literal column expression that you have specified.
Example: Here, we are creating a query to select all student details whose branch is ECE. We create a query using query(Student). This sets to select all the rows present in the Student table. Then we apply a filter condition to select all student whose branch is ECE using filter(literal_column("branch")=="ECE"). Here literal_column("branch") represents the branch column in student table. Then we execute the query and print the results.
Note: The argument of literal_column should be present in model class otherwise it givens an error.
Python3
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# create Base class
base_class = declarative_base()
# Establish connection
engine = create_engine("mysql+pymysql://root:Ravi123@localhost/employee_db")
# model class
class Student(base_class):
__tablename__ = "student"
student_id = Column(Integer, primary_key=True)
student_name = Column(String(50))
gender = Column(String(10))
phone_number = Column(Integer)
branch = Column(String(10))
# creating session
Session = sessionmaker(bind=engine)
session = Session()
# creating the query to select the student details
# whose branch is ECE
query = session.query(Student).filter(literal_column("branch") == "ECE")
# executing the query
result = query.all()
print("literal_column output")
print("____________________")
for row in result:
# print(row) it print refference of object
print(row.student_id, row.student_name, row.phone_number, row.branch)
# closing the connection
session.close()
Output
Literal Column outputBy using getattr()
The getattr() is used to retrieve an attribute value from an object dynamically, based on its name. It is Python built-in method not specific to SQLAlchmey.
Python3
# creating the query to select the student details
# whose branch is ECE
query = session.query(Student).filter(getattr(Student, "branch") == "ECE")
# executing the query
result = query.all()
print("getattr output")
print("____________________")
for row in result:
# print(row) it print refference of object
print(row.student_id, row.student_name, row.phone_number, row.branch)
session.close()
Output
getattr outputUpdating Data using bindparam() and literal_column()
In the following example, we update the student's phone number to 987654321 where the student ID is even using bindparam() and literal_column(). First, we create phone_param with the value 987654321. Then, we create the update statement using update(), and in the where clause, we check if the student ID is even or not using literal_column() and the modulo operator. In the value(), we simply update the phone number of the student.
Python3
# bind param
phone_param = bindparam("phone_param", 987654321)
# update query
updateQuery = update(Student).\
where(literal_column("student_id") % 2 == 0).\
values(phone_number=phone_param)
session.execute(updateQuery)
# commit is mendatory without this method data wont be updated
session.commit()
print("student data")
res = session.query(Student)
for s in res:
print(s.student_id, s.student_name, s.phone_number)
# closing connection
session.close()

Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read