r"""Produce a ``CASE`` expression. The ``CASE`` construct in SQL is a conditional object that acts somewhat analogously to an "if/then" construct in other languages. It returns an instance of :class:`.Case`. :func:`.case` in its usual form is passed a series of "when" construc
(
*whens: Union[
typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any]
],
value: Optional[Any] = None,
else_: Optional[Any] = None,
)
| 747 | |
| 748 | |
| 749 | def case( |
| 750 | *whens: Union[ |
| 751 | typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any] |
| 752 | ], |
| 753 | value: Optional[Any] = None, |
| 754 | else_: Optional[Any] = None, |
| 755 | ) -> Case[Any]: |
| 756 | r"""Produce a ``CASE`` expression. |
| 757 | |
| 758 | The ``CASE`` construct in SQL is a conditional object that |
| 759 | acts somewhat analogously to an "if/then" construct in other |
| 760 | languages. It returns an instance of :class:`.Case`. |
| 761 | |
| 762 | :func:`.case` in its usual form is passed a series of "when" |
| 763 | constructs, that is, a list of conditions and results as tuples:: |
| 764 | |
| 765 | from sqlalchemy import case |
| 766 | |
| 767 | stmt = select(users_table).where( |
| 768 | case( |
| 769 | (users_table.c.name == "wendy", "W"), |
| 770 | (users_table.c.name == "jack", "J"), |
| 771 | else_="E", |
| 772 | ) |
| 773 | ) |
| 774 | |
| 775 | The above statement will produce SQL resembling: |
| 776 | |
| 777 | .. sourcecode:: sql |
| 778 | |
| 779 | SELECT id, name FROM user |
| 780 | WHERE CASE |
| 781 | WHEN (name = :name_1) THEN :param_1 |
| 782 | WHEN (name = :name_2) THEN :param_2 |
| 783 | ELSE :param_3 |
| 784 | END |
| 785 | |
| 786 | When simple equality expressions of several values against a single |
| 787 | parent column are needed, :func:`.case` also has a "shorthand" format |
| 788 | used via the |
| 789 | :paramref:`.case.value` parameter, which is passed a column |
| 790 | expression to be compared. In this form, the :paramref:`.case.whens` |
| 791 | parameter is passed as a dictionary containing expressions to be |
| 792 | compared against keyed to result expressions. The statement below is |
| 793 | equivalent to the preceding statement:: |
| 794 | |
| 795 | stmt = select(users_table).where( |
| 796 | case({"wendy": "W", "jack": "J"}, value=users_table.c.name, else_="E") |
| 797 | ) |
| 798 | |
| 799 | The values which are accepted as result values in |
| 800 | :paramref:`.case.whens` as well as with :paramref:`.case.else_` are |
| 801 | coerced from Python literals into :func:`.bindparam` constructs. |
| 802 | SQL expressions, e.g. :class:`_expression.ColumnElement` constructs, |
| 803 | are accepted |
| 804 | as well. To coerce a literal string expression into a constant |
| 805 | expression rendered inline, use the :func:`_expression.literal_column` |
| 806 | construct, |