Skip to content

Instantly share code, notes, and snippets.

@olgakogan
Last active February 7, 2023 22:49
Show Gist options
  • Save olgakogan/537e543845975453963e to your computer and use it in GitHub Desktop.
Save olgakogan/537e543845975453963e to your computer and use it in GitHub Desktop.
SQL Alchemy Samples
########## CASE IN UPDATE STATEMENT ############
from sqlalchemy import case
# single value modification (the 'else' is not mandatory)
session.query(User).update({User.status : case([(User.status == "pending", "approved")], else_=User.status)}, False)
# multiple values modification
session.query(User).update({User.status : case([(User.status == "pending", "approved"),
(User.status == "waiting", "deprecated_status")])}, False)
########## CONCAT ############
from sqlalchemy.sql.functions import concat
session.query(User).update({ User.department: concat(PREFIX, User.department, SUFFIX)}, False)
########## CAST ############
from sqlalchemy.sql.expression import cast
import sqlalchemy
session.query(User).update({User.name: cast(User.user_id, sqlalchemy.String)}, False)
@peteristhegreat
Copy link

Thanks for posting useful examples!

@reimundklain
Copy link

Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment