Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SqlAlchemy concat two columns for `ilike` query

I’m trying to recreate the following (PostgreSQL) query in SqlAlchemy:

select
       u.first_name,
       u.last_name,
from users u
where ((u.first_name ||' '|| u.last_name) ilike '%Mark Zuckerberg%')

Essentially I’m concatenating the two columns then searching by the full name, which in my case is passed in via a user query.

Is there a way to do this in SqlAlchemy?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Example, how you can do it

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)


# Create the SQLAlchemy engine
engine = create_engine('postgresql://username:password@host:port/database_name')

# Create a session
Session = sessionmaker(bind=engine)
session = Session()

# Concatenate the first_name and last_name columns
full_name = User.first_name + ' ' + User.last_name

# Perform the query
query = session.query(User.first_name, User.last_name).filter(full_name.ilike('%Mark Zuckerberg%'))

# Retrieve the results
results = query.all()

# Print the results
for first_name, last_name in results:
    print(f'First Name: {first_name}, Last Name: {last_name}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading