Open In App

PostgreSQL ILIKE query with SQLAlchemy

Last Updated : 02 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The ILIKE is a pattern-matching approach provided by PostgreSQL. It is similar to the LIKE operator but it simply ignores the case. It is case-sensitive. For more understanding, you can visit this article on ILIKE operators. In this article, we will cover about PostgreSQL ILIKE query with SQLAlchemy.

PostgreSQL ILIKE Query

Step 1: Installation

We are using SQLAlchemy, psycopg2, pgAdmin, and Python. To install all these please refer to

Step 2: Creating Database and Table

We have created one database called SQLAlchemyPractice and a Table named Movies. We have inserted some dummy data using PgAdmin. We use a select command in SQL to display the resultset.

HarryPotterNewDB

Data Present in Movies table

Step 3: Writing the Code

Importing Libraries: We are creating a simple program that fetches the data from the database using ilike_op() method in python. These are the libraries that we are going to use in our program. We sqlalchemy library that lubricates the transmission between python program and database.

import sqlalchemy as db
from sqlalchemy import create_engine
from sqlalchemy import URL
from sqlalchemy.sql.operators import ilike_op,like_op

Making Connection With Database: Here we are simply initializing our connection string. Psycopg2 is a postgresql database driver, it is used to perform operations on PostgreSQL using python. After that we provide username, password, host and database name. We pass connection string as a parameter in create_engine() to create an engine object. This will establish a connection with PostgreSQL.

url_object = URL.create(
"postgresql+psycopg2",
username="postgres",
password="gfg@123",
host="localhost",
database="SQLAlchemyPractice",
)
engine = create_engine(url_object)

Defining the Table Structure: Now we use db.MetaData() to define the structure of Table in terms of python data structure. After that we use db.Table() to define the data types of our attributes.

metadata_obj = db.MetaData()
db.Table(
'Movies',
metadata_obj,
db.Column('id', db.Integer, primary_key=True),
db.Column('Movietitle', db.String(50)),
db.Column('genre', db.String(15))
)

Syntax of like_op() and ilike_op()

  • like_op(attribute, expression)
  • ilike_op(attribute, expression)

attribute : Here we need to filter the data on the basis of Movie Title, So we use MOVIES.c.Movietitle.
expression : Here we need to provide the pattern of the data that we want to filter out. “%” is a wild card which represents zero, one or multiple characters. The pattern “h%” specifies that it will fetch all the Movietitle start with “h”.

Function for Filtering Movie Names Starting with ‘h’: Now we simply create MOVIES bucket and assign Movies matadata into it. We use filter() method, that filters the given sequence with the help of function that passed as a first argument. Here we pass ilike_op() as an argument. We use for loop in python to print our result set.

MOVIES = metadata_obj.tables['Movies']
query = db.select(MOVIES).filter(ilike_op(MOVIES.c.Movietitle, 'h%'))
for record in result:
print("\n", record)

Full Implementation for Filtering Using LIKE for Names of Movies with ‘h’

Python3




import sqlalchemy as db
from sqlalchemy import create_engine
from sqlalchemy import URL
from sqlalchemy.sql.operators import ilike_op,like_op
 
url_object = URL.create(
    "postgresql+psycopg2",
    username="postgres",
    password="xyz@123",
    host="localhost",
    database="SQLAlchemyPractice",
)
 
engine = create_engine(url_object)
metadata_obj = db.MetaData()
 
db.Table(
    'Movies',                                       
    metadata_obj,                                   
    db.Column('id', db.Integer, primary_key=True), 
    db.Column('Movietitle', db.String(50)),                   
    db.Column('genre', db.String(15))        
)
 
MOVIES = metadata_obj.tables['Movies']
query  = db.select(MOVIES).filter(like_op(MOVIES.c.Movietitle, f'h%'))
result = engine.connect().execute(query).fetchall()
 
for record in result:
    print("\n", record)


Output

It fetches all the movie titles start with ‘h’.

HarryPotterWithLike

Output using like_op()

Implementation for Filtering Using ILIKE for Movie Names with ‘h’ and ‘H’

As you can see it only fetches Movietitle having a small case ‘h’ as it is case-sensitive. Now, we want to ignore the case of characters. We can use SQLAlchemy ilike_op() method on ‘Movietitle’. It has same syntax of like_op() method.

Python3




import sqlalchemy as db
from sqlalchemy import create_engine
from sqlalchemy import URL
from sqlalchemy.sql.operators import ilike_op,like_op
 
url_object = URL.create(
    "postgresql+psycopg2",
    username="postgres",
    password="xyz@123",
    host="localhost",
    database="SQLAlchemyPractice",
)
 
engine = create_engine(url_object)
metadata_obj = db.MetaData()
 
db.Table(
    'Movies',                                       
    metadata_obj,                                   
    db.Column('id', db.Integer, primary_key=True), 
    db.Column('Movietitle', db.String(50)),                   
    db.Column('genre', db.String(15))        
)
         
MOVIES = metadata_obj.tables['Movies']
query  = db.select(MOVIES).filter(ilike_op(MOVIES.c.Movietitle, 'h%'))
result = engine.connect().execute(query).fetchall()
 
for record in result:
    print("\n", record)


Output:

It fetches all the movie titles start with ‘h’ and ‘H’.

HarryPotterWithILike

Output using ilike_op()

Demonstration

For complete explanation of code, you can go through this video tutorial.



Similar Reads

PostgreSQL Query To View with SQLAlchemy
As a software developer, it is a common task to query a PostgreSQL view. Using views which is a virtual table representing the output of a SQL query, is considered to be an efficient way when dealing with a relational database. This article covers how to query a PostgreSQL view using SQLAlchemy in Python. Before directly moving to the demonstration
9 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 connections. This SQLAlchemy engine is a global object which
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 installed using - pip install flask-sqlalchemyExample Befo
2 min read
SQLAlchemy ORM - Query
In this article, we will see how to query using SQLAlchemy ORM in Python. To follow along with this article, we need to have sqlalchemy and anyone database installed in our system. We have used the MySQL database for this article's understanding. Created a Profile table and a Students table: Here we are going to cover the following methods: add_col
10 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, Group by is performed using a function called sum(),
3 min read
Python SQLAlchemy - Write a query where a column contains a substring
In this article, we discussed how to extract the column values containing substring in SQLAlchemy against a PostgreSQL database in python. In SQLAlchemy, generic functions like SUM, MIN, MAX, are invoked like conventional SQL functions using the func attribute. Some common functions used in SQLAlchemy are contains, count, cube, current_date, curren
2 min read
Single column query results in SQLAlchemy
In this post, we are going to deep dive into the results obtained when we run a single-column query using SQLAlchemy. SQLAlchemy is an awesome and easy-to-use python module that is used to connect python and SQL databases together increasing the powers of any programmer. To install SQLAlchemy, run the following command in your terminal: pip install
3 min read
How to change datetime to string in SQLAlchemy query?
In this article, we are going to change DateTime to string in sqlalchemy query in the python programming language. Database used: Installation Syntax to install sqlalchemy and pymysql: pip install sqlalchmey pymysql Note: pymysql is a dependency of sqlalchemy which we need to install for this post First of all, we need to import the module and conn
2 min read
SQLAlchemy db.session.query()
In SQLAlchemy, session.query() can be used as a filter in a query to specify criteria for which rows should be returned. This is done using the expression module and the filter method of the query object. The expression module allows you to create an expression that can be used in a query. This can include mathematical equations, as well as other t
5 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
Practice Tags :