SQL and Generic Functions

SQL functions are invoked by using the func namespace. See the tutorial at Working with SQL Functions for background on how to use the func object to render SQL functions in statements.

See also

Working with SQL Functions - in the SQLAlchemy Unified Tutorial

Function API

The base API for SQL functions, which provides for the func namespace as well as classes that may be used for extensibility.

Object NameDescription

AnsiFunction

Define a function in “ansi” format, which doesn’t render parenthesis.

Function

Describe a named SQL function.

FunctionElement

Base for SQL function-oriented constructs.

GenericFunction

Define a ‘generic’ function.

register_function(identifier, fn[, package])

Associate a callable with a particular func. name.

class sqlalchemy.sql.functions.AnsiFunction

Define a function in “ansi” format, which doesn’t render parenthesis.

Class signature

class sqlalchemy.sql.functions.AnsiFunction (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.Function

Describe a named SQL function.

The Function object is typically generated from the func generation object.

  • Parameters:

    • *clauses – list of column expressions that form the arguments of the SQL function call.

    • type_ – optional TypeEngine datatype object that will be used as the return value of the column expression generated by this function call.

    • packagenames

      a string which indicates package prefix names to be prepended to the function name when the SQL is generated. The func generator creates these when it is called using dotted format, e.g.:

      1. func.mypackage.some_function(col1, col2)

See also

Working with SQL Functions - in the SQLAlchemy Unified Tutorial

func - namespace which produces registered or ad-hoc Function instances.

GenericFunction - allows creation of registered function types.

Members

__init__()

Class signature

class sqlalchemy.sql.functions.Function (sqlalchemy.sql.functions.FunctionElement)

class sqlalchemy.sql.functions.FunctionElement

Base for SQL function-oriented constructs.

See also

Working with SQL Functions - in the SQLAlchemy Unified Tutorial

Function - named SQL function.

func - namespace which produces registered or ad-hoc Function instances.

GenericFunction - allows creation of registered function types.

Members

__init__(), alias(), as_comparison(), c, clauses, column_valued(), columns, entity_namespace, exported_columns, filter(), over(), scalar_table_valued(), select(), self_group(), table_valued(), within_group(), within_group_type()

Class signature

class sqlalchemy.sql.functions.FunctionElement (sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ColumnElement, sqlalchemy.sql.expression.FromClause, sqlalchemy.sql.expression.Generative)

  1. See also
  2. [func]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.func "sqlalchemy.sql.expression.func")
  3. [Function](#sqlalchemy.sql.functions.Function "sqlalchemy.sql.functions.Function")
  • method sqlalchemy.sql.functions.FunctionElement.alias(name=None, joins_implicitly=False)

    Produce a Alias construct against this FunctionElement.

    Tip

    The FunctionElement.alias() method is part of the mechanism by which “table valued” SQL functions are created. However, most use cases are covered by higher level methods on FunctionElement including FunctionElement.table_valued(), and FunctionElement.column_valued().

    This construct wraps the function in a named alias which is suitable for the FROM clause, in the style accepted for example by PostgreSQL. A column expression is also provided using the special .column attribute, which may be used to refer to the output of the function as a scalar value in the columns or where clause, for a backend such as PostgreSQL.

    For a full table-valued expression, use the FunctionElement.table_valued() method first to establish named columns.

    e.g.:

    1. >>> from sqlalchemy import func, select, column
    2. >>> data_view = func.unnest([1, 2, 3]).alias("data_view")
    3. >>> print(select(data_view.column))
    4. SELECT data_view
    5. FROM unnest(:unnest_1) AS data_view

    The FunctionElement.column_valued() method provides a shortcut for the above pattern:

    1. >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view")
    2. >>> print(select(data_view))
    3. SELECT data_view
    4. FROM unnest(:unnest_1) AS data_view

    New in version 1.4.0b2: Added the .column accessor

    • Parameters:

      • name – alias name, will be rendered as AS <name> in the FROM clause

      • joins_implicitly

        when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no “cartesian product” warning will be generated. May be useful for SQL functions such as func.json_each().

        New in version 1.4.33.

  1. See also
  2. [Table-Valued Functions]($93605e6ef77d4344.md#tutorial-functions-table-valued) - in the [SQLAlchemy Unified Tutorial]($4406c4fa3e52f66b.md#unified-tutorial)
  3. [FunctionElement.table\_valued()](#sqlalchemy.sql.functions.FunctionElement.table_valued "sqlalchemy.sql.functions.FunctionElement.table_valued")
  4. [FunctionElement.scalar\_table\_valued()](#sqlalchemy.sql.functions.FunctionElement.scalar_table_valued "sqlalchemy.sql.functions.FunctionElement.scalar_table_valued")
  5. [FunctionElement.column\_valued()](#sqlalchemy.sql.functions.FunctionElement.column_valued "sqlalchemy.sql.functions.FunctionElement.column_valued")
  • method sqlalchemy.sql.functions.FunctionElement.as_comparison(left_index, right_index)

    Interpret this expression as a boolean comparison between two values.

    This method is used for an ORM use case described at Custom operators based on SQL functions.

    A hypothetical SQL function “is_equal()” which compares to values for equality would be written in the Core expression language as:

    1. expr = func.is_equal("a", "b")

    If “is_equal()” above is comparing “a” and “b” for equality, the FunctionElement.as_comparison() method would be invoked as:

    1. expr = func.is_equal("a", "b").as_comparison(1, 2)

    Where above, the integer value “1” refers to the first argument of the “is_equal()” function and the integer value “2” refers to the second.

    This would create a BinaryExpression that is equivalent to:

    1. BinaryExpression("a", "b", operator=op.eq)

    However, at the SQL level it would still render as “is_equal(‘a’, ‘b’)”.

    The ORM, when it loads a related object or collection, needs to be able to manipulate the “left” and “right” sides of the ON clause of a JOIN expression. The purpose of this method is to provide a SQL function construct that can also supply this information to the ORM, when used with the relationship.primaryjoin parameter. The return value is a containment object called FunctionAsBinary.

    An ORM example is as follows:

    1. class Venue(Base):
    2. __tablename__ = 'venue'
    3. id = Column(Integer, primary_key=True)
    4. name = Column(String)
    5. descendants = relationship(
    6. "Venue",
    7. primaryjoin=func.instr(
    8. remote(foreign(name)), name + "/"
    9. ).as_comparison(1, 2) == 1,
    10. viewonly=True,
    11. order_by=name
    12. )

    Above, the “Venue” class can load descendant “Venue” objects by determining if the name of the parent Venue is contained within the start of the hypothetical descendant value’s name, e.g. “parent1” would match up to “parent1/child1”, but not to “parent2/child1”.

    Possible use cases include the “materialized path” example given above, as well as making use of special SQL functions such as geometric functions to create join conditions.

    • Parameters:

      • left_index – the integer 1-based index of the function argument that serves as the “left” side of the expression.

      • right_index – the integer 1-based index of the function argument that serves as the “right” side of the expression.

  1. New in version 1.3.
  2. See also
  3. [Custom operators based on SQL functions]($b68ea79e4b407a37.md#relationship-custom-operator-sql-function) - example use within the ORM
  • attribute sqlalchemy.sql.functions.FunctionElement.c

    synonym for FunctionElement.columns.

  • attribute sqlalchemy.sql.functions.FunctionElement.clauses

    Return the underlying ClauseList which contains the arguments for this FunctionElement.

  • method sqlalchemy.sql.functions.FunctionElement.column_valued(name=None, joins_implicitly=False)

    Return this FunctionElement as a column expression that selects from itself as a FROM clause.

    E.g.:

    1. >>> from sqlalchemy import select, func
    2. >>> gs = func.generate_series(1, 5, -1).column_valued()
    3. >>> print(select(gs))
    4. SELECT anon_1
    5. FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) AS anon_1

    This is shorthand for:

    1. gs = func.generate_series(1, 5, -1).alias().column
    • Parameters:

      • name – optional name to assign to the alias name that’s generated. If omitted, a unique anonymizing name is used.

      • joins_implicitly

        when True, the “table” portion of the column valued function may be a member of the FROM clause without any explicit JOIN to other tables in the SQL query, and no “cartesian product” warning will be generated. May be useful for SQL functions such as func.json_array_elements().

        New in version 1.4.46.

  1. See also
  2. [Column Valued Functions - Table Valued Function as a Scalar Column]($93605e6ef77d4344.md#tutorial-functions-column-valued) - in the [SQLAlchemy Unified Tutorial]($4406c4fa3e52f66b.md#unified-tutorial)
  3. [Column Valued Functions]($73be5b0078e482d0.md#postgresql-column-valued) - in the [PostgreSQL]($73be5b0078e482d0.md) documentation
  4. [FunctionElement.table\_valued()](#sqlalchemy.sql.functions.FunctionElement.table_valued "sqlalchemy.sql.functions.FunctionElement.table_valued")
  • attribute sqlalchemy.sql.functions.FunctionElement.columns

    The set of columns exported by this FunctionElement.

    This is a placeholder collection that allows the function to be placed in the FROM clause of a statement:

    1. >>> from sqlalchemy import column, select, func
    2. >>> stmt = select(column('x'), column('y')).select_from(func.myfunction())
    3. >>> print(stmt)
    4. SELECT x, y FROM myfunction()

    The above form is a legacy feature that is now superseded by the fully capable FunctionElement.table_valued() method; see that method for details.

    See also

    FunctionElement.table_valued() - generates table-valued SQL function expressions.

  • attribute sqlalchemy.sql.functions.FunctionElement.entity_namespace

    overrides FromClause.entity_namespace as functions are generally column expressions and not FromClauses.

  • attribute sqlalchemy.sql.functions.FunctionElement.exported_columns

  • method sqlalchemy.sql.functions.FunctionElement.filter(*criterion)

    Produce a FILTER clause against this function.

    Used against aggregate and window functions, for database backends that support the “FILTER” clause.

    The expression:

    1. func.count(1).filter(True)

    is shorthand for:

    1. from sqlalchemy import funcfilter
    2. funcfilter(func.count(1), True)

    New in version 1.0.0.

    See also

    Special Modifiers WITHIN GROUP, FILTER - in the SQLAlchemy Unified Tutorial

    FunctionFilter

    funcfilter()

  • method sqlalchemy.sql.functions.FunctionElement.over(partition_by=None, order_by=None, rows=None, range\=None_)

    Produce an OVER clause against this function.

    Used against aggregate or so-called “window” functions, for database backends that support window functions.

    The expression:

    1. func.row_number().over(order_by='x')

    is shorthand for:

    1. from sqlalchemy import over
    2. over(func.row_number(), order_by='x')

    See over() for a full description.

    See also

    over()

    Using Window Functions - in the SQLAlchemy Unified Tutorial

  • method sqlalchemy.sql.functions.FunctionElement.scalar_table_valued(name, type\=None_)

    Return a column expression that’s against this FunctionElement as a scalar table-valued expression.

    The returned expression is similar to that returned by a single column accessed off of a FunctionElement.table_valued() construct, except no FROM clause is generated; the function is rendered in the similar way as a scalar subquery.

    E.g.:

    1. >>> from sqlalchemy import func, select
    2. >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key")
    3. >>> print(select(fn))
    4. SELECT (jsonb_each(:jsonb_each_1)).key

    New in version 1.4.0b2.

    See also

    FunctionElement.table_valued()

    FunctionElement.alias()

    FunctionElement.column_valued()

  • method sqlalchemy.sql.functions.FunctionElement.select() → Select

    Produce a select() construct against this FunctionElement.

    This is shorthand for:

    1. s = select(function_element)
  • method sqlalchemy.sql.functions.FunctionElement.self_group(against=None)

    Apply a ‘grouping’ to this ClauseElement.

    This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another select(). (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

    As expressions are composed together, the application of self_group() is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

    The base self_group() method of ClauseElement just returns self.

  • method sqlalchemy.sql.functions.FunctionElement.table_valued(*expr, **kw)

    Return a TableValuedAlias representation of this FunctionElement with table-valued expressions added.

    e.g.:

    1. >>> fn = (
    2. ... func.generate_series(1, 5).
    3. ... table_valued("value", "start", "stop", "step")
    4. ... )
    5. >>> print(select(fn))
    6. SELECT anon_1.value, anon_1.start, anon_1.stop, anon_1.step
    7. FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1
    8. >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2))
    9. SELECT anon_1.value, anon_1.stop
    10. FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1
    11. WHERE anon_1.value > :value_1

    A WITH ORDINALITY expression may be generated by passing the keyword argument “with_ordinality”:

    1. >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality")
    2. >>> print(select(fn))
    3. SELECT anon_1.gen, anon_1.ordinality
    4. FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1
    • Parameters:

      • *expr – A series of string column names that will be added to the .c collection of the resulting TableValuedAlias construct as columns. column() objects with or without datatypes may also be used.

      • name – optional name to assign to the alias name that’s generated. If omitted, a unique anonymizing name is used.

      • with_ordinality – string name that when present results in the WITH ORDINALITY clause being added to the alias, and the given string name will be added as a column to the .c collection of the resulting TableValuedAlias.

      • joins_implicitly

        when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no “cartesian product” warning will be generated. May be useful for SQL functions such as func.json_each().

        New in version 1.4.33.

  1. New in version 1.4.0b2.
  2. See also
  3. [Table-Valued Functions]($93605e6ef77d4344.md#tutorial-functions-table-valued) - in the [SQLAlchemy Unified Tutorial]($4406c4fa3e52f66b.md#unified-tutorial)
  4. [Table-Valued Functions]($73be5b0078e482d0.md#postgresql-table-valued) - in the [PostgreSQL]($73be5b0078e482d0.md) documentation
  5. [FunctionElement.scalar\_table\_valued()](#sqlalchemy.sql.functions.FunctionElement.scalar_table_valued "sqlalchemy.sql.functions.FunctionElement.scalar_table_valued") - variant of [FunctionElement.table\_valued()](#sqlalchemy.sql.functions.FunctionElement.table_valued "sqlalchemy.sql.functions.FunctionElement.table_valued") which delivers the complete table valued expression as a scalar column expression
  6. [FunctionElement.column\_valued()](#sqlalchemy.sql.functions.FunctionElement.column_valued "sqlalchemy.sql.functions.FunctionElement.column_valued")
  7. [TableValuedAlias.render\_derived()]($75ae4d183452a412.md#sqlalchemy.sql.expression.TableValuedAlias.render_derived "sqlalchemy.sql.expression.TableValuedAlias.render_derived") - renders the alias using a derived column clause, e.g. `AS name(col1, col2, ...)`

class sqlalchemy.sql.functions.GenericFunction

Define a ‘generic’ function.

A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name. The primary use case for defining a GenericFunction class is so that a function of a particular name may be given a fixed return type. It can also include custom argument parsing schemes as well as additional methods.

Subclasses of GenericFunction are automatically registered under the name of the class. For example, a user-defined function as_utc() would be available immediately:

  1. from sqlalchemy.sql.functions import GenericFunction
  2. from sqlalchemy.types import DateTime
  3. class as_utc(GenericFunction):
  4. type = DateTime()
  5. inherit_cache = True
  6. print(select(func.as_utc()))

User-defined generic functions can be organized into packages by specifying the “package” attribute when defining GenericFunction. Third party libraries containing many functions may want to use this in order to avoid name conflicts with other systems. For example, if our as_utc() function were part of a package “time”:

  1. class as_utc(GenericFunction):
  2. type = DateTime()
  3. package = "time"
  4. inherit_cache = True

The above function would be available from func using the package name time:

  1. print(select(func.time.as_utc()))

A final option is to allow the function to be accessed from one name in func but to render as a different name. The identifier attribute will override the name used to access the function as loaded from func, but will retain the usage of name as the rendered name:

  1. class GeoBuffer(GenericFunction):
  2. type = Geometry()
  3. package = "geo"
  4. name = "ST_Buffer"
  5. identifier = "buffer"
  6. inherit_cache = True

The above function will render as follows:

  1. >>> print(func.geo.buffer())
  2. ST_Buffer()

The name will be rendered as is, however without quoting unless the name contains special characters that require quoting. To force quoting on or off for the name, use the quoted_name construct:

  1. from sqlalchemy.sql import quoted_name
  2. class GeoBuffer(GenericFunction):
  3. type = Geometry()
  4. package = "geo"
  5. name = quoted_name("ST_Buffer", True)
  6. identifier = "buffer"
  7. inherit_cache = True

The above function will render as:

  1. >>> print(func.geo.buffer())
  2. "ST_Buffer"()

New in version 1.3.13: The quoted_name construct is now recognized for quoting when used with the “name” attribute of the object, so that quoting can be forced on or off for the function name.

Class signature

class sqlalchemy.sql.functions.GenericFunction (sqlalchemy.sql.functions.Function)

function sqlalchemy.sql.functions.register_function(identifier, fn, package=’_default’)

Associate a callable with a particular func. name.

This is normally called by GenericFunction, but is also available by itself so that a non-Function construct can be associated with the func accessor (i.e. CAST, EXTRACT).

Selected “Known” Functions

These are GenericFunction implementations for a selected set of common SQL functions that set up the expected return type for each function automatically. The are invoked in the same way as any other member of the func namespace:

  1. select(func.count("*")).select_from(some_table)

Note that any name not known to func generates the function name as is - there is no restriction on what SQL functions can be called, known or unknown to SQLAlchemy, built-in or user defined. The section here only describes those functions where SQLAlchemy already knows what argument and return types are in use.

Object NameDescription

array_agg

Support for the ARRAY_AGG function.

char_length

The CHAR_LENGTH() SQL function.

coalesce

concat

The SQL CONCAT() function, which concatenates strings.

count

The ANSI COUNT aggregate function. With no arguments, emits COUNT *.

cube

Implement the CUBE grouping operation.

cume_dist

Implement the cume_dist hypothetical-set aggregate function.

current_date

The CURRENT_DATE() SQL function.

current_time

The CURRENT_TIME() SQL function.

current_timestamp

The CURRENT_TIMESTAMP() SQL function.

current_user

The CURRENT_USER() SQL function.

dense_rank

Implement the dense_rank hypothetical-set aggregate function.

grouping_sets

Implement the GROUPING SETS grouping operation.

localtime

The localtime() SQL function.

localtimestamp

The localtimestamp() SQL function.

max

The SQL MAX() aggregate function.

min

The SQL MIN() aggregate function.

mode

Implement the mode ordered-set aggregate function.

next_value

Represent the ‘next value’, given a Sequence as its single argument.

now

The SQL now() datetime function.

percent_rank

Implement the percent_rank hypothetical-set aggregate function.

percentile_cont

Implement the percentile_cont ordered-set aggregate function.

percentile_disc

Implement the percentile_disc ordered-set aggregate function.

random

The RANDOM() SQL function.

rank

Implement the rank hypothetical-set aggregate function.

rollup

Implement the ROLLUP grouping operation.

session_user

The SESSION_USER() SQL function.

sum

The SQL SUM() aggregate function.

sysdate

The SYSDATE() SQL function.

user

The USER() SQL function.

class sqlalchemy.sql.functions.array_agg

Support for the ARRAY_AGG function.

The func.array_agg(expr) construct returns an expression of type ARRAY.

e.g.:

  1. stmt = select(func.array_agg(table.c.values)[2:5])

New in version 1.1.

See also

array_agg() - PostgreSQL-specific version that returns ARRAY, which has PG-specific operators added.

Class signature

class sqlalchemy.sql.functions.array_agg (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.char_length

The CHAR_LENGTH() SQL function.

Class signature

class sqlalchemy.sql.functions.char_length (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.coalesce

Class signature

class sqlalchemy.sql.functions.coalesce (sqlalchemy.sql.functions.ReturnTypeFromArgs)

class sqlalchemy.sql.functions.concat

The SQL CONCAT() function, which concatenates strings.

E.g.:

  1. >>> print(select(func.concat('a', 'b')))
  2. SELECT concat(:concat_2, :concat_3) AS concat_1

String concatenation in SQLAlchemy is more commonly available using the Python + operator with string datatypes, which will render a backend-specific concatenation operator, such as :

  1. >>> print(select(literal("a") + "b"))
  2. SELECT :param_1 || :param_2 AS anon_1

Class signature

class sqlalchemy.sql.functions.concat (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.count

The ANSI COUNT aggregate function. With no arguments, emits COUNT *.

E.g.:

  1. from sqlalchemy import func
  2. from sqlalchemy import select
  3. from sqlalchemy import table, column
  4. my_table = table('some_table', column('id'))
  5. stmt = select(func.count()).select_from(my_table)

Executing stmt would emit:

  1. SELECT count(*) AS count_1
  2. FROM some_table

Class signature

class sqlalchemy.sql.functions.count (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.cube

Implement the CUBE grouping operation.

This function is used as part of the GROUP BY of a statement, e.g. Select.group_by():

  1. stmt = select(
  2. func.sum(table.c.value), table.c.col_1, table.c.col_2
  3. ).group_by(func.cube(table.c.col_1, table.c.col_2))

New in version 1.2.

Class signature

class sqlalchemy.sql.functions.cube (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.cume_dist

Implement the cume_dist hypothetical-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is Numeric.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.cume_dist (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.current_date

The CURRENT_DATE() SQL function.

Class signature

class sqlalchemy.sql.functions.current_date (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.current_time

The CURRENT_TIME() SQL function.

Class signature

class sqlalchemy.sql.functions.current_time (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.current_timestamp

The CURRENT_TIMESTAMP() SQL function.

Class signature

class sqlalchemy.sql.functions.current_timestamp (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.current_user

The CURRENT_USER() SQL function.

Class signature

class sqlalchemy.sql.functions.current_user (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.dense_rank

Implement the dense_rank hypothetical-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is Integer.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.dense_rank (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.grouping_sets

Implement the GROUPING SETS grouping operation.

This function is used as part of the GROUP BY of a statement, e.g. Select.group_by():

  1. stmt = select(
  2. func.sum(table.c.value), table.c.col_1, table.c.col_2
  3. ).group_by(func.grouping_sets(table.c.col_1, table.c.col_2))

In order to group by multiple sets, use the tuple_() construct:

  1. from sqlalchemy import tuple_
  2. stmt = select(
  3. func.sum(table.c.value),
  4. table.c.col_1, table.c.col_2,
  5. table.c.col_3
  6. ).group_by(
  7. func.grouping_sets(
  8. tuple_(table.c.col_1, table.c.col_2),
  9. tuple_(table.c.value, table.c.col_3),
  10. )
  11. )

New in version 1.2.

Class signature

class sqlalchemy.sql.functions.grouping_sets (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.localtime

The localtime() SQL function.

Class signature

class sqlalchemy.sql.functions.localtime (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.localtimestamp

The localtimestamp() SQL function.

Class signature

class sqlalchemy.sql.functions.localtimestamp (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.max

The SQL MAX() aggregate function.

Class signature

class sqlalchemy.sql.functions.max (sqlalchemy.sql.functions.ReturnTypeFromArgs)

class sqlalchemy.sql.functions.min

The SQL MIN() aggregate function.

Class signature

class sqlalchemy.sql.functions.min (sqlalchemy.sql.functions.ReturnTypeFromArgs)

class sqlalchemy.sql.functions.mode

Implement the mode ordered-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is the same as the sort expression.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.mode (sqlalchemy.sql.functions.OrderedSetAgg)

class sqlalchemy.sql.functions.next_value

Represent the ‘next value’, given a Sequence as its single argument.

Compiles into the appropriate function on each backend, or will raise NotImplementedError if used on a backend that does not provide support for sequences.

Class signature

class sqlalchemy.sql.functions.next_value (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.now

The SQL now() datetime function.

SQLAlchemy dialects will usually render this particular function in a backend-specific way, such as rendering it as CURRENT_TIMESTAMP.

Class signature

class sqlalchemy.sql.functions.now (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.percent_rank

Implement the percent_rank hypothetical-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is Numeric.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.percent_rank (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.percentile_cont

Implement the percentile_cont ordered-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is the same as the sort expression, or if the arguments are an array, an ARRAY of the sort expression’s type.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.percentile_cont (sqlalchemy.sql.functions.OrderedSetAgg)

class sqlalchemy.sql.functions.percentile_disc

Implement the percentile_disc ordered-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is the same as the sort expression, or if the arguments are an array, an ARRAY of the sort expression’s type.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.percentile_disc (sqlalchemy.sql.functions.OrderedSetAgg)

class sqlalchemy.sql.functions.random

The RANDOM() SQL function.

Class signature

class sqlalchemy.sql.functions.random (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.rank

Implement the rank hypothetical-set aggregate function.

This function must be used with the FunctionElement.within_group() modifier to supply a sort expression to operate upon.

The return type of this function is Integer.

New in version 1.1.

Class signature

class sqlalchemy.sql.functions.rank (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.rollup

Implement the ROLLUP grouping operation.

This function is used as part of the GROUP BY of a statement, e.g. Select.group_by():

  1. stmt = select(
  2. func.sum(table.c.value), table.c.col_1, table.c.col_2
  3. ).group_by(func.rollup(table.c.col_1, table.c.col_2))

New in version 1.2.

Class signature

class sqlalchemy.sql.functions.rollup (sqlalchemy.sql.functions.GenericFunction)

class sqlalchemy.sql.functions.session_user

The SESSION_USER() SQL function.

Class signature

class sqlalchemy.sql.functions.session_user (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.sum

The SQL SUM() aggregate function.

Class signature

class sqlalchemy.sql.functions.sum (sqlalchemy.sql.functions.ReturnTypeFromArgs)

class sqlalchemy.sql.functions.sysdate

The SYSDATE() SQL function.

Class signature

class sqlalchemy.sql.functions.sysdate (sqlalchemy.sql.functions.AnsiFunction)

class sqlalchemy.sql.functions.user

The USER() SQL function.

Class signature

class sqlalchemy.sql.functions.user (sqlalchemy.sql.functions.AnsiFunction)